Programming notes
The Big If Really great work! Here's what you've learned in this unit: Comparators 3 < 4 5 >= 5 10 == 10 12 != 13 Boolean operators True or False (3 < 4) and (5 >= 5) this() and not that() Conditional statements if this_might_be_true(): print "This really is true." elif that_might_be_true(): print "That is true." else: print "None of the above." Let's get to the grand finale.
# Make sure that the_flying_circus() returns True def the_flying_circus(): if 9 <= 9: print "It's true" return True elif 6 == 8 or 99 < 88: print "It's wrong" return False else: return False
Bringing It All Together Nice work! So far, you've learned about: Variables, which store values for later use Data types, such as numbers and booleans Whitespace, which separates statements Comments, which make your code easier to read Arithmetic operations, including +, -, *, /, **, and %
Let's put our knowledge to work. Write a single-line comment on line 1. It can be anything! (Make sure it starts with #) Set the variable monty equal to True. Set another variable python equal to 1.234. Set a third variable monty_python equal to python squared.
And Now, For Something Completely Familiar Great job! You've learned a lot in this unit, including: Three ways to create strings 'Alpha' "Bravo" str(3) String methods len("Charlie") "Delta".upper() "Echo".lower() Printing a string print "Foxtrot" Advanced printing techniques g = "Golf" h = "Hotel" print "%s, %s" % (g, h)
Let's wrap it all up! On line 3, create the variable my_string and set it to any string you'd like. On line 4, print the length of my_string. On line 5, print the .upper() case version of my_string. # Write your code below, starting on line 3! my_string = str(3) print len(my_string) print my_string .upper()
Whitespace Means Right Space Now let's examine the error from the last lesson: IndentationError: expected an indented block You'll get this error whenever your whitespace is off.
Properly indent the code with four spaces before eggs on line 2 and another four before return on line 3. You should indent your code with four spaces. def spam(): eggs = 12 return eggs print spam()
Go With the Flow Just like in real life, sometimes we'd like our code to be able to make decisions. The Python programs we've written so far have had one-track minds: they can add two numbers or print something, but they don't have the ability to pick one of these outcomes over the other. Control flow gives us this ability to choose among outcomes based off what else is happening in the program.
def clinic(): print "You've just entered the clinic!" print "Do you take the door on the left or the right?" answer = raw_input("Type left or right and hit 'Enter'.").lower() if answer == "left" or answer == "l": print "This is the Verbal Abuse Room, you heap of parrot droppings!" elif answer == "right" or answer == "r": print "Of course this is the Argument Room, I've told you that already!" else: print "You didn't pick left or right! Try again." clinic() clinic()
Review: Built-In Functions Perfect! Last but not least, let's review the built-in functions you've learned about in this lesson. def is_numeric(num): return type(num) == int or type(num) == float: max(2, 3, 4) # 4 min(2, 3, 4) # 2 abs(2) # 2 abs(-2) # 2
def distance_from_zero(n): if type(n) == int or type(n)==float : return abs(n) else: return"Nope" distance_from_zero(5)
Pull it Together Great! Now that you've got your 3 main costs figured out, let's put them together in order to find the total cost of your trip. def double(n): return 2 * n def triple(p): return 3 * p def add(a, b): return double(a) + triple(b) We define two simple functions, double(n) and triple(p) that return 2 times or 3 times their input. Notice that they have n and p as their arguments. We define a third function, add(a, b) that returns the sum of the previous two functions when called with a and b, respectively. Instructions Below your existing code, define a function called trip_cost that takes two arguments, city and days. Like the example above, have your function return the sum of calling the rental_car_cost(days), hotel_cost(days), and plane_ride_cost(city) functions. It is completely valid to call the hotel_cost(nights) function with the variable days. Just like the example above where we call double(n) with the variable a, we pass the value of days to the new function in the argument nights.
def hotel_cost(nights): return 140 * nights def hotel_cost(days): return 140 * days def plane_ride_cost(city): if city == "Charlotte": return 183 elif city == "Tampa": return 220 elif city == "Pittsburgh": return 222 elif city == "Los Angeles": return 475 def rental_car_cost(days): if days >=7: return (days * 40)-50 elif days >=3 and days <7: return (days * 40)-20 elif days <3: return days*40 def trip_cost(city,days): return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city)
Hey, You Never Know! You can't expect to only spend money on the plane ride, hotel, and rental car when going on a vacation. There also needs to be room for additional costs like fancy food or souvenirs. Instructions Modify your trip_cost function definition. Add a third argument, spending_money. Modify what the trip_cost function does. Add the variable spending_money to the sum that it returns.
def hotel_cost(nights): return 140 * nights def hotel_cost(days): return 140 * days def plane_ride_cost(city): if city == "Charlotte": return 183 elif city == "Tampa": return 220 elif city == "Pittsburgh": return 222 elif city == "Los Angeles": return 475 def rental_car_cost(days): if days >=7: return (days * 40)-50 elif days >=3 and days <7: return (days * 40)-20 elif days <3: return days*40 def trip_cost(city,days,spending_money): return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) + spending_money
Getting There You're going to need to take a plane ride to get to your location. def fruit_color(fruit): if fruit == "apple": return "red" elif fruit == "banana": return "yellow" elif fruit == "pear": return "green" The example above defines the function fruit_color that accepts a string as the argument fruit. The function returns a string if it knows the color of that fruit. Instructions Below your existing code, define a function called plane_ride_cost that takes a string, city, as input. The function should return a different price depending on the location, similar to the code example above. Below are the valid destinations and their corresponding round-trip prices. "Charlotte": 183 "Tampa": 220 "Pittsburgh": 222 "Los Angeles": 475
def hotel_cost(nights): return 140 * nights def plane_ride_cost(city): if city == "Charlotte": return 183 elif city == "Tampa": return 220 elif city == "Pittsburgh": return 222 elif city == "Los Angeles": return 475
Transportation You're also going to need a rental car in order for you to get around. def finish_game(score): tickets = 10 * score if score >= 10: tickets += 50 elif score >= 7: tickets += 20 return tickets In the above example, we first give the player 10 tickets for every point that the player scored. Then, we check the value of score multiple times. First, we check if score is greater than or equal to 10. If it is, we give the player 50 bonus tickets. If score is just greater than or equal to 7, we give the player 20 bonus tickets. At the end, we return the total number of tickets earned by the player. Remember that an elif statement is only checked if all preceding if/elif statements fail. Instructions Below your existing code, define a function called rental_car_cost with an argument called days. Calculate the cost of renting the car: Every day you rent the car costs $40. if you rent the car for 7 or more days, you get $50 off your total. Alternatively (elif), if you rent the car for 3 or more days, you get $20 off your total. You cannot get both of the above discounts. Return that cost. Just like in the example above, this check becomes simpler if you make the 7-day check an if statement and the 3-day check an elif statement.
def hotel_cost(nights): return 140* nights def plane_ride_cost(city): if city == "Charlotte": return 183 elif city == "Tampa": return 220 elif city == "Pittsburgh": return 222 elif city == "Los Angeles": return 475 else: return "Go Home" def rental_car_cost(days): total = days * 40 if days >= 7: return total - 50 elif days >= 3: return total - 20 else: return total
Plan Your Trip! Nice work! Now that you have it all together, let's take a trip. What if we went to Los Angeles for 5 days and brought an extra 600 dollars of spending money? Instructions After your previous code, print out the trip_cost( to "Los Angeles" for 5 days with an extra 600 dollars of spending money. Don't forget the closing ) after passing in the 3 previous values!
def hotel_cost(nights): return 140*nights def plane_ride_cost(city): if city == "Charlotte": return 183 if city=="Tampa": return 220 if city=="Pittsburgh": return 222 if city=="Los Angeles": return 475 else: return "Unknown" def rental_car_cost(days): cost = days*40 if days >= 7: return cost-50 elif days >= 3: return cost-20 else: return cost def spending_money(money): money = 50*days def trip_cost(city, days, money): return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) + money def trip_cost(city, days, money): print trip_cost("Los Angeles", 5, 600)
Review: Functions Okay! Let's review functions. def speak(message): return message if happy(): speak("I'm happy!") elif sad(): speak("I'm sad.") else: speak("I don't know what I'm feeling.") Again, the example code above is just there for your reference! Instructions First, def a function, shut_down, that takes one argument s. Don't forget the parentheses or the colon! Then, if the shut_down function receives an s equal to "yes", it should return "Shutting down" Alternatively, elif s is equal to "no", then the function should return "Shutdown aborted". Finally, if shut_down gets anything other than those inputs, the function should return "Sorry"
def shut_down(s): s = s.lower() if s == "yes": return "Shutting down" elif s == "no": return "Shutdown aborted" else: return "Sorry" print shut_down("Yes") print shut_down("I don't know")
Grand Finale We've managed to print the date and time separately in a very pretty fashion. Let's combine the two! from datetime import datetime now = datetime.now() print '%s/%s/%s' % (now.month, now.day, now.year) print '%s:%s:%s' % (now.hour, now.minute, now.second) The example above will print out the date, then on a separate line it will print the time. Let's print them all on the same line in a single print statement!
from datetime import datetime now = datetime.now() day = str(now.month) + "/" + str(now.day) + "/" + str(now.year) hour = str(now.hour) + ":" + str(now.minute) + ":" + str(now.second) print day + " " + hour
Review: Modules Good work! Now let's see what you remember about importing modules (and, specifically, what's available in the math module). Instructions Import the math module in whatever way you prefer. Call its sqrt function on the number 13689 and print that value to the console.
from math import sqrt print sqrt(13689)
Congratulations! You learned how to use the command line to redirect standard input and standard output. What can we generalize so far? Redirection reroutes standard input, standard output, and standard error. The common redirection commands are: > redirects standard output of a command to a file, overwriting previous content. >> redirects standard output of a command to a file, appending new content to old content. < redirects standard input to a command. | redirects standard output of a command to another command. A number of other commands are powerful when combined with redirection commands: sort: sorts lines of text alphabetically. uniq: filters duplicate, adjacent lines of text. grep: searches for a text pattern and outputs it. sed : searches for a text pattern, modifies it, and outputs it.
j
Congratulations! You learned how to use the command line to view and manipulate the filesystem. What can we generalize so far? Options modify the behavior of commands: ls -a lists all contents of a directory, including hidden files and directories ls -l lists all contents in long format ls -t orders files and directories by the time they were last modified Multiple options can be used together, like ls -alt From the command line, you can also copy, move, and remove files and directories: cp copies files mv moves and renames files rm removes files rm -r removes directories Wildcards are useful for selecting groups of files and directories
j
Congratulations! You learned to use the bash profile to configure the environment. What can we generalize so far? The environment refers to the preferences and settings of the current user. The nano editor is a command line text editor used to configure the environment. ~/.bash_profile is where environment settings are stored. You can edit this file with nano. environment variables are variables that can be used across commands and programs and hold information about the environment. export VARIABLE="Value" sets and exports an environment variable. USER is the name of the current user. PS1 is the command prompt. HOME is the home directory. It is usually not customized. PATH returns a colon separated list of file paths. It is customized in advanced cases. env returns a list of environment variables.
j
Congratulations! You've learned five commands commonly used to navigate the filesystem from the command line. What can we generalize so far? The command line is a text interface for the computer's operating system. To access the command line, we use the terminal. A filesystem organizes a computer's files and directories into a tree structure. It starts with the root directory. Each parent directory can contain more child directories and files. From the command line, you can navigate through files and folders on your computer: pwd outputs the name of the current working directory. ls lists all files and directories in the working directory. cd switches you into the directory you specify. mkdir creates a new directory in the working directory. touch creates a new file inside the working directory.
j
The -l option lists files and directories as a table. Here there are four rows, with seven columns separated by spaces. Here's what each column means: Access rights. These are actions that are permitted on a file or directory. Number of hard links. This number counts the number of child directories and files. This number includes the parent directory link (..) and current directory link (.). The username of the file's owner. Here the username is cc. The name of the group that owns the file. Here the group name is eng. The size of the file in bytes. The date & time that the file was last modified. The name of the file or directory.
j
The ls command lists all files and directories in the working directory. The -a modifies the behavior of the ls command to also list the files and directories starting with a dot (.). Files started with a dot are hidden, and don't appear when using ls alone. The -a is called an option. Options modify the behavior of commands. Here we used ls -a to display the contents of the working directory in more detail. In addition to -a, the ls command has several more options. Here are three common options: -a - lists all contents, including hidden files and directories -l - lists all contents of a directory in long format -t - order files and directories by the time they were last modified.
j
A Matter of Interpretation The window in the top right corner of the page is called the interpreter. The interpreter runs your code line by line, and checks for any errors. cats = 3 In the above example, we create a variable cats and assign it the value of 3.
k
Booleans Great! You just stored a number in a variable. Numbers are one data type we use in programming. A second data type is called a boolean. A boolean is like a light switch. It can only have two values. Just like a light switch can only be on or off, a boolean can only be True or False. You can use variables to store booleans like this: a = True b = False
k
Exponentiation All that math can be done on a calculator, so why use Python? Because you can combine math with other data types (e.g. booleans) and commands to create useful programs. Calculators just stick to numbers. Now let's work with exponents. eight = 2 ** 3 In the above example, we create a new variable called eight and set it to 8, or the result of 2 to the power to 3 (2^3). Notice that we use ** instead of * or the multiplication operator.
k
Math Great! Now let's do some math. You can add, subtract, multiply, divide numbers like this addition = 72 + 23 subtraction = 108 - 204 multiplication = 108 * 0.5 division = 108 / 9
k
Modulo Our final operator is modulo. Modulo returns the remainder from a division. So, if you type 3 % 2, it will return 1, because 2 goes into 3 evenly once, with 1 left over.
k
Multi-Line Comments The # sign will only comment out a single line. While you could write a multi-line comment, starting each line with #, that can be a pain. Instead, for multi-line comments, you can include the whole block in a set of triple quotation marks: """Sipping from your cup 'til it runneth over, Holy Grail. """
k
Single Line Comments You probably saw us use the # sign a few times in earlier exercises. The # sign is for comments. A comment is a line of text that Python won't try to run as code. It's just for humans to read. Comments make your program easier to understand. When you look back at your code or others want to collaborate with you, they can read your comments and easily figure out what your code does.
k
Variables Creating web apps, games, and search engines all involve storing and working with different types of data. They do so using variables. A variable stores a piece of data, and gives it a specific name. For example: spam = 5 The variable spam now stores the number 5.
k
Whitespace In Python, whitespace is used to structure code. Whitespace is important, so you have to be careful with how you use it.
k
You've Been Reassigned Now you know how to use variables to store values. Say my_int = 7. You can change the value of a variable by "reassigning" it, like this: my_int = 3
k
Check Yourself! Next we need to ensure that the user actually typed something. empty_string = "" if len(empty_string) > 0: # Run this block. # Maybe print something? else: # That string must have been empty. We can check that the user's string actually has characters!
print 'Welcome to the Pig Latin Translator!' # Start coding here! raw_input("Enter a word:") original = raw_input('Prompt') if len(original) > 0 : print else: print "empty"
Check Yourself... Some More Now we know we have a non-empty string. Let's be even more thorough. x = "J123" x.isalpha() # False In the first line, we create a string with letters and numbers. The second line then runs the function isalpha() which returns False since the string contains non-letter characters. Let's make sure the word the user enters contains only alphabetical characters. You can use isalpha() to check this! For example:
print 'Welcome to the Pig Latin Translator!' # Start coding here! raw_input("Enter a word:") original = raw_input('Prompt') if len(original) > 0 and original.isalpha(): print else: print "empty"