In [ ]:
# average1.py
# A program to average a set of numbers
# Illustrates counted loop with accumulator
def avg():
n = input("How many numbers do you have? ")
sum = 0.0
for i in range(n):
x = input("Enter a number >> ")
sum = sum + x
print "\nThe average of the numbers is", sum / n
avg()
In [ ]:
# average2.py
# A program to average a set of numbers
# Illustrates interactive loop with two accumulators
def avg():
moredata = "yes"
sum = 0.0
count = 0
while moredata[0] == 'y':
x = input("Enter a number to average >> ")
sum = sum + x
count = count + 1
moredata = raw_input("Do you have more numbers (yes or no)? ")
print "\nThe average of the numbers is", sum / count
avg()
In [ ]:
# average3.py
# A program to average a set of numbers
# Illustrates sentinel loop using negative input as sentinel
def avg():
sum = 0.0
count = 0
x = input("Enter a number (negative to quit) >> ")
while x >= 0:
sum = sum + x
count = count + 1
x = input("Enter a number (negative to quit) >> ")
print "\nThe average of the numbers is", sum / count
avg()
In [ ]:
# average4.py
# A program to average a set of numbers
# Illustrates sentinel loop using empty string as sentinel
def avg():
sum = 0.0
count = 0
xStr = raw_input("Enter a number (<Enter> to quit) >> ")
while xStr != "":
x = eval(xStr)
sum = sum + x
count = count + 1
xStr = raw_input("Enter a number (<Enter> to quit) >> ")
print "\nThe average of the numbers is", sum / count
avg()
In [ ]:
def isOdd(num):
check = int(num) % 2
## print check
if check == 1:
return 1
if check == 0:
return 0
def sumOdd():
odd_count = 0
num_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
for item in num_list:
check = isOdd(item)
if check == 1:
odd_count = odd_count + item
else:
pass
print odd_count
sumOdd()
In [ ]:
##sumOdd 2.0 --> only sum single digit odd numbers
def isOdd(num):
check = int(num) % 2
if check == 1:
return True
if check == 0:
return False
def sumOdd():
odd_count = 0
num_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
for item in num_list:
check = isOdd(item)
if check == True and item < 10:
odd_count = odd_count + item
else:
pass
print odd_count
sumOdd()