def factorial(n):
# Selection
if n < 0:
return "Factorial is not defined for negative numbers"
# in case negative numbers are inputted...
elif n == 0 or n == 1:
# "else if" sets a condition to be met, and if it is met, the code should return 1
return 1
else:
result = 1
for i in range(2, n + 1):
#iterates through the list, from 2 to n inclusive - 1 is not counted, n*1 = n
result *= i
#multiplies the current value of result by i
# i is sort of like the index, or the number assigned to each value in the list, starting from 0
return result
def main():
try:
# Get user input for the numbers as a comma-separated list
user_input = input("Enter a list of non-negative integers (comma-separated): ")
numbers = [int(num.strip()) for num in user_input.split(',')]
# Calculate and print factorial for each number
for number in numbers:
# Calculate factorial for each number, iterates through the list
result = factorial(number)
if isinstance(result, int):
print(f"The factorial of {number} is: {result}")
# Selection, makes sure the result is actually an integer before printing
else:
print(f"The factorial for {number} is not defined (negative input).")
except ValueError:
print("Invalid input. Please enter a valid list of non-negative integers.")
if __name__ == "__main__":
main()
The factorial of 2 is: 2
The factorial of 0 is: 1
The factorial of 1 is: 1
The factorial of 5 is: 120
The factorial for -3 is not defined (negative input).
Scenario: You’re in your math test and you forgot how to graph the parent function of 3(x+2)-4. Input a list of x-values to figure out the y-values and print the results of what you get so you can graph the function and get an A on your math test!
y_values = []
for x in range(0,11):
y_values.append(3*(x+2)-4)
for y in y_values:
print(y)
2
5
8
11
14
17
20
23
26
29
32
num1 = 40
num2 = num1 / 2
num3 = 5 * num2 + 3
result = num2 % 3 * num1 + 4 - num3 / 2
print (result)
32.5
What will the code below print?
num1 = 20
num2 = num1 /2
num3 = num2 * 10 + 3
print(num3)
103.0
Write a code that can add, subtract, multiply, divide, and MOD numbers. Try adding them in the same line and seeing what they do. Try adding variables to your hack #2.
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print(f"{num1} + {num2} = {num1 + num2}")
print(f"{num1} - {num2} = {num1 - num2}")
print(f"{num1} * {num2} = {num1 * num2}")
print(f"{num1} * {num2} % {num2} + {num1} // {num2} ** {num1} - {num1} = {num1 * num2 % num2 + num1 // num2 ** num1 - num1}")
55 + 38 = 93
55 - 38 = 17
55 * 38 = 2090
55 * 38 % 38 + 55 // 38 ** 55 - 55 = -55
len ("APCSP")
5
concat = "AP" + "CSP"
# Concat is simply a variable
print(concat)
APCSP
Find the number of characters in your last name using len. Use concat to merge your first and last name together. Use Substring to show only the 3rd to 6th characters.
#Find the number of characters in your last name using len.
length = len("Bharadwaj")
print(length)
# Use concat to merge your first and last name together.
concat = "Aditi" + "Bharadwaj"
print(concat)
# Use Substring to show only the 3rd to 6th characters.
# be sure to start at 2 because it starts counting at 0
substring = concat[2:6]
print(substring)
print("Number of letters in my last name: " + str(len("Singamneni")))
concat2 = "Akhil" + "Singamneni"
sub = concat2[2:6]
print(concat2)
print(sub)
9
AditiBharadwaj
itiB
Number of letters in my last name: 10
AkhilSingamneni
hilS
A palindrome is a string that reads the same from right to left as left to right. For example, 2112 and mom are palindromes
def palindrome(input_str):
# Remove spaces and convert the string to lowercase
clean_str = input_str.replace(" ", "").lower()
# Check if the cleaned string is equal to its reverse
return clean_str == clean_str[::-1]
print(palindrome("taco cat")) # True
print(palindrome("hi")) # False
True
False
Python is a high-level programming language. When you write an algorithm in Python, you are essentially creating a set of instructions that a computer can follow to solve a specific problem.
name = "Eshika"
age = 15
print("Name:", name)
print("Age:", age)
College Board Pseudo Code is a simplified, high-level representation of an algorithm that is designed to be easy to understand. Pseudo code uses a mixture of natural language and programming-like constructs to describe the algorithm’s logic without specifying a particular programming language.
OUTPUT “Name:”, name OUTPUT “Age:”, age </span>
If the robot leaves the grid, the program will end Command MOVE_FORWARD() moves the robot one block in the direction its facing Command ROTATE_LEFT() moves the robot left in place Command ROTATE_RIGHT() makes the robot do an in place right turn Command CAN_MOVE(direction) makes it so that if there is an open space in the relative direction the robot is facing, the robot goes there, can be any direction
MOVE_FORWARD()
ROTATE_LEFT()
MOVE_FORWARD()
ROTATE_RIGHT()
AND gate, OR gate, NOT gate, NAND gate, NOR gate, XOR gate, and XNOR gate.
What is a logic gate?: Logic gates are used in circuits to make decisions based on a combination of digital signals beign inputed. The concept of logic gates revolves around Boolean algebra as well as binary. It is basically how zero represents the false condition and 1 represents True. Think of it as a switch where if it is at 0, the switch is turned off while if it is 1, then the lightbulb will turn on.
The AND gate requires both inputs to be 1 or true so the end output is true. In other words, the output is 1 only when both inputs one AND two are 1.
age= 15
if age>2 and type(age)==int:
print(age)
age=13
if age>2 and type(age)==str:
print(age)
15
Use an algorithm to find certain values of the Fibonacci sequence. For example, your code should output the nth index in the sequence. An example of how the sequence works is 0,1,1,2,3,5,8,13. The pattern is you add the previous 2 numbers together to get the new number.
#Homework
fibonacci = []
#Create the fibonacci list
user = int(input("Enter how many numbers of the fibonacci sequence you want: "))
#Use iteration to get all numbers of the fibonacci sequence up to a specified upper bound
def fibonacci_iter(num):
for index in range(0, user + 1):
if index == 0:
fibonacci.append(0)
elif index == 1:
fibonacci.append(1)
else:
fibonacci.append(fibonacci[index-2]+fibonacci[index-1])
#Set an upper bound for the number value
user_input = int(input("Input a number you want to set as the highest level: "))
for num in fibonacci:
if num < user_input:
print(num)
#Mathematically determine fibonacci's number at the input num
def get_fibonacci(user):
print(f"\nThe final number of the fibonacci sequence is around {(1.618**user - (1-1.618) ** user) / 5**1/2}")
#Use recursion to recurse through function until we get the num desired by user :0
def fibonacci_recursive(num):
if num <= 0:
return 0
elif num == 1:
return 1
else:
return fibonacci_recursive(num - 1) + fibonacci_recursive(num - 2)
#Print output by callin da functions
fibonacci_iter(user)
get_fibonacci(user)
fibonacci_recursive(user)
0
1
1
2
3
5
8
13
21
The final number of the fibonacci sequence is around 55
55