Python
https://www.codecademy.com/learn/python
Python Syntax
Welcome!
Python is an easy to learn programming language. You can use it to create web apps, games, even a search engine!
Ready to learn Python? Click Save & Submit Code to continue!
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.
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
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
# my_int is set to 7 below. What do you think
# will happen if we reset it to 3 and print the result?
my_int = 7
# Change the value of my_int to 3 on line 8!
my_int = 3
# Here's some code that will print my_int to the console:
# The print keyword will be covered in detail soon!
print my_int
Whitespace
In Python, whitespace is used to structure code. Whitespace is important, so you have to be careful with how you use it.
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.
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.
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.
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.
"""
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
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.
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.
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 %
Tip Calculator
Now that you've completed the lesson on Python syntax, let's see if you can put your newfound skills to use. In this lesson, you'll create a simple calculator that determines the price of a meal after tax and tip.
Tip Calculator
- The Meal
Now let's apply the concepts from the previous section to a real world example.
You've finished eating at a restaurant, and received this bill:
— Cost of meal: $44.50
— Restaurant tax: 6.75%
— Tip: 15%
You'll apply the tip to the overall cost of the meal (including tax).
- The Tax
Good! Now let's create a variable for the tax percentage.
The tax on your receipt is 6.75%. You'll have to divide 6.75 by 100 in order to get the decimal form of the percentage. (See the Hint if you would like further explanation.)
- The Tip
Nice work! You received good service, so you'd like to leave a 15% tip on top of the cost of the meal, including tax.
Before we compute the tip for your bill, let's set a variable for the tip. Again, we need to get the decimal form of the tip, so we divide 15.0 by 100.
- Reassign in a Single Line
Okay! We've got the three variables we need to perform our calculation, and we know some arithmetic operators that can help us out.
We saw in Lesson 1 that we can reassign variables. For example, we could say spam = 7, then later change our minds and say spam = 3.
- The Total
Now that meal has the cost of the food plus tax, let's introduce on line 8 a new variable, total, equal to the new meal + meal * tip.
The code on line 10 formats and prints to the console the value of total with exactly two numbers after the decimal. (We'll learn about string formatting, the console, and print in Unit 2!)
# Reassign meal on line 7!
meal = 44.50
tax = 0.0675
tip = 0.15
Strings & Console Output
This lesson will introduce you to strings and console output in Python, including creating string literals, calling a variety of string methods, and using the "print" keyword.
Strings
Another useful data type is the string. A string can contain letters, numbers, and symbols.
name = "Ryan"
age = "19"
food = "cheese"
In the above example, we create a variable name
and set it to the string value ”Ryan”
.
We also set age
to ”19”
and food
to ”cheese”
.
Strings need to be within quotes.
Practice
Excellent! Let's get a little practice in with strings.
Escaping characters
There are some characters that cause problems. For example:
'There's a snake in my boot!'
This code breaks because Python thinks the apostrophe in 'There's' ends the string. We can use the backslash to fix the problem, like this:
'There\'s a snake in my boot!'
Access by Index
Great work!
Each character in a string is assigned a number. This number is called the index. Check out the diagram in the editor.
c = "cats"[0]
n = "Ryan"[3]
In the above example, we create a new variable called c
and set it to ”c”
, the character at index zero of the string ”cats”
.
Next, we create a new variable called n
and set it to ”n”
, the character at index three of the string ”Ryan”
.
In Python, we start counting the index from zero instead of one.
"""
The string "PYTHON" has six characters,
numbered 0 to 5, as shown below:
+---+---+---+---+---+---+
| P | Y | T | H | O | N |
+---+---+---+---+---+---+
0 1 2 3 4 5
So if you wanted "Y", you could just type
"PYTHON"[1] (always start counting from 0!)
"""
fifth_letter = "MONTY"[4]
print fifth_letter
String methods
Great work! Now that we know how to store strings, let's see how we can change them using string methods.
String methods let you perform specific tasks for strings.
We'll focus on four string methods:
len()
lower()
upper()
str()
Let's start with len(), which gets the length (the number of characters) of a string!
parrot = "Norwegian Blue"
print len(parrot)
lower()
Well done!
You can use the lower()
method to get rid of all the capitalization in your strings. You call lower()
like so:
"Ryan".lower()
which will return ”ryan”
.
parrot = "Norwegian Blue"
print parrot.lower()
upper()
Now your string is 100% lower case! A similar method exists to make a string completely upper case.
parrot = "norwegian blue"
print parrot.upper()
str()
Now let's look at str(), which is a little less straightforward. The str() method turns non-strings into strings! For example:
str(2)
would turn 2
into ”2”
.
"""Declare and assign your variable on line 4,
then call your method on line 5!"""
pi = 3.14
print str(pi)
Dot Notation
Let's take a closer look at why you use len(string)
and str(object)
, but dot notation (such as ”String".upper()
) for the rest.
lion = "roar"
len(lion)
lion.upper()
Methods that use dot notation only work with strings.
On the other hand, len()
and str()
can work on other data types.
ministry = "The Ministry of Silly Walks"
print len(ministry)
print ministry.upper()
Printing Strings
The area where we've been writing our code is called the editor.
The console (the window in the upper right) is where the results of your code is shown.
print simply displays your code in the console.
"""Tell Python to print "Monty Python"
to the console on line 4!"""
print "Monty Python"
Printing Variables
Great! Now that we've printed strings, let's print variables
String Concatenation
You know about strings, and you know about arithmetic operators. Now let's combine the two!
print "Life " + "of " + "Brian"
This will print out the phrase Life of Brian.
The + operator between strings will 'add' them together, one after the other. Notice that there are spaces inside the quotation marks after Life and of so that we can make the combined string look like 3 words.
Combining strings together like this is called concatenation. Let's try concatenating a few strings together now!
Explicit String Conversion
Sometimes you need to combine a string with something that isn't a string. In order to do that, you have to convert the non-string into a string.
print "I have " + str(2) + " coconuts!"
This will print I have 2 coconuts!
.
The str() method converts non-strings into strings. In the above example, you convert the number 2
into a string and then you concatenate the strings together just like in the previous exercise.
Now try it yourself!
String Formatting with %, Part 1
When you want to print a variable with a string, there is a better method than concatenating strings together.
name = "Mike"
print "Hello %s" % (name)
The %
operator after a string is used to combine a string with variables. The %
operator will replace a %s
in the string with the string variable that comes after it.
string_1 = "Camelot"
string_2 = "place"
print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)
String Formatting with %, Part 2
Remember, we used the % operator to replace the %s placeholders with the variables in parentheses.
name = "Mike"
print "Hello %s" % (name)
You need the same number of %s terms in a string as the number of variables in parentheses:
print "The %s who %s %s!" % ("Knights", "say", "Ni")
# This will print "The Knights who say Ni!"
name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
color = raw_input("What is your favorite color?")
print "Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, quest, color)
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)
Date and Time
This lesson is a follow up to Unit 2: Strings and Console input and will give you practice with the concepts introduced in that lesson.
The datetime Library
A lot of times you want to keep track of when something happened. We can do so in Python using datetime.
Here we'll use datetime to print the date and time in a nice format.
Getting the Current Date and Time
We can use a function called datetime.now() to retrieve the current date and time.
from datetime import datetime
print datetime.now()
The first line imports the datetime library so that we can use it.
The second line will print out the current date and time.
Extracting Information
Notice how the output looks like 2013-11-25 23:45:14.317454. What if you don't want the entire date and time?
from datetime import datetime
now = datetime.now()
current_year = now.year
current_month = now.month
current_day = now.day
You already have the first two lines.
In the third line, we take the year (and only the year) from the variable now
and store it in current_year
.
In the fourth and fifth lines, we store the month and day from `now.
Hot Date
What if we want to print today's date in the following format? mm/dd/yyyy. Let's use string substitution again!
from datetime import datetime
now = datetime.now()
print '%s-%s-%s' % (now.year, now.month, now.day)
# will print: 2014-02-19
Remember that the %
operator will fill the %s
placeholders in the string on the left with the strings in the parentheses on the right.
In the above example, we print 2014-02-19
(if today is February 19th, 2014), but you are going to print out 02/19/2014
.
Pretty Time
Nice work! Let's do the same for the hour, minute, and second.
from datetime import datetime
now = datetime.now()
print now.hour
print now.minute
print now.second
In the above example, we just printed the current hour, then the current minute, then the current second.
We can again use the variable now
to print the time.
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!
Conditionals & Control Flow
In this lesson, we'll learn how to create programs that generate different outcomes based on user input!
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.
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.
Compare Closely!
Let's start with the simplest aspect of control flow: comparators. There are six:
Equal to (==)
Not equal to (!=)
Less than (<)
Less than or equal to (<=)
Greater than (>)
Greater than or equal to (>=)
Comparators check if a value is (or is not) equal to, greater than (or equal to), or less than (or equal to) another value.
Note that == compares whether two things are equal, and = assigns a value to a variable.
Compare... Closelier!
Excellent! It looks like you're comfortable with basic expressions and comparators.
But what about extreme expressions and comparators?
How the Tables Have Turned
Comparisons result in either True or False, which are booleans as we learned before in this exercise.
# Make me true!
bool_one = 3 < 5
Let's switch it up: we'll give the boolean, and you'll write the expression, just like the example above.
To Be and/or Not to Be
Boolean operators compare statements and result in boolean values. There are three boolean operators:
and, which checks if both the statements are True;
or, which checks if at least one of the statements is True;
not, which gives the opposite of the statement.
We'll go through the operators one by one.
"""
Boolean Operators
------------------------
True and True is True
True and False is False
False and True is False
False and False is False
True or True is True
True or False is True
False or True is True
False or False is False
Not True is False
Not False is True
"""
And
The boolean operator and returns True when the expressions on both sides of and are true. For instance:
1 < 2 and 2 < 3 is True;
1 < 2 and 2 > 3 is False.
Or
The boolean operator or returns True when at least one expression on either side of or is true. For example:
1 < 2 or 2 > 3 is True;
1 > 2 or 2 > 3 is False.
Not
The boolean operator not returns True for false statements and False for true statements.
For example:
not False will evaluate to True, while not 41 > 40 will return False.
This and That (or This, But Not That!)
Boolean operators aren't just evaluated from left to right. Just like with arithmetic operators, there's an order of operations for boolean operators:
not is evaluated first;
and is evaluated next;
or is evaluated last.
For example, True or not False and False returns True. If this isn't clear, look at the Hint.
Parentheses () ensure your expressions are evaluated in the order you want. Anything in parentheses is evaluated as its own unit.
Mix 'n' Match
Great work! We're almost done with boolean operators.
# Make me false
bool_one = (2 <= 2) and "Alpha" == "Bravo"
Conditional Statement Syntax
if is a conditional statement that executes some specified code after checking if its expression is True.
Here's an example of if statement syntax:
if 8 < 9:
print "Eight is less than nine!"
In this example, 8 < 9 is the checked expression and print "Eight is less than nine!" is the specified code.
If You're Having...
Let's get some practice with if statements. Remember, the syntax looks like this:
if some_function():
# block line one
# block line two
# et cetera
Looking at the example above, in the event that some_function()
returns True
, then the indented block of code after it will be executed. In the event that it returns False
, then the indented block will be skipped.
Also, make sure you notice the colons at the end of the if statement. We've added them for you, but they're important.
Else Problems, I Feel Bad for You, Son...
The else statement complements the if statement. An if/else pair says: "If this expression is true, run this indented code block; otherwise, run this code after the else statement."
Unlike if, else doesn't depend on an expression. For example:
if 8 > 9:
print "I don't printed!"
else:
print "I get printed!"
I Got 99 Problems, But a Switch Ain't One
"Elif" is short for "else if." It means exactly what it sounds like: "otherwise, if the following expression is true, do this!"
if 8 > 9:
print "I don't get printed!"
elif 8 < 9:
print "I get printed!"
else:
print "I also don't get printed!"
In the example above, the elif statement is only checked if the original if statement if False.
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.
PygLatin
In this lesson we'll put together all of the Python skills we've learned so far including string manipulation and branching. We'll be building a Pyg Latin translator. (That's Pig Latin for Python Programmers!)
Break It Down
Now let's take what we've learned so far and write a Pig Latin translator.
Pig Latin is a language game, where you move the first letter of the word to the end and add "ay." So "Python" becomes "ythonpay." To write a Pig Latin translator in Python, here are the steps we'll need to take:
Ask the user to input a word in English.
Make sure the user entered a valid word.
Convert the word from English to Pig Latin.
Display the translation result.
Ahoy! (or Should I Say Ahoyay!)
Let's warm up by printing a welcome message for our translator users.
Input!
Next, we need to ask the user for input.
name = raw_input("What's your name?")
print name
In the above example, raw_input() accepts a string, prints it, and then waits for the user to type something and press Enter (or Return).
In the interpreter, Python will ask:
What's your name? >
Once you type in your name and hit Enter, it will be stored in name.
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!
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!
original = raw_input("Enter a word:")
if len(original) > 0 and original.isalpha():
print original
else:
print "empty"
Pop Quiz!
When you finish one part of your program, it's important to test it multiple times, using a variety of inputs.
Ay B C
Now we can get ready to start translating to Pig Latin! Let's review the rules for translation:
You move the first letter of the word to the end and then append the suffix 'ay'.
Example: python -> ythonpay
Let's create a variable to hold our translation suffix.
Word Up
Let's simplify things by making the letters in our word lowercase.
the_string = "Hello"
the_string = the_string.lower()
The .lower() function does not modify the string itself, it simply returns a lowercase-version. In the example above, we store the result back into the same variable.
We also need to grab the first letter of the word.
first_letter = the_string[0]
second_letter = the_string[1]
third_letter = the_string[2]
Remember that we start counting from zero, not one, so we access the first letter by asking for [0].
Move it on Back
Now that we have the first letter stored, we need to add both the letter and the string stored in pyg to the end of the original string.
Remember how to concatenate (i.e. add) strings together?
greeting = "Hello "
name = "D. Y."
welcome = greeting + name
Ending Up
Well done! However, now we have the first letter showing up both at the beginning and near the end.
s = "Charlie"
print s[0]
# will print "C"
print s[1:4]
# will print "har"
First we create a variable s and give it the string "Charlie"
Next we access the first letter of "Charlie" using s[0]. Remember letter positions start at 0.
Then we access a slice of "Charlie" using s[1:4]. This returns everything from the letter at position 1 up till position 4.
We are going to slice the string just like in the 3rd example above.
Testing, Testing, is This Thing On?
Yay! You should have a fully functioning Pig Latin translator. Test your code thorougly to be sure everything is working smoothly.
You'll also want to take out any print statements you were using to help debug intermediate steps of your code. Now might be a good time to add some comments too! Making sure your code is clean, commented, and fully functional is just as important as writing it in the first place.
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = (word + first + pyg)[1:len(new_word)]
print new_word
else:
print 'empty'