Comp 150 – Computer Programming 1

January 23, 2008

 

1.         Solving Quadratic Equations          

 

#

# File: quadraticSp08.py

#

 

import math

 

def main():

 

    print "Quadratic Equation"

    print

    a, b, c = input("Enter values for coefficients a, b, and c: ")

 

    d = b**2 - 4.0*a*c  # discriminant

    if (d >= 0):

        x1 = (-b + math.sqrt(d))/(2.0 * a)

        x2 = (-b - math.sqrt(d))/(2.0 * a)

        print "The solutions are", x1, "and", x2

    else:

        print ("There are no real solutions")

 

 

main()

 

 

2.         Computing factorial n

 

#

# File factorialsSp08.py

#

 

def main():

    print "A Factorial Program - January 23, 2008"

    print

 

    n = input("Enter an integer greater than 0: ")

#   factorial = 1.0     # float type result

    factorial = 1       # int type result

    for i in range(1, n+1, 1):

        factorial = factorial * i

 

    print n,"factorial = ", factorial

 

main(); 

 


3.         List Demonstration

 

#

#  ListDemoSp08.py

#

 

def main():

    print "Sequence Demo Program"

    print

 

    list = []   # create an empty list (array)

 

    print "At the prompt, type a number. Enter 0 when done:"

 

#   read a number an append it to the list

 

    x = input("? ")

    while (x != 0):

        list.append(x)  # add x to the list

        x  = input("? ")

 

#   print list

 

    print "List =", list

 

#   use list to control a for loop

 

    sum = 0

    print "Print list in order"

    for item in list:

        sum = sum + item   # sum items

        print item,        # print each item

    print   

    print "Sum = ", sum

 

#   find the number of elements in a list

   

    print "Number of items in list =", len(list)

 

#   optional: use indexing to print out list backwards

 

    length = len(list)  # get size of list

    print "Print out list backwards"   

    for i in range(length-1, -1, -1):

        print list[i],

    print

 

main()      

 


4.         Type Conversions

 

#

# TypeDemoSp08.py

#

 

def main():

    print"Data Type Demo Pgm"

    print

 

    print "17/5 =", 17/5

    print "17.0/5.0 =", 17.0/5.0

    print "17.0/5 = ", 17.0/5

    print "float(17/5) = ",float(17/5)

    print "float(17)/5 = ",float(17)/5

    print

    print "17/5*5 = ",17/5*5

    print "17.0/5.0*5 =", 17.0/5.0*5

    print

    print "8.0/3.0 =", 8.0/3.0

    print "int(8.0/3.0) =", int(8.0/3.0)

    print "round(8.0/3.0) = ",round(8.0/3.0)

    print "int(round(8.0/3.0) =", int(round(8.0/3.0))

    print

    print "153 % 10 =", 153 % 10

    print "153 / 10 % 10 =", 153 / 10 % 10

    print "153 / 100 % 10 =", 153 / 100 % 10

    print

    print "float(int(3.71) = ", float(int(3.71))

    print "3.71 % 1 =", 3.71 % 1

    print

   

main()