Python Boot Camp Day 3
Agenda 1. Review Day 2 Exercises 2.Getting input from the user, Interview Lab 3.Scopes 4.Conditionals, Mood Ring Lab 5.Recursion, Recursion Lab
Day 2 Exercises Think Python Ch. 3 Functions can call other functions Passing functions as arguments
Day 2 Exercises Think Python Ch. 4 Generalization! Refactoring!
Getting Input from the User raw_input([prompt]) raw_input() takes the user s input, converts it to a string (!), stripping off the trailing newline, and returns the string. set raw_input() to a variable in order to handle it
Let s try it out... Write a function called interview that asks the following questions: What is your first name? How many pets do you have? How likely do you think it is to rain today? (Enter as a floating point number.) After the user (you) answers each question, the function should print out a few sentences repeating what the user entered.
Interview Script
Scopes and Namespaces When you create/assign/define a name, Python creates or looks up the name in a namespace. A namespace is the place where the name lives. In Scheme, it s called the environment. When you create a name, you either define the meaning of the name or refer to a definition somewhere else. Ex: a = b Where you physically assign a name, determines the name s scope Ex: Functions create nested namespaces The scope of a definition is the part of the program over which the definition holds. Variables must be assigned before they are referenced in order to be used. Adapted from CS9H
Python Scope Basics 1. All names are scoped the same Different from Java or C++ where the variable foo and class foo are considered two different things A name can only refer to one thing at a time Adapted from CS9H
Example What does each print statement produce? Write down your predictions and then try it in the interpreter. 4 <function spoon at 08xe630> foo Adapted from CS9H
Python Scope Basics 2. The Scope of a name is its enclosing function or class In the function genius, the second line binds x to 4, and the third line refers to x in the local namespace The scope of x is the genius function Adapted from CS9H
Another Example Let s look at the flow of execution. two plus two is 4 two plus two is 3 4 two plus two is 4 two plus two is 5 Adapted from CS9H
Python Scope Basics 3.Names belong to the namespaces where they are bound If a binding for a variable appears anywhere inside a function, that variable name is local to the function, even if it is never executed. Adapted from CS9H
Last Example What will the two function calls produce? spam(1) causes an UnboundLocalError because x is bound to 5 within spam() even though it is not executed spam(6) prints 5 because it passes 6 in as y, which is greater than 3, which assigns x to 5 before printing x Adapted from CS9H
Python Scope Basics Summary We usually talk about variables as being either global or local (in scope) Assigned variables are local by default unless declared global. The enclosing module is the global scope. Module = file you are working in, for example. The global scope only spans a single file. Each call to a function creates a new local scope. Python will try to look for variables from the inside out: local, enclosing function, global (module), built-in module Adapted from Learning Python by Mark Lutz
Conditionals Boolean Logic Logical Operators (previously talked about math operators) Conditional Statements Chained Conditionals Nested Conditionals
Boolean Logic A boolean expression is an expression that evaluates to either true or false. 7 > 3 evalutes to True 4 >= 5 evalutes to False 3!= 5 evalutes to True 1 + 1 == 3 evalutes to False comparison operators
Logical Operators and, or, not evalute the way that you would expect in English and evalutes as True if both expressions are true or evalutes as True is either expression is true not evalutes as True if the expression is not true not (8 > 10) is True not (8 < 10) is False
Logical Operators Non-zero numbers evalute as true not 17 is False And of course you can combine them! not (True and False) is True not (False or True) is False
How do these statements evaluate? False and True True or False and True not True and not False (6**2) or False and True 0 and 1 or False and False
Conditional Statements So far we ve written scripts or code that executes more or less in order from top to bottom. Conditional statements allow us to write code that behaves differently depending on the given values. if, else statements
Conditional Statements What will this print?
The return statement Return is not the same as print Ok, so how do we print the result? Allows you to terminate the execution of a function before you reach the end. If you detect an error, for example You can only return once from a function.
elif Chained Conditionals
Nested Conditionals
Mood Ring Lab Write a script that tells the user how he/she is feeling today. The script should: Print a greeting to the user with his or her name Tell the user if he/she is happy, neutral, or sad (at random). Or any three emotions. Hint: use the random module Try to encapsulate your code inside functions Use your neighbors for help. Adapted from Python Programming for the Absolute Beginner
Recursion A function can call another function. A function can also call itself. What would happen if we executed this script?
Infinite Recursion Oh no! The output repeats forever! How do we fix this? Include a conditional statement or a loop and a base case. Generally, recursive functions work like this: If the problem can be solved immediately, the function returns the result. If the problem cannot be solved now, the function reduces it to a smaller but similar problem and calls itself to solve the smaller problem.
Infinite Recursion Fixed
Recursion Lab Write a script that uses recursion to calculate the factorial of a number. Create a function called main that: Gets a non-negative number from the user and Calls another function which calculates the factorial of the number and Prints the result Hint: The factorial (n!) of a nonnegative number can be defined by: If n = 0, then n! is 1 If n > 0, then n! is 1 * 2 * 3 *...n
Recursion Lab Volunteers want to share their script?
Recursion Lab
Exercises Read Think Python Ch. 5 & 6 Do the exercises in Think Python Ch. 5 and Ch. 6, but not exercise 6.4