factorial.py
#defines a function that calculates the factorial def factorial(n): if n <= 1: return 1 return n*factorial(n-1) print "2! = ",factorial(2) print "3! = ",factorial(3) print "4! = ",factorial(4) print "5! = ",factorial(5)
Output:
2! = 2 3! = 6 4! = 24 5! = 120
temperature2.py
#converts temperature to fahrenheit or celsius def print_options(): print "Options:" print " 'p' print options" print " 'c' convert from celsius" print " 'f' convert from fahrenheit" print " 'q' quit the program" def celsius_to_fahrenheit(c_temp): return 9.0/5.0*c_temp+32 def fahrenheit_to_celsius(f_temp): return (f_temp - 32.0)*5.0/9.0 choice = "p" while choice != "q": if choice == "c": temp = input("Celsius temperature:") print "Fahrenheit:",celsius_to_fahrenheit(temp) elif choice == "f": temp = input("Fahrenheit temperature:") print "Celsius:",fahrenheit_to_celsius(temp) elif choice != "q": print_options() choice = raw_input("option:")
Sample Run:
> python temperature2.py Options: 'p' print options 'c' convert from celsius 'f' convert from fahrenheit 'q' quit the program option:c Celsius temperature:30 Fahrenheit: 86.0 option:f Fahrenheit temperature:60 Celsius: 15.5555555556 option:q