Contents
- average2.py
- average2_withmain.py
- flow_example.py
- mystery.py
- oldmac.py
average2.py 1/5
[top][prev][next]
# Program to find the average of two numbers
# by Sara Sprenkle
def average2(num1, num2):
"""
Parameters: two numbers to be averaged
Returns the average of two numbers
"""
average = (num1 + num2)/2
return average
print("This program will find the average of two numbers.")
print()
num1 = eval(input("Enter the first number: " ))
num2 = eval(input("Enter the second number: "))
# calculate the average of the two numbers
average = average2(num1, num2)
print("The average of", num1, "and", num2, "is", average)
average2_withmain.py 2/5
[top][prev][next]
# Program to find the average of two numbers.
# Demonstrates using a main function.
# by Sara Sprenkle
def main():
print("This program will find the average of two numbers.")
print()
num1 = eval(input("Enter the first number: " ))
num2 = eval(input("Enter the second number: "))
# calculate the average of the two numbers
average = average2(num1, num2)
print("The average of", num1, "and", num2, "is", average)
def average2(num1, num2):
"""
Parameters: two numbers to be averaged
Returns the average of two numbers
"""
average = (num1 + num2)/2
return average
main()
flow_example.py 3/5
[top][prev][next]
# Example of program flow
# Sara Sprenkle
def max(num1, num2):
result = 0
if num1 >= num2:
result = num1
else:
result = num2
return result
x = 12
y = float(input("Enter a number: "))
z = max(x, y)
print("The max is", z)
mystery.py 4/5
[top][prev][next]
# Mystery Program
# Used to demonstrate variable lifetimes and scope
def main():
x = 10
sum = sumEvens( x )
print("The sum of even #s up to", x, "is", sum)
def sumEvens(limit):
total = 0
for x in range(0, limit, 2):
total += x
return total
main()
oldmac.py 5/5
[top][prev][next]
# Print out verses of the song Old MacDonald
# Sara Sprenkle
BEGIN_END = "Old McDonald had a farm"
EIEIO = ", E-I-E-I-O"
def main():
# call the verse function to print out a verse
printVerse("dog", "ruff")
printVerse("duck", "quack")
animal_type = "cow"
animal_sound = "moo"
printVerse(animal_type, animal_sound)
# QUESTION: What happens if main called function as
# printVerse("ruff", "dog")
# prints a verse of Old MacDonald, plugging in the animal and sound
# parameters (which are strings), as appropriate.
def printVerse(animal, sound):
print(BEGIN_END + EIEIO)
print("And on that farm he had a " + animal + EIEIO)
print("With a " + sound + ", " + sound + " here")
print("And a " + sound + ", " + sound + " there")
print("Here a", sound)
print("There a", sound)
print("Everywhere a " + sound + ", " + sound)
print(BEGIN_END + EIEIO)
print()
main()
Generated by GNU Enscript 1.6.6.