Python-3-Basics-Tutorial-En
Python-3-Basics-Tutorial-En
of Contents
Introduction 1.1
Dictionaries 1.9.1
Tuples 1.9.2
Reading from the keyboard 1.9.3
Modules 1.9.8
Introspection 1.9.9
Acknowledgements 1.13
2
3
Introduction
Distributed under the conditions of the Creative Commons Attribution Share-alike License 4.0
Introduction
you have worked a little with a different programming language like R, MATLAB or C.
you have no programming experience at all
you know Python well and would like to teach others
This tutorial works best if you follow the chapters and exercises step by step.
The authorities of the United States have recorded the first names of all people born as U.S. citizens since 1880. The
dataset is publicly available on http://www.ssa.gov/oact/babynames/limits.html . However for the protection of privacy only
names used at least 5 times appear in the data.
4
Introduction
For a tutorial for non-beginners, I recommend the following free online books:
5
Installing Python
Installing Python
The first step into programming is to get Python installed on your computer. You will need two things
Python itself
a text editor
On Ubuntu Linux
By default, Python is already installed. In this tutorial however, we will use Python3 whenever possible. You can install it
from a terminal window with:
ipython3
As a text editor, it is fine to start with gedit. Please make sure to change tabs to spaces via Edit -> Preferences -> Editor ->
tick 'Insert spaces instead of tabs'.
On Windows
A convenient way to install Python, an editor and many additional packages in one go is Anaconda, a Python distribution
with many pre-installed packages for scientific applications.
After installing, you will need to launch the Spyder editor from the Start menu.
Questions
Question 1
Which text editors are installed on your system?
Question 2
Which Python version are you running?
6
Installing Python
7
First steps in the IPython Shell
In the first part of the tutorial, you will use the IPython shell to write simple commands.
Goals
The commands on the IPython shell cover:
8
Using Python as a calculator
In [1]:
In [1]: 1 + ___
Out[1]: 3
In [2]: 12 ___ 8
Out[2]: 4
In [3]: ___ * 5
Out[3]: 20
In [4]: 21 / 7
Out[4]: ___
In [5]: ___ ** 2
Out[5]: 81
Enter the commands to see what happens (do not type the first part In [1] etc., these will appear automatically).
Exercise 2:
Which operations result in 8?
0 + 8
4 4
8 /
65 // 8
17 % 9
2 * * 4
64 ** 0.5
Exercise 3:
Collect the Python operators you already know in a table ( + , - , * etc.).
9
Storing numbers
Storing numbers
The U.S. authorities record the names of all babies born since 1880. How many babies with more or less popular names
were born in 2000? Let's store the numbers in variables.
Exercise 1:
Let's define some variables. Fill in the gaps:
Exercise 2:
Let's change the content. Insert the correct values and variable names into the blanks.
In [9]: all_babies = 0
In [10]: all_babies = _____ + _____ + _____
In [11]: all_babies
Out[11]: 49031
If you like maths, you may sigh loud at the notion of redefining a variable every few lines.
Exercise 3:
Which of the following variable names are correct? Try assigning some numbers to them.
Sarah
ASHLEY
madison alexis
sam90
2000jessy
liz_lauren
alyssa.kay
Exercise 4:
Which are correct variable assignments?
a = 1 * 2
2 = 1 + 1
5 + 6 = y
seven = 3 * 4
10
Storing numbers
11
Storing text
Storing text
Exercise 1:
So far, we have only worked with numbers. Now we will work with text as well.
Exercise 2:
What do the following statements do?
In [5]: name[0]
In [6]: name[3]
In [7]: name[-1]
Exercise 3:
Is it possible to include the following special characters in a string?
Exercise 4:
What does name contain after the following statements? Explain the code.
12
Writing Python programs
In this chapter, we will learn to know the print() function for producing output, loops and branching statements.
Turing Completeness
In the second part of the tutorial, you will learn a basic set of Python commands. Theoretically, they are sufficient to write
any program on the planet (this is called Turing completeness).
Practically, you will need shortcuts that make programs prettier, faster, and less painful to write. We will save these
shortcuts for the later parts.
13
Writing Python programs
14
My first program
My first program
Using the interactive IPython shell alone is exciting only for a while. To write more complex programs, you need to store
your instructions in programs, so that you can execute them later.
In this section we will write our first Python program. It is going to simply write a few names of babies to the screen.
Exercise 1
Open a text editor (e.g. Spyder) and create a new file. Write into it:
print("Hannah")
print(23073)
Exercise 2
Now let's execute our program.
python3 output.py
Exercise 3
Explain the following program:
name = "Emily"
jahr = 2000
print(name, jahr)
Exercise 4
Write the following program:
name = "Emily"
name
15
Repeating instructions
Repeating instructions
In our early programs, each Python instruction was executed only once. That makes programming a bit pointless, because
our programs are limited by our typing speed.
In this section we will take a closer look at the for statement that repeats one or more instructions several times.
Exercise 1
What does the following program do?
Exercise 2
What advantages does the for loop have over the following one?
print(0)
print(1)
print(2)
print(3)
print(4)
..
Exercise 3
Write a for loop that creates the following output
1
4
9
16
25
36
49
Exercise 4
Explain the difference between the following two programs:
total = 0
for number in range(10):
total = total + number
print(total)
and
total = 0
for number in range(10):
total = total + number
print(total)
Exercise 5
16
Repeating instructions
text = ""
characters = "Hannah"
for char in characters:
text = char + text
print(text)
Exercise 6
Write a program that calculates the number of characters in Stefani Joanne Angelina Germanotta . Spaces count as well!
17
Making decisions
Making decisions
The last missing piece in our basic set of commands is the ability to make decisions in a program. This is done in Python
using the if command.
Exercise 1
Execute the following program and explain its output.
number = 123
Exercise 2
Set name to such a value that one, two or all three conditions apply.
name = ____
if "m" in name:
print("There is a 'm' in the name.")
if name != "Mimi":
print("The name is not Mimi.")
if name[0] == "M" and name[-1] == "m":
print("The name starts and ends with m.")
Exercise 3
18
Making decisions
The following program writes the positions of all letters "n" in the name to the screen. Unfortunately, it contains three
errors. Make the program execute correctly:
name = "Anna"
position = 1
Exercise 4
Which of these if statements are syntactically correct?
if a and b:
if len(s) == 23:
if a ** 2 >= 49:
if a != 3
19
Overview of data types in Python
Data types
Match the data samples with their types.
Definitions
List [1, 2, 2, 3]
20
Overview of data types in Python
Type conversions
Values can be converted into each other using conversion functions. Try the following:
int('5.5')
float(5)
str(5.5)
list("ABC")
tuple([1,2,3])
dict([('A',1),('B',2)])
set([1,2,2,3])
21
Lists
Lists
To handle larger amounts of data, we cannot invent a new variable for every new data item. Somehow we need to store
more data in one variable. This is where Python lists come in.
22
Creating lists
Creating lists
Exercise 1
Find out what each of the expressions does to the list in the center.
Exercise 2
What does the following program do?
Exercise 3
How many babies are there in total? Write a program that calculates that number.
Exercise 4
You have a list of the 20 most popular girls names from the year 2000:
Write a program that prints all names starting with 'A' or 'M' .
23
Creating lists
Exercise 5
Use the expressions to modify the list as indicated. Use each expression once.
Exercise 6
Create a new list containing the sum of California and New York for each name.
Exercise 7
Use the expressions to modify the list as indicated. Use each expression once.
24
Creating lists
25
Shortcuts
Shortcuts
Exercise 1
Simplify the following code using the function sum() :
total = 0
for number in data:
total = total + number
print(total)
Exercise 2
Simplify the following code using the function range() :
i = 0
while i < 10:
print(i * '*')
i += 1
Exercise 3
Simplify the following code using the function zip() :
table = []
i = 0
while i < len(names):
row = (names[i], counts[i])
table.append(row)
i += 1
print(table)
Exercise 4
Simplify the following code using the function enumerate() :
i = 0
for name in names:
print(i, name)
i += 1
Exercise 5
Use list(range()) to create the following lists:
[4, 7, 9, 12]
Exercise 6
26
Shortcuts
lists
dictionaries
strings
floats
sets
27
Working with tables
Tables
Data frequently occurs in the form of tables. To process tables in Python, it helps to know that we can put lists in other lists.
These are also called nested lists.
In this chapter we will deal with creating and processing nested lists.
Exercise 1
Write all rows of the above table to the screen with a for loop.
Exercise 2
Write all cells of the table to the screen with a double for loop.
Exercise 3
Create an empty table of 10 x 10 cells and fill them with numbers from 1 to 100.
Exercise 4
Sort the above table by the second column. Use the following code sniplet:
28
Reading data from files
For the next exercises, you will need the complete archive of baby names (the shorter one not grouped by states). You can
download the files from http://www.ssa.gov/oact/babynames/limits.html.
29
Reading a simple text file
Emily,F,12562
Amy,F,2178
Penny,F,342
Bernadette,F,129
Leonard,M,384
Howard,M,208
Sheldon,M,164
Stuart,M,82
Raj,M,41
Exercise 1:
Make the program work by inserting close , line , bigbang.txt , print into the gaps.
f = open(___)
for ____ in f:
____(line)
f.____()
Hint:
Depending on your editor, you may need to insert the complete path to the file. If the program does not work, a wrong file
name or location are the most probable reasons.
Exercise 3
How many different girls names were there in 2015?
girls = 0
if "B" in line:
print(girls)
if ",F," in line:
girls += 1
Exercise 4
Extend the program from the previous exercise such that boys and girls names are counted separately.
Exercise 5
Which of the following commands are correct?
30
Reading a simple text file
for i in range(10):
for k in 3+7:
Exercise 6
Write a program that reads lines from the file yob2015.txt . Identify all lines containing your name and print them to the
screen.
31
Extracting data from text
Exercise 1
Insert the following pieces into the code, so that all commands are executed correctly: age , int(age) , name , str(born) ,
2000
text = ____ + ' was born in the year ' + _____ + '.'
year = born + _____
text
year
Exercise 2
The following program collects names in a list that occur at least 10000 times. Unfortunately, the program contains four
errors. Find and fix these.
frequent = []
print(frequent)
Exercise 3
Write a program that calculates the total number of babys for the year 2015 and writes it to the screen. Compare that
number with the year 1915.
Exercise 4
Write a program that finds the three most frequent names for boys and girls in a given year and writes them to the screen.
Hint: The three most frequent names are on top of the list.
Exercise 5
Write a program that calculates the percentage of the 10 most frequent names for the year 2015 and writes it to the screen.
32
Writing files
Writing Files
Exercise 1
Form pairs of Python commands and their meanings.
Exercise 2
Execute the following program. Explain what happens.
f = open('boys.txt', 'w')
for name in names:
f.write(name + '\n')
f.close()
Exercise 3
Remove the + '\n' from the program and execute it again. What happens?
Exercise 4
Complete the following statements by int() or str() so that all of them work.
33
Writing files
In [1]: 9 + 9
In [2]: 9 + '9'
In [4]: 9 * '9'
Exercise 5
Write a program that writes the following data into a two-column text file.
34
Processing multiple files
The code contains a subtle semantic bug. Execute the program. Inspect the output. Find and fix the bug.
births = []
result = 0
Exercise 2
Write a program that finds lines containing your name in the years 1880 to 2014.
Exercise 3
Extend the program in such a way that the gender is being checked as well. Print only lines with matching 'M' or 'F' ,
respectively.
Exercise 4
Collect all matches in a list.
Exercise 5
If no matches were found in a given year, add a 0 to the result.
35
Screen output
Screen output
In this chapter we will explor the print() function to write text to the screen.
Exercise 1
Which print statements are correct?
print("9" + "9")
print "nine"
print(str(9) + "nine")
print(9 + 9)
print(nine)
Exercise 2
Explain the following statement:
print("Emily\tSmith\n2000")
Exercise 3
Some babies have names similar to celebrities. Write a program producing the following output:
Exercise 4
Expand the previous exercise so that:
36
String methods
String methods
Exercise 1
Determine what the expressions do to the string in the center.
Exercise 2
The following program identifies names used for both girls and boys and writes them to a file.
Complete the code to dissect lines to columns, so that the variables name and gender are defined.
girls = []
duplicates = []
if gender == 'F':
girls.append(name)
elif gender == 'M':
if name in girls:
duplicates.append(name)
37
String methods
38
Format strings
Format Strings
Exercise 1
Try the following expressions in a Python shell:
"{}".format("Hello")
"{:10}".format("Hello")
"{:>10}".format("Hello")
"{1} {0}".format("first", "second")
"{:5d}".format(42)
"{:4.1f}".format(3.14159)
"{:6.3f}".format(3.14159)
Exercise 2
Write a for loop producing the following string:
000111222333444555666777888999
Exercise 3
You have the following two lists:
Write a program that creates a table with two vertically aligned columns.
39
Dictionaries
Dictionaries
Exercise 1
Find out what each of the expressions does to the dictionary in the center.
Exercise 2
What do the following commands produce?
False
"B"
True
Exercise 3
What do these commands produce?
40
Dictionaries
True
"B"
False
Exercise 4
What do these commands produce?
True
['A', 1, True]
Exercise 5
What do these commands produce?
['A', 'B', 1]
Exercise 6
What do these commands produce?
None
'C'
an Error
False
Exercise 7
What do these commands produce?
'C'
None
41
Dictionaries
an Error
42
Tuples
Tuples
A tuple is a sequence of elements that cannot be modified. They are useful to group elements of different type.
t = ('bananas','200g',0.55)
Exercises
Exercise 1
Which are correct tuples?
[ ] (1, 2, 3)
[ ] ("Jack", "Knife")
[ ] ('blue', [0, 0, 255])
[ ] [1, "word"]
Exercise 2
What can you do with tuples?
43
Reading from the keyboard
Warming up
What happens when you write the follwing lines in the IPython shell:
In [1]: a = input()
In [2]: a
Exercise 1
Which input statements are correct?
[ ] a = input()
[ ] a = input("enter a number")
[ ] a = input(enter your name)
[ ] a = input(3)
Extra challenge:
Add 1 to the age entered.
44
Converting numbers to text and back
Warming up
Now we are going to combine strings with integer numbers.
Insert into the following items into the code, so that all statements are working: age , int(age) , name, str(born) , 2000
Questions
Can you leave str(born) and int(age) away?
What do str() and int() do?
Exercises
Exercise 1:
What is the result of the following statements?
9 + 9
9 + '9'
'9' + '9'
Exercise 2:
Change the statements above by adding int() or str() to each of them, so that the result is 18 or '99', respectively.
Exercise 3:
Explain the result of the following operations?
9 * 9
9 * '9'
'9' * 9
Exercise 4:
Write Python statements that create the following string:
45
Converting numbers to text and back
12345678901234567890123456789012345678901234567890
gender M string
age 15 integer
Write the values from each row of the table into string or integer variables, then combine them to a single one-line string.
46
Structuring programs
Structuring programs
In Python, you can structure programs on four different levels: with functions, classes, modules and packages. Of these,
classes are the most complicated to use. Therefore they are skipped in this tutorial.
Goals
Learn to write functions
Learn to write modules
Learn to write packages
Know some standard library modules
Know some installable modules
47
Writing your own functions
Functions
Python 3.5 has 72 builtin functions. To start writing useful programs, knowing about 25 of them is sufficient. Many of these
functions are useful shortcuts that make your programs shorter.
48
Modules
Modules
What is a module?
Any Python file (ending .py) can be imported from another Python script. A single Python file is also called a module.
Importing modules
To import from a module, its name (without .py) needs to be given in the import statement. Import statements can look like
this:
import fruit
import fruit as f
from fruit import fruit_prices
from my_package.fruit import fruit_prices
It is strongly recommended to list the imported variables and functions explicitly instead of using the import * syntax. This
makes debugging a lot easier.
When importing, Python generates intermediate code files (in the pycache directory) that help to execute programs faster.
They are managed automatically, and dont need to be updated.
49
Introspection
Introspection
Warming up
Try the following on the interactive shell:
import random
dir(random)
help(random.choice)
name = random.choice(['Hannah', 'Emily', 'Sarah'])
type(name)
Extra challenges:
let the user choose the gender of the babies.
let the user enter how many babies they want to have.
load baby names from a file.
50
Working with directories
Warming up
Fill in the gaps
Exercise 1
Explain the following code:
import os
for dirname in os.listdir('.'):
print(dirname)
Exercise 1
Write a program that counts the number of files in the unzipped set of baby names. Have the program print that number.
51
Working with directories
Exercise 2
How many entries (lines) does the entire name dataset have?
Hint: Generate a message that tells you which file the program is reading.
Exercise 3
Write a program that finds the most frequently occuring name in each year and prints it.
The Challenge
Find and print your name and the according number in each of the files, so that you can see how the number changes over
time.
52
Programming Challenge: Count Words in Moby Dick
Your Task
Write a program that counts how often each word occurs in the book. Determine how often the words captain and whale
occur. You will need different data structures for counting words and for sorting them.
When you know whether whale or captain occurs more often, you have mastered this challenge.
Background
You can find the full text for Herman Melville’s “Moby Dick” in the text file mobydick.txt and on www.gutenberg.org.
53
Background information on Python 3
What is Python?
Python is an interpreted language.
Python uses dynamic typing.
Python 3 is not compatible to Python 2.x
The Python interpreter generates intermediate code (in the pycache directory).
Strengths
Quick to write, no compilation
Fully object-oriented
Many reliable libraries
All-round language
100% free software
Weaknesses
Writing very fast programs is not straightforward
No strict encapsulation
54
Recommended books and websites
Paper books
Managing your Biological Data with Python - Allegra Via, Kristian Rother and Anna Tramontano
Data Science from Scratch - Joel Grus
Websites
Main documentation and tutorial: http://www.python.org/doc
Tutorial for experienced programmers: http://www.diveintopython.org
Tutorial for beginners: http://greenteapress.com/thinkpython/thinkCSpy/html/
Comprehensive list of Python tutorials, websites and books: http://www.whoishostingthis.com/resources/python/
Python Library Reference covering the language basics: https://docs.python.org/3/library/index.html
Global Module Index – description of standard modules: https://docs.python.org/3/py-modindex.html
55
Acknowledgements
Authors
© 2013 Kristian Rother ([email protected])
This document contains contributions by Allegra Via, Kaja Milanowska and Anna Philips.
License
Distributed under the conditions of a Creative Commons Attribution Share-alike License 3.0.
Acknowledgements
I would like to thank the following people for inspiring exchange on training and Python that this tutorial has benefited from:
Pedro Fernandes, Tomasz Puton, Edward Jenkins, Bernard Szlachta, Robert Lehmann and Magdalena Rother
56