CS 112: Intro to Comp Prog Importing modules Branching Loops Program Planning Arithmetic Program Lab Assignment #2 Upcoming
Assignment #1 Solution CODE: # lab1.py # Student Name: John Noname # Assignment: Lab #1 # Submission Date: 02/09/2009 # Honor Code Statement: I received no assistance on this assignment that # violates the guidelines as set forth by the instructor # and the class syllabus. # References: Python Programming for the absolute beginner (book) # Comments: Our first assignment # Defining the main function def main(): #printing name and major print ''' Name: John Noname Major: Electrical Engineering ''' #prompting user to hit enter to exit the program raw_input("press <Enter> to exit...") print "Good bye" #Calling the main function main()
Assignment #1 Solution Q1. What steps do you take to create a program using IDLE? (Include creating a new file, saving it, and executing it) Ans. -After opening idle, click on file, select "New Window". -Write your code in the opened script window -To save the file click on file again and select "save as" *select the directory you want to store your file in using the pop-up dialog window. *name the file followed by a.py extension. -The file can be executed clicking in the menu "Run Module" (F5). Q2. What steps do you take to create a program (using a text editor) in your operating system? (Include creating a new file, saving it, and executing it) Ans. -Open text editor (eg. notepad) -Click on file, select "new" -To save the file click on file again and select "save as" *select the directory you want to store your file in. *name the file followed by a.py extension. -To run the file, open command prompt *type "cd" with the appropriate directory to get to the location of the script file (.py), use "dir" or "ls" (depending on your OS) to verify the file is in that directory *Once you have found the file, type "python file_name" where file_name is the name of the file you saved Q3. Is it possible to create a program using the method from Q1 and execute it using the method from Q2? Ans. Yes
Lecture Topics Theory...why have these constructs in programming? Modules Can separate code into separate files grouping similar functions (math is the best example). Good for organization, usability, and distribution Branching Programs no longer have to run sequentially, i.e. always behaves the same way. Now programs can be dynamic based on user's input. Looping Allows for arbitrary code to be repeated...before code would have to be copied and pasted; thus would have to be for a set number of times.
Importing modules module: a file that contains external code that is related There are many different modules that have been created and are available to be used by your code. (Tkinter, math, os) Importing loads the code and allows your program to access specific functions Example module: random Function: randrange(<bound>) #gets a number between 0 and (<bound> - 1) # Will randomly display a number in the range 0 to 4 import random print random.randrange(5)
if-structure if <condition>: <statements to perform when condition is true> <tabbing signifies which statements are contained> <within the if-block> <code not tabbed is always run> Example: num = int(raw_input("enter a number")) if (num % 2) == 0: print str(num)+" is even!" print "It is a good number"
if-else structure if <condition>: else: <statements to perform when condition is true> <...> <statements to perform when condition is false> <...> <code not tabbed is always run> Example: num = int(raw_input("enter a number")) if (num % 2) == 0: print str(num)+" is even!" else: print str(num)+" is odd!"
Conditions Conditions are expressions that evaluate to True or False Comparison Operators are used to create these expressions == equal to!= not equal to > greater than >= greater than or equal to < less than <= less than or equal to Examples: (10 / 2) == 5 True HELLO == hello False
Conditions Values in variables can also be directly evaluated to True or False Numeric: 0 == False, everything else is true String: == False, everything else is true Condition expressions can be combined/modified using Logical Operators not #negate the boolean value (false -> true) and #both sides of operator must be true or #at least one side of operator must be true There exists several parallels with if-statements and logical operators, and many times, solutions can be found through a variety of means.
Conditions if (num % 2)!= 0: print str(num)+" is odd! #Equivalent to: if not ((num % 2) == 0): print str(num)+" is odd!" ------------------------------------------------------- if (num % 2) == 0 and (num % 3) == 0: print str(num)+" is divisible by 6!" #Equivalent to: if (num % 2) == 0: if (num % 3) == 0: print str(num)+" is divisible by 6!"
Conditions if userinput == "yes" or userinput == "YES": print "I am glad you feel that way" #Equivalent to: if userinput == "yes": print "I am glad you feel that way" if userinput == "YES": print "I am glad you feel that way"
if-elif-...-else structure if <condition1>: <statements to perform when condition1 is true> <...> elif <condition2>: <statements to perform when condition2 is true> <...> <...many elif statements may follow> else: <statements to perform when all above conditions> <are false> <...> <code not tabbed is always run>
if-elif-...-else structure Example: print "1. Print \"Hello\"" print "2. Print \"Good-bye\"" print "3. Print \"Zzzzzz\"" num = int(raw_input("enter your choice")) if num == 1: print "Hello" elif num == 2: print "Good-bye" elif num == 3: print "Zzzzzz" else: print "Not a valid choice"
while structure while <condition>: <statements to perform when condition is true> <tabbing signifies which statements are contained> <within the while-block. Once tabbed statements are> <executed program goes back to top to check> <condition again...repeat until false> <code not tabbed is always run, and is where code> <resumes when loop finishes, careful of infinite loops> Example: num = 0 while not num: num = int(raw_input("enter a non-zero number")) print "Hurray you chose: "+ str(num)
break continue Sometimes you may want to alter the way your loop runs from inside the loop rather than waiting for a single iteration of the loop to finish. We can do this with two commands: break - this will stop the loop and jump the program to run the code after the loop body (i.e. the tabbed code) continue - this will skip all lines of code inside the loop, jumping the program back to check the condition of the loop
Program Planning (Revisit) Write a program that will ask the user for two decimal numbers, then list a set of operations for them to choose (1 sum, 2 difference, 3 product, 4 quotient, 5 Quit). Display the solution to their choice. After the solution is printed redisplay the menu for them to choose another option until they choose 5, if they type any number other than 1-5 display an error message and continue to display the menu again. Terminal is as shown:
Identify the Main Steps Entering the two numbers Displaying the menu Entering a choice Branching for choice Repeating Menu
Identify the Variables Number 1 - num1 Number 2 - num2 User's Choice - choice Could have decided to have variables for each arithmetic operation, but will do the calculations in-line.
Pseudo-code Get user values for the two decimal numbers Create an infinite loop only to be stopped if 5 entered Print menu Get the user's choice of what operation to perform If choice is 1 print num1 + num2 If choice is 2 print num1 - num2 If choice is 3 print num1 * num2 If choice is 4 print num1 / num2 If choice is 5 stop the loop If choice is anything other than 1 5 restart loop ************************************************************** FOR YOU: Take the time to convert the above pseudo-code into python code.
Assignment #3 Due next week before lab You need to turn in one file Lab3.py Contains the proper comment header Reads input from the user Constructs the proper date string Gathers info using the webbrowser module Outputs the result as shown in the example output Again make sure to verify that everything was submitted
Upcoming Loops, Strings, Tuples, and Number-Base Conversion Finish Lab Assignment #3 and be sure to complete it before next week's lab Read Chapter 4 in the textbook