- % 10 == 7: # Check if the number ends in 7 → # % 10 == → checks if number ends in a digit
- # Function to calculate the product of prime numbers between 90 and 110
defproduct_of_primes_between_90_and_110():
product = 1 # Start with a product of 1
for num in range(90, 111): # Iterate through numbers from 90 to 110
if is_prime(num): # Check if the number is prime
product *= num # Multiply it to the product return product
# Calculate and print the result
result = product_of_primes_between_90_and_110()
print(f"The product of prime numbers between 90 and 110 is: {result}")
- # sum in range: Function to calculate the sum of numbers between 4000 and 8000 divisible by 8
but not by 12
def sum_in_range():
total_sum = 0
for num in range(4000, 8001): # Range from 4000 to 8000 (inclusive)
if num % 8 == 0 and num % 12 != 0: # Divisible by 8 but not by 12
total_sum += num
return total_sum
# Calculate and print the result
result = sum_in_range()print(result)
- # Consider the series of fractions 8/1, 9/2, 10/3, 11/4, etc. where the numerator is 7 more than the denominator. Note that
this series is decreasing. What is the value to five decimal places of the first number in the series that is below 1.2
(expressed as a floating point number)?
def find_fraction():
denominator = 1
while True:
numerator = denominator + 7
fraction = numerator / denominator
if fraction < 1.2:
return round(fraction, 5)
denominator += 1
print(find_fraction())
- # How many times do the letters a, A, c, C, w, or W appear in the passage from Shakespeare's Henry V that
is stored in the string that is preloaded
count = 0 for char in s: if char in ['a', 'A', 'c', 'C', 'w', 'W']: count += 1
print(count)
- # reverse an integer
def reverse_int(n):
return int(str(n)[::-1])
n = 123456
reversed_n = reverse_int(n)
print ("The reversed integer is:", reversed_n)
Sorting alphabetically:
w1 = input("Enter a word: ")
w2 = input("Enter another word: ")
if (w1>w2): w2, w1 = w1, w2
print(f"Your words in alphabetical order are {w1} and {w2}.")
Soting by length:
w1 = input("Enter a word: ")
w2 = input("Enter another word: ")
if (len(w1)>len(w2)): w2, w1 = w1, w2
print(f"Your words order by length are {w1} and {w2}.")
Ed Exercise: Matching a Number. Write a program that generates a random number between 1 and 3. Ask the user to input a
number between 1 and 3 as well. If the numbers match, output "you win!" otherwise output "better luck next time."
import random
compnum = [Link](1,3)
usernum = int(input("Enter an integer (1-3): "))
if usernum == compnum:
print ("you win!!")
else:
print ("try again!")
Ed Exercise: Matching a Number (with Validation). Modify the previous program so that it makes sure that the number the user
enters is actually between 1 and 3. If they enter a number out of range, print "Out of range!"" and prompt them again.
import random
compnum = [Link](1,3)
while True:
usernum = int(input("Enter an integer (1-3): "))
if (usernum>=1) and (usernum<=3): break
print ("Out of range!")
if usernum == compnum:
print ("you win :)")
else:
print ("try again :(")
Example #3. Qualifying for a Credit Card. The program on the right qualifies the user for a credit card. Users must meet the
following criteria:
- Make at least $60,000 per year.
- Their rent payment must not be more than 5% of their total salary per month (i.e. 3000 is the max rent that they can pay
while making $60,000 per year)
- However, if they own their home you do not need to take their monthly house payment into account
print ("Credit card qualifier")
salary = int(input("How much do you make per year? "))
own = input("Do you own your home? (y/n) ")
if own == 'y':
if salary >= 60000:
print ("You qualify!")
else:
print ("You don't qualify. You need to make at least 60,000 per year and own your home.")
else:
if salary < 60000:
print ("You don't qualify. You need to make at least 60,000 per year and own your home.")
else:
rent = int(input("How much do you pay in rent per month? "))
if rent > 0.05 * salary:
print ("Sorry, you don't qualify. Your rent is too high")
else:
print ("You qualify!")
Ed Exercise: Grading. Write a program that asks the user for the scores on three tests, each between 0 and 100, and a score on the
homework, also between 0-100. Calculate the average test score and then the overall score is the average of the average test score
and the homework score. Print out the grade based on the overall score as follows: over 90, A, over 80, B, over 70, C, over 65, D,
otherwise F.
test1 = float(input("Test 1: "))
test2 = float(input("Test 2: "))
test3 = float(input("test 3: "))
homework = float(input("Homework: "))
test_avg = (test1 + test2 + test3) / 3
class_avg = (test_avg + homework) / 2
print ("overall score: ", format(class_avg, '.2f'))
print ("letter grade: ", end='')
if class_avg > 90:
print ("A")
elif class_avg > 80:
print ("B")
elif class_avg > 70:
print ("C")
elif class_avg > 65:
print ("D")
else:
print ("F")
Ed Exercise: Unit Conversion. Ask the user for a number of square feet. Then convert to acres by dividing by 43560 and output
the number of acres.
sq_ft = int(input("Sqaure feet: "))
acres = sq_ft / 43560
print ("In acres:", acres)
Ed Exercise: Sum of Primes. Write a program to calculate the sum of the prime numbers between 1000 and 2000 and print it out.
def prime(n):
for i in range(2,int(n**0.5)+1):
if (n%i==0):
return False
return True
total =0
for n in range(1001,2001,2):
if prime(n):
total+=n
print(total)
Ed Exercise: Finding a Prime Number. Find the 11,235th prime number and print it out. The first three are 2, 3 and 5.
def prime(n):
for i in range(2,int(n**0.5)+1):
if (n%i==0):
return False
return True
count=2
k=3
while True:
k+=2
if prime(k):
count+=1
if (count==11235):
print(k)
break