Introduction to Python
Part of this chapter is based on tutorials by Geek Girls Carrots (https://github.com/ggcarrots/django-carrots).
Letâs write some code!
Python prompt
For readers at home: this part is covered in the Python Basics: Integers, Strings, Lists, Variables and Errors video.
To start playing with Python, we need to open up a command line on your computer. You should already know how to do that â you learned it in the Intro to Command Line chapter.
Once youâre ready, follow the instructions below.
We want to open up a Python console, so type in python on Windows and hit enter.
command-line
> python3
Python {{ book.py_release }} (...)
Type "help", "copyright", "credits" or "license" for more information.
>>>
Your first Python command!
After running the Python command, the prompt changed to >>>. For us this means that for now we may only
use commands in the Python language. You donât have to type in >>> â Python will do that for you.
If you want to exit the Python console at any point, type exit() or use the shortcut Ctrl + Z for
Windows and Ctrl + D for Mac/Linux. Then you wonât see >>> any longer.
For now, we donât want to exit the Python console. We want to learn more about it. Letâs start by typing
some math, like 2 + 3 and hitting enter.
command-line
>>> 2 + 3
5
Nice! See how the answer popped out? Python knows math! You could try other commands like:
4 * 55 - 140 / 2
To perform exponential calculation, say 2 to the power 3, we type:
command-line
>>> 2 ** 3
8
Have fun with this for a little while and then get back here. :)
As you can see, Python is a great calculator. If youâre wondering what else you can doâŚ
Strings
How about your name? Type your first name in quotes like this:
command-line
>>> "Ola"
'Ola'
Youâve now created your first string! Itâs a sequence of characters that can be processed by a computer.
The string must always begin and end with the same character. This may be single (') or double (")
quotes (there is no difference!) The quotes tell Python that whatâs inside of them is a string.
Strings can be strung together. Try this:
command-line
>>> "Hi there " + "Ola"
'Hi there Ola'
You can also multiply strings with a number:
command-line
>>> "Ola" * 3
'OlaOlaOla'
If you need to put an apostrophe inside your string, you have two ways to do it.
Using double quotes:
command-line
>>> "Runnin' down the hill"
"Runnin' down the hill"
or escaping the apostrophe with a backslash (\):
command-line
>>> 'Runnin\' down the hill'
"Runnin' down the hill"
Nice, huh? To see your name in uppercase letters, type:
command-line
>>> "Ola".upper()
'OLA'
You just used the upper method on your string! A method (like upper()) is a sequence of instructions
that Python has to perform on a given object ("Ola") once you call it.
If you want to know the number of letters contained in your name, there is a function for that too!
command-line
>>> len("Ola")
3
Wonder why sometimes you call functions with a . at the end of a string (like "Ola".upper()) and
sometimes you first call a function and place the string in parentheses? Well, in some cases, functions
belong to objects, like upper(), which can only be performed on strings. In this case, we call the
function a method. Other times, functions donât belong to anything specific and can be used on
different types of objects, just like len(). Thatâs why weâre giving "Ola" as a parameter to the
len function.
Summary
OK, enough of strings. So far youâve learned about:
- the prompt â typing commands (code) into the Python prompt results in answers in Python
- numbers and strings â in Python numbers are used for math and strings for text objects
- operators â like
+and*, combine values to produce a new one - functions â like
upper()andlen(), perform actions on objects.
These are the basics of every programming language you learn. Ready for something harder? We bet you are!
Errors
Letâs try something new. Can we get the length of a number the same way we could find out the length of
our name? Type in len(304023) and hit enter:
command-line
>>> len(304023)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()
We got our first error! The icon is our way of giving you a heads up that the code you are about to run wonât work as expected. Making mistakes (even intentional ones) are an important part of learning!
It says that objects of type âintâ (integers, whole numbers) have no length. So what can we do now? Maybe we can write our number as a string? Strings have a length, right?
command-line
>>> len(str(304023))
6
It worked! We used the str function inside of the len function. str() converts everything to strings.
- The
strfunction converts things into strings - The
intfunction converts things into integers
Important: we can convert numbers into text, but we canât necessarily convert text into numbers â what would
int('hello')be anyway?
Variables
An important concept in programming is variables. A variable is nothing more than a name for something so you can use it later. Programmers use these variables to store data, make their code more readable and so they donât have to keep remembering what things are.
Letâs say we want to create a new variable called name:
command-line
>>> name = "Ola"
We type name equals Ola.
As youâve noticed, your program didnât return anything like it did before. So how do we know that the
variable actually exists? Enter name and hit enter:
command-line
>>> name
'Ola'
Yippee! Your first variable! :) You can always change what it refers to:
command-line
>>> name = "Sonja"
>>> name
'Sonja'
You can use it in functions too:
command-line
>>> len(name)
5
Awesome, right? Now, variables can be anything â numbers too! Try this:
command-line
>>> a = 4
>>> b = 6
>>> a * b
24
But what if we used the wrong name? Can you guess what would happen? Letâs try!
command-line
>>> city = "Tokyo"
>>> ctiy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'ctiy' is not defined
An error! As you can see, Python has different types of errors and this one is called a NameError. Python will give you this error if you try to use a variable that hasnât been defined yet. If you encounter this error later, check your code to see if youâve mistyped any names.
Play with this for a while and see what you can do!
The print function
Try this:
command-line
>>> name = 'Maria'
>>> name
'Maria'
>>> print(name)
Maria
When you just type name, the Python interpreter responds with the string representation of the variable
ânameâ, which is the letters M-a-r-i-a, surrounded by single quotes, â. When you say print(name), Python
will âprintâ the contents of the variable to the screen, without the quotes, which is neater.
As weâll see later, print() is also useful when we want to print things from inside functions, or when we
want to print things on multiple lines.
Lists
Beside strings and integers, Python has all sorts of different types of objects. Now weâre going to introduce one called list. Lists are exactly what you think they are: objects which are lists of other objects. :)
Go ahead and create a list:
command-line
>>> []
[]
Yes, this list is empty. Not very useful, right? Letâs create a list of lottery numbers. We donât want to repeat ourselves all the time, so we will put it in a variable, too:
command-line
>>> lottery = [3, 42, 12, 19, 30, 59]
All right, we have a list! What can we do with it? Letâs see how many lottery numbers there are in a list. Do you have any idea which function you should use for that? You know this already!
command-line
>>> len(lottery)
6
Yes! len() can give you a number of objects in a list. Handy, right? Maybe we will sort it now:
command-line
>>> lottery.sort()
This doesnât return anything, it just changed the order in which the numbers appear in the list. Letâs print it out again and see what happened:
command-line
>>> print(lottery)
[3, 12, 19, 30, 42, 59]
As you can see, the numbers in your list are now sorted from the lowest to highest value. Congrats!
Maybe we want to reverse that order? Letâs do that!
command-line
>>> lottery.reverse()
>>> print(lottery)
[59, 42, 30, 19, 12, 3]
If you want to add something to your list, you can do this by typing this command:
command-line
>>> lottery.append(199)
>>> print(lottery)
[59, 42, 30, 19, 12, 3, 199]
If you want to show only the first number, you can do this by using indexes. An index is the number that says where in a list an item occurs. Programmers prefer to start counting at 0, so the first object in your list is at index 0, the next one is at 1, and so on. Try this:
command-line
>>> print(lottery[0])
59
>>> print(lottery[1])
42
As you can see, you can access different objects in your list by using the listâs name and the objectâs index inside of square brackets.
To delete something from your list you will need to use indexes as we learned above and the pop()
method. Letâs try an example and reinforce what we learned previously; we will be deleting the first number
of our list.
command-line
>>> print(lottery)
[59, 42, 30, 19, 12, 3, 199]
>>> print(lottery[0])
59
>>> lottery.pop(0)
59
>>> print(lottery)
[42, 30, 19, 12, 3, 199]
That worked like a charm!
For extra fun, try some other indexes: 6, 7, 1000, -1, -6 or -1000. See if you can predict the result before trying the command. Do the results make sense?
You can find a list of all available list methods in this chapter of the Python documentation: https://docs.python.org/3/tutorial/datastructures.html
Dictionaries
For readers at home: this part is covered in the Python Basics: Dictionaries video.
A dictionary is similar to a list, but you access values by looking up a key instead of a numeric index. A key can be any string or number. The syntax to define an empty dictionary is:
command-line
>>> {}
{}
This shows that you just created an empty dictionary. Hurray!
Now, try writing the following command (try substituting your own information, too):
command-line
>>> participant = {'name': 'Ola', 'country': 'Poland', 'favorite_numbers': [7, 42, 92]}
With this command, you just created a variable named participant with three keyâvalue pairs:
- The key
namepoints to the value'Ola'(astringobject), countrypoints to'Poland'(anotherstring),- and
favorite_numberspoints to[7, 42, 92](alistwith three numbers in it).
You can check the content of individual keys with this syntax:
command-line
>>> print(participant['name'])
Ola
See, itâs similar to a list. But you donât need to remember the index â just the name.
What happens if we ask Python the value of a key that doesnât exist? Can you guess? Letâs try it and see!
command-line
>>> participant['age']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'age'
Look, another error! This one is a KeyError. Python is helpful and tells you that the key 'age'
doesnât exist in this dictionary.
When should you use a dictionary or a list? Well, thatâs a good point to ponder. Think about the answer before looking at it in the next line.
- Do you just need an ordered sequence of items? Go for a list.
- Do you need to associate values with keys, so you can look them up efficiently (by key) later on? Use a dictionary.
Like lists, using the len() function on the dictionaries returns the number of keyâvalue pairs in the
dictionary. Go ahead and type in this command:
command-line
>>> len(participant)
3
Dictionaries, like lists, are mutable, meaning that they can be changed after they are created. You can add new keyâvalue pairs to a dictionary after it is created, like this:
command-line
>>> participant['favorite_language'] = 'Python'
I hope it makes sense up to now. :) Ready for some more fun with dictionaries? Read on for some amazing things.
You can use the pop() method to delete an item in the dictionary. Say, if you want to delete the entry
corresponding to the key 'favorite_numbers', type in the following command:
command-line
>>> participant.pop('favorite_numbers')
[7, 42, 92]
>>> participant
{'country': 'Poland', 'favorite_language': 'Python', 'name': 'Ola'}
As you can see from the output, the keyâvalue pair corresponding to the âfavorite_numbersâ key has been deleted.
As well as this, you can also change a value associated with an already-created key in the dictionary. Type this:
command-line
>>> participant['country'] = 'Germany'
>>> participant
{'country': 'Germany', 'favorite_language': 'Python', 'name': 'Ola'}
As you can see, the value of the key 'country' has been altered from 'Poland' to 'Germany'. :)
Exciting? Hurrah! You just learned another amazing thing.
Summary
Awesome! You know a lot about programming now. In this last part you learned about:
- errors â you now know how to read and understand errors that show up if Python doesnât understand a command youâve given it
- variables â names for objects that allow you to code more easily and to make your code more readable
- lists â lists of objects stored in a particular order
- dictionaries â objects stored as keyâvalue pairs
Excited for the next part? :)
Compare things
For readers at home: this part is covered in the Python Basics: Comparisons video.
A big part of programming involves comparing things. Whatâs the easiest thing to compare? Numbers! Letâs see how that works:
command-line
>>> 5 > 2
True
>>> 3 < 1
False
>>> 5 > 2 * 2
True
>>> 1 == 1
True
>>> 5 != 2
True
>>> len([1, 2, 3]) > len([4, 5])
True
We gave Python some numbers to compare. As you can see, not only can Python compare numbers, but it can
also compare values of mathematical expressions like 2 * 2 and function results like the 2 returned by
len([4, 5]). Nice, huh?
Do you wonder why we put two equal signs == next to each other to compare if numbers are equal? We use a
single = for assigning values to variables. You always, always need to put two of them â == â if
you want to check if things are equal to each other. We can also state that things are unequal to each
other. For that, we use the symbol !=, as shown in the example above.
Give Python two more tasks:
command-line
>>> 6 >= 12 / 2
True
>>> 3 <= 2
False
Weâve seen > and <, but what do >= and <= mean? Read them like this:
- x
>y means: x is greater than y - x
<y means: x is less than y - x
<=y means: x is less than or equal to y - x
>=y means: x is greater than or equal to y
Awesome! Wanna do one more? Try this:
command-line
>>> 6 > 2 and 2 < 3
True
>>> 3 > 2 and 2 < 1
False
>>> 3 > 2 or 2 < 1
True
You can give Python as many numbers to compare as you want, and it will give you an answer! Pretty smart, right?
- and â if you use the
andoperator, both comparisons have to be True in order for the whole command to be True - or â if you use the
oroperator, only one of the comparisons has to be True in order for the whole command to be True
Have you heard of the expression âcomparing apples to orangesâ? Letâs try the Python equivalent:
command-line
>>> 1 > 'django'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'int' and 'str'
Here you see that just like in the expression, Python is not able to compare a number (int) and a string (str).
Instead, it shows a TypeError and tells us the two types canât be compared together.
Boolean
Incidentally, you just learned about a new type of object in Python. Itâs called Boolean.
There are only two Boolean objects:
- True
- False
But for Python to understand this, you need to always write it as âTrueâ (first letter uppercase, with the rest of the letters lowercased). true, TRUE, and tRUE wonât work â only True is correct. (The same applies to âFalseâ as well.)
Booleans can be variables, too! See here:
command-line
>>> a = True
>>> a
True
You can also do it this way:
command-line
>>> a = 2 > 5
>>> a
False
Practice and have fun with Booleans by trying to run the following commands:
True and TrueFalse and TrueTrue or 1 == 11 != 2
Congrats! Booleans are one of the coolest features in programming, and you just learned how to use them!
Save it!
For readers at home: this part is covered in the Python Basics: Saving files and âIfâ statement video.
So far weâve been writing all our python code in the interpreter, which limits us to entering one line of code at a time. Normal programs are saved in files and executed by our programming language interpreter or compiler. So far weâve been running our programs one line at a time in the Python interpreter. Weâre going to need more than one line of code for the next few tasks, so weâll quickly need to:
- Exit the Python interpreter
- Open up our code editor of choice
- Save some code into a new python file
- Run it!
To exit from the Python interpreter that weâve been using, type the exit() function
command-line
>>> exit()
$
This will put you back into the command prompt.
Earlier, we picked out a code editor from the code editor section. Weâll need to open the editor now and write some code into a new file:
editor
print('Hello, Django girls!')
Obviously, youâre a pretty seasoned Python developer now, so feel free to write some code that youâve learned today.
Now we need to save the file and give it a descriptive name. Letâs call the file python_intro.py and save it to your desktop. We can name the file anything we want, but the important part here is to make sure the file ends in .py. The .py extension tells our operating system that this is a Python executable file and Python can run it.
Note You should notice one of the coolest thing about code editors: colors! In the Python console, everything was the same color; now you should see that the
defin a function, which weâll see below). This is one of the reasons we use a code editor. :)
With the file saved, itâs time to run it! Using the skills youâve learned in the command line section, use the terminal to change directories to the desktop.
On Windows Command Prompt, it will be like this:
command-line
> cd %HomePath%\Desktop
And on Windows Powershell, it will be like this:
command-line
> cd $Home\Desktop
f you get stuck, ask for help. Thatâs exactly what the coaches are here for!
Now use Python to execute the code in the file like this:
command-line
$ python3 python_intro.py
Hello, Django girls!
Note: on Windows âpython3â is not recognized as a command. Instead, use âpythonâ to execute the file:
command-line
> python python_intro.py
Alright! You just ran your first Python program that was saved to a file. Feel awesome?
You can now move on to an essential tool in programming:
If ⌠elif ⌠else
Lots of things in code should be executed only when given conditions are met. Thatâs why Python has something called if statements.
Replace the code in your python_intro.py file with this:
python_intro.py
if 3 > 2:
If we were to save and run this, weâd see an error like this:
command-line
$ python3 python_intro.py
File "python_intro.py", line 2
^
SyntaxError: unexpected EOF while parsing
Python expects us to give further instructions to it which are executed if the condition 3 > 2 turns out
to be true (or True for that matter). Letâs try to make Python print âIt works!â. Change your code in
your python_intro.py file to this:
python_intro.py
if 3 > 2:
print('It works!')
Notice how weâve indented the next line of code by 4 spaces? We need to do this so Python knows what code to run if the result is true. You can do one space, but nearly all Python programmers do 4 to make things look neat. A single Tab will also count as 4 spaces as long as your text editor is set to do so. When you made your choice, donât change it! If you already indented with 4 spaces, make any future indentation with 4 spaces, too - otherwise you may run into problems.
Save it and give it another run:
command-line
$ python3 python_intro.py
It works!
Note: Remember that on Windows, âpython3â is not recognized as a command. From now on, replace âpython3â with âpythonâ to execute the file.
What if a condition isnât True?
In previous examples, code was executed only when the conditions were True. But Python also has elif and
else statements:
python_intro.py
if 5 > 2:
print('5 is indeed greater than 2')
else:
print('5 is not greater than 2')
When this is run it will print out:
command-line
$ python3 python_intro.py
5 is indeed greater than 2
If 2 were a greater number than 5, then the second command would be executed. Letâs see how elif works:
python_intro.py
name = 'Sonja'
if name == 'Ola':
print('Hey Ola!')
elif name == 'Sonja':
print('Hey Sonja!')
else:
print('Hey anonymous!')
and executed:
command-line
$ python3 python_intro.py
Hey Sonja!
See what happened there? elif lets you add extra conditions that run if the previous conditions fail.
You can add as many elif statements as you like after your initial if statement. For example:
python_intro.py
volume = 57
if volume < 20:
print("It's kinda quiet.")
elif 20 <= volume < 40:
print("It's nice for background music")
elif 40 <= volume < 60:
print("Perfect, I can hear all the details")
elif 60 <= volume < 80:
print("Nice for parties")
elif 80 <= volume < 100:
print("A bit loud!")
else:
print("My ears are hurting! :(")
Python runs through each test in sequence and prints:
command-line
$ python3 python_intro.py
Perfect, I can hear all the details
Comments
Comments are lines beginning with #. You can write whatever you want after the # and Python will ignore
it. Comments can make your code easier for other people to understand.
Letâs see how that looks:
python_intro.py
# Change the volume if it's too loud or too quiet
if volume < 20 or volume > 80:
volume = 50
print("That's better!")
You donât need to write a comment for every line of code, but they are useful for explaining why your code is doing something, or providing a summary when itâs doing something complex.
Summary
In the last few exercises you learned about:
- comparing things â in Python you can compare things by using
>,>=,==,<=,<and theand,oroperators - Boolean â a type of object that can only have one of two values:
TrueorFalse - Saving files â storing code in files so you can execute larger programs.
- if ⌠elif ⌠else â statements that allow you to execute code only when certain conditions are met.
- comments - lines that Python wonât run which let you document your code
Time for the last part of this chapter!
Your own functions!
For readers at home: this part is covered in the Python Basics: Functions video.
Remember functions like len() that you can execute in Python? Well, good news â you will learn how to
write your own functions now!
A function is a sequence of instructions that Python should execute. Each function in Python starts with
the keyword def, is given a name, and can have some parameters. Letâs give it a go. Replace the code in
python_intro.py with the following:
python_intro.py
def hi():
print('Hi there!')
print('How are you?')
hi()
Okay, our first function is ready!
You may wonder why weâve written the name of the function at the bottom of the file. When we write
def hi(): and the indented lines following, this is us writing instructions for what the hi() function
should do. Python will read and remember these instructions, but wonât run the function yet. To tell Python
we want to run the function, we have to call the function with hi(). Python reads the file and executes
it from top to bottom, so we have to define the function in the file before we call it.
Letâs run this now and see what happens:
command-line
$ python3 python_intro.py
Hi there!
How are you?
Note: if it didnât work, donât panic! The output will help you to figure why:
- If you get a
NameError, that probably means you typed something wrong, so you should check that you used the same name when creating the function withdef hi():and when calling it withhi(). - If you get an
IndentationError, check that both of theprintlines have the same whitespace at the start of a line: python wants all the code inside the function to be neatly aligned. - If thereâs no output at all, check that the last
hi()isnât indented - if it is, that line will become part of the function too, and it will never get run.
Letâs build our first function with parameters. We will change the previous example â a function that says âhiâ to the person running it â with a name:
python_intro.py
def hi(name):
As you can see, we now gave our function a parameter that we called name:
python_intro.py
def hi(name):
if name == 'Ola':
print('Hi Ola!')
elif name == 'Sonja':
print('Hi Sonja!')
else:
print('Hi anonymous!')
hi()
Remember: The print function is indented four spaces within the if statement. This is because the
function runs when the condition is met. Letâs see how it works now:
command-line
$ python3 python_intro.py
Traceback (most recent call last):
File "python_intro.py", line 10, in <module>
hi()
TypeError: hi() missing 1 required positional argument: 'name'
Oops, an error. Luckily, Python gives us a pretty useful error message.
It tells us that the function hi() (the one we defined) has one required argument (called name) and
that we forgot to pass it when calling the function.
Letâs fix it at the bottom of the file:
python_intro.py
hi("Ola")
And run it again:
command-line
$ python3 python_intro.py
Hi Ola!
And if we change the name?
python_intro.py
hi("Sonja")
And run it:
command-line
$ python3 python_intro.py
Hi Sonja!
Now, what do you think will happen if you write another name in there? (Not Ola or Sonja.) Give it a try and see if youâre right. It should print out this:
command-line
Hi anonymous!
This is awesome, right? This way you donât have to repeat yourself every time you want to change the name of the person the function is supposed to greet. And thatâs exactly why we need functions â you never want to repeat your code!
Letâs do something smarter â there are more names than two, and writing a condition for each would be hard, right? Replace the content of your file with the following:
python_intro.py
def hi(name):
print('Hi ' + name + '!')
hi("Rachel")
Letâs call the code now:
command-line
$ python3 python_intro.py
Hi Rachel!
Congratulations! You just learned how to write functions! :)
Loops
For readers at home: this part is covered in the Python Basics: For Loop video.
This is the last part already. That was quick, right? :)
Programmers donât like to repeat themselves. Programming is all about automating things, so we donât want to greet every person by their name manually, right? Thatâs where loops come in handy.
Still remember lists? Letâs do a list of girls:
python_intro.py
girls = ['Rachel', 'Monica', 'Phoebe', 'Ola', 'You']
We want to greet all of them by their name. We have the hi function to do that, so letâs use it in a loop:
python_intro.py
for name in girls:
The for statement behaves similarly to the if statement; code below both of these need to be indented four spaces.
Here is the full code that will be in the file:
python_intro.py
def hi(name):
print('Hi ' + name + '!')
girls = ['Rachel', 'Monica', 'Phoebe', 'Ola', 'You']
for name in girls:
hi(name)
print('Next girl')
And when we run it:
command-line
$ python3 python_intro.py
Hi Rachel!
Next girl
Hi Monica!
Next girl
Hi Phoebe!
Next girl
Hi Ola!
Next girl
Hi You!
Next girl
As you can see, everything you put inside a for statement with an indent will be repeated for every
element of the list girls.
You can also use for on numbers using the range function:
python_intro.py
for i in range(1, 6):
print(i)
Which would print:
command-line
1
2
3
4
5
range is a function that creates a list of numbers following one after the other (these numbers are
provided by you as parameters).
Note that the second of these two numbers is not included in the list that is output by Python (meaning
range(1, 6) counts from 1 to 5, but does not include the number 6). That is because range is half-open,
and by that we mean it includes the first value, but not the last.
Summary
Thatâs it. You totally rock! This was a tricky chapter, so you should feel proud of yourself. Weâre definitely proud of you for making it this far!
For official and full python tutorial visit https://docs.python.org/3/tutorial/. This will give you a more thorough and complete study of the language. Cheers! :)
You might want to briefly do something else â stretch, walk around for a bit, rest your eyes â before going on to the next chapter. :)
