Week_1_SamplePythonPrograms
Week_1_SamplePythonPrograms
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(i,"times",num//i,"is",num)
break
else:
else:
2. Program make a simple calculator that can add, subtract, multiply and divide
using functions
# This function adds two numbers
return x + y
return x - y
return x * y
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
print(num1,"-",num2,"=", subtract(num1,num2))
print(num1,"*",num2,"=", multiply(num1,num2))
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
factorial = 1
if num < 0:
else:
factorial = factorial*i
5. Write a program to prompt for a score between 0.0 and 1.0. If the score is out
of range, print an error message. If the score is between 0.0 and 1.0, print a
grade using the following table:
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
Run the program repeatedly as shown above to test the various, different values for input.
try:
score = float(input1) #Only allows input floats
except:
print('Bad score')
quit()
if score > 0 and score < 1: #Scores must be between 0.0 and 1.0
if score >= .9:
print('A')
elif score >= .8:
print('B')
elif score >= .7:
print('C')
elif score >= .6:
print('D')
else:
print('F')
else:
print('Bad score')
6. Rewrite the grade program from previous chapter using a function called
computegrade that takes a score as its parameter and returns a grade as a
string.
def computegrade(score):
if score > 0 and score < 1:
if score >= .9:
print('A')
elif score >= .8:
print('B')
elif score >= .7:
print('C')
elif score >= .6:
print('D')
else:
print('F')
else:
print('Bad score')
7. Generating random numbers.Run the program on your system and see what
numbers you get. Run the program more than once and see what numbers you
get.
import random
for i in range(10):
x = random.random()
print(x)
8. Write a program which repeatedly reads numbers until the user enters
"done". Once "done" is entered, print out the total, count, and average of the
numbers. If the user enters anything other than a number, detect their mistake
using try and except and print an error message and skip to the next number.
total = 0
try:
except:
print('Invalid input')
9. Write a program to open the file words.txt and read it line by line. For each
line, split the line into a list of words using the split function.For each word,
check to see if the word is already in a list. If the word is not in the list, add it to
the list. When the program completes, sort and print the resulting words in
alphabetical order.
myList = []
fhand = open('words.txt')