Download CS 112: Intro to Comp Prog

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Elementary mathematics wikipedia , lookup

Transcript
CS 112: Intro to Comp Prog

Importing modules

Branching

Loops

Program Planning

Arithmetic Program

Lab Assignment #2

Upcoming
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.
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)
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>:
<statements to perform when condition is true>
<...>
else:
<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
A Top-Down Approach




We can use a Top-Down approach to designing our
program, these approach helps us keep the goal of the
program in mind and “not lose the forest for the trees”
Top-Down means looking from the big picture and breaking
it down
Example: An iron crowbar -> iron elements -> atoms ->
protons, neutron, electrons -> ...
Thus we can identify a broad set of steps needed to
accomplish our goal. These steps can be broken down into
smaller stages and eventually into code
Program Planning
●
Below is a series of steps you should go through either in
your head or on paper to help you code your program.
1) Identify the Main Steps (Parts)...later make these into
functions
2) Identify the Variables (Information) needed for each part or
the entire program
3) Begin writing pseudo-code for each of steps
4) Revision (may take several revisions)
5) Convert pseudo-code into Python
6) Debug your code
Program Planning


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
**************************************************************
Take the time to convert the above pseudo-code into python code.
Arithmetic Prog Solution
# Getting user values for the two numbers
num1 = float(raw_input("Enter Number 1: "))
num2 = float(raw_input("Enter Number 2: "))
while 1:
# Creating an infinite loop only to be stopped if 5 entered
# Printing menu in single line with escape characters
print "\n1-Sum\n2-Difference\n3-Product\n4-Quotient\n5-Quit"
# Getting the user's choice of what operation to perform
choice = int(raw_input("Choose your operation by typing the number(1-5): "))
if choice == 1:
# Performing the proper actions based on the input 1 - 4
print "\nSum is " + str(num1 + num2)
elif choice == 2:
print "\nDifference is " + str(num1 - num2)
elif choice == 3:
print "\nProduct is " + str(num1 * num2)
elif choice == 4:
print "\nQuotient is " + str(num1 / num2)
elif choice == 5:
# Quitting
break
else:
# Restarting Loop
print "\nBad Choice! Restarting..."
continue
Arithmetic Prog Solution
# Modify the condition of the loop to eliminate breaks and continues
num1 = float(raw_input("Enter Number 1: "))
num2 = float(raw_input("Enter Number 2: "))
choice = 0
# Creating the choice variable so that it can be used by the
condition
while choice != 5:
# Creating an infinite loop only to be stopped if 5 entered
print "\n1-Sum\n2-Difference\n3-Product\n4-Quotient\n5-Quit"
choice = int(raw_input("Choose your operation by typing the number(1-5): "))
if choice == 1:
# Performing the proper actions based on the input 1 - 4
print "\nSum is " + str(num1 + num2)
elif choice == 2:
print "\nDifference is " + str(num1 - num2)
elif choice == 3:
print "\nProduct is " + str(num1 * num2)
elif choice == 4:
print "\nQuotient is " + str(num1 / num2)
elif choice == 5: print "\nQuitting..."
else:
# Restarting Loop
print "\nBad Choice! Restarting..."