Example: Convert Temperature


In [7]:
def convert():
    ## Temp Convert Code
    """Converts temperature from Celsius to Fahrenheit"""
    celsius = input("Enter the Celsius temperature: ")
    fahrenheit = (9.0 / 5.0)*celsius + 32
    print "It is",fahrenheit, "degress Fahrenheit."
    


#convert()

Naming Variables


In [10]:
x = 5
print x
spam = "SPAM"
print spam


5
SPAM

Playing around with print


In [11]:
print 3+4
print 3, 4, 3+4
print
print 3,4,
print 3+4
print "the answer is", 3+4
### print(3+4)


7
3 4 7

3 4 7
the answer is 7

Input


In [15]:
##NB:  Numeric
def inp():
    x = input("Enter something:")
    print x
inp()


Enter something:3+7
10

Write a function called breakfast that does the following:

Asks a user to input the number of eggs and number of bacon strips they would like

Prints out their order – e.g. “You ordered 2 eggs and 3 strips of bacon.”


In [18]:
def breakfast():
    eggs, bacon = input("Enter # of eggs followed by # of bacon slices:")
    print "You have ordered", eggs, "eggs and", bacon, "slices of bacon."

breakfast()


Enter # of eggs followed by # of bacon slices:3,4
You have ordered 3 eggs and 4 slices of bacon.

In [4]:
def futval():
    print "This program calculates future value"
    principal = input("Enter the principal amount: ")
    apr = input("Enter the annual interest rate: ")

    for i in range(10):
        principal = principal * (1+apr)

    print "The value in 10 years is:", principal

futval()


This program calculates future value
Enter the principal amount: 100
Enter the annual interest rate: .10
The value in 10 years is: 259.37424601

In [4]:
# quadratic.py
#    A program that computes the real roots of a quadratic equation.
#    Illustrates use of the math library.
#    Note: This program crashes if the equation has no real roots.
## NB:  3, 4, -1

import math  # Makes the math library available.

def quadratic():
    print "This program finds the real solutions to a quadratic"
    print

    a, b, c = input("Please enter the coefficients (a, b, c): ")

    discRoot = math.sqrt(b * b - 4 * a * c)
    root1 = (-b + discRoot) / (2 * a)
    root2 = (-b - discRoot) / (2 * a)

    print
    print "The solutions are:", root1, ", ", root2 

#quadratic()

Factorials


In [10]:
def fact():
    fact = 1
    for factor in [6,5,4,3,2,1]:
        fact = factor * fact
        print fact

fact()


6
30
120
360
720
720

In [1]:
# factorial.py
#    Program to compute the factorial of a number
#    Illustrates for loop with an accumulator

def factorial():
    n = input("Please enter a whole number: ")
    fact = 1
    for factor in range(n,1,-1): 
       fact = fact * factor
    print "The factorial of", n, "is", fact

factorial()


Please enter a whole number: 7
The factorial of 7 is 5040