Python 3 Basics Tutorial

Python 3 Basics Tutorial Table of Contents Introduction 0 The dataset of U.S. baby names 1 Installing Python 2 Fi

Views 128 Downloads 0 File size 2MB

Report DMCA / Copyright

DOWNLOAD FILE

Recommend stories

Citation preview

Python 3 Basics Tutorial

Table of Contents Introduction

0

The dataset of U.S. baby names

1

Installing Python

2

First steps on the IPython Shell

3

Using Python as a calculator

3.1

Warming up

3.1.1

Definitions

3.1.2

Exercises

3.1.3

Storing numbers

3.2

Warming up

3.2.1

Definitions

3.2.2

Exercises

3.2.3

Storing text

3.3

Warming up

3.3.1

Definitions

3.3.2

Exercises

3.3.3

Converting numbers to text and back

3.4

Warming up

3.4.1

Definitions

3.4.2

Exercises

3.4.3

Writing Python programs

4

Writing to the screen

4.1

Warming up

4.1.1

Definitions

4.1.2

Exercises

4.1.3

Reading from the keyboard

4.2

Warming up

4.2.1

Definitions

4.2.2

Exercises

4.2.3

Repeating instructions

4.3

2

Python 3 Basics Tutorial

Warming up

4.3.1

Definitions

4.3.2

Exercises

4.3.3

Storing lists of items

4.4

Warming up

4.4.1

Definitions

4.4.2

Exercises

4.4.3

Making decisions

4.5

Warming up

4.5.1

Definitions

4.5.2

Exercises

4.5.3

Reading and writing files Reading a text file

5 5.1

Warming up

5.1.1

Definitions

5.1.2

Exercises

5.1.3

Writing a text file

5.2

Warming up

5.2.1

Definitions

5.2.2

Exercises

5.2.3

File parsing

5.3

Warming up

5.3.1

Definitions

5.3.2

Exercises

5.3.3

Working with directories

5.4

Warming up

5.4.1

Definitions

5.4.2

Exercises

5.4.3

Using external modules Introspection

6 6.1

Warming up

6.1.1

Definitions

6.1.2

Standard modules and libraries re

6.2 6.2.1 3

Python 3 Basics Tutorial

xml

6.2.2

urllib

6.2.3

time

6.2.4

csv

6.2.5

Installable modules and libraries

6.3

pandas

6.3.1

xlrd

6.3.2

scipy

6.3.3

matplotlib

6.3.4

pillow

6.3.5

Leftovers

7

Overview of Data types in Python

7.1

Dictionaries

7.2

Tuples

7.3

while

7.4

List functions

7.5

Structuring bigger programs

8

Functions

8.1

Modules

8.2

Packages

8.3

Background information on Python 3

9

Recommended books and websites

10

Acknowledgements

11

4

Python 3 Basics Tutorial

Python 3 Basics Tutorial (c) 2015 Dr. Kristian Rother ([email protected]) with contributions by Allegra Via, Kaja Milanowska and Anna Philips Distributed under the conditions of the Creative Commons Attribution Share-alike License 4.0 Sources of this document can be found on https://github.com/krother/Python3_Basics_Tutorial

Introduction Who is this tutorial for? This is a tutorial for novice programmers. You are the learner I had in mind when writing this tutorial if: 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.

If you are an experienced programmer If you are fluent in any programming language, this tutorial might be very easy for you. Of course, you can work through the exercises to get the Python syntax into your fingers. However, this tutorial contains very little material on the higher abstraction levels in Python, like classes, namespaces or even functions. For a tutorial for non-beginners, I recommend the following free online books: Learn Python the Hard Way - a bootcamp-style tutorial by Zed Shaw How to think like a Computer Scientist - a very systematic, scientific tutorial by Allen B. Downey Dive into Python 3 - explains one sophisticated program per chapter - by Mark Pilgrim

Introduction

5

Python 3 Basics Tutorial

The dataset of U.S. baby names

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. Throughout this tutorial, we will work with this data.

The dataset of U.S. baby names

6

Python 3 Basics Tutorial

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 Which to install, depends on your operating system.

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: sudo apt-get install python3 sudo apt-get install ipython3

To check whether everything worked, type: 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 Canopy. Download and install it from the website. After installing, you will need to set up Canopy from the Start menu. Select the first item from the Enthought Canopy group and click through the dialog.

Other Python distributions Python 3 - the standard Python installation Anaconda - a Python distribution with many pre-installed packages for scientific

Installing Python

7

Python 3 Basics Tutorial

applications

Other editors Idle - the standard editor Sublime Text - a very powerful text editor for all operating systems Notepad++ - a powerful text editor for Windows. Please do not use the standard Notepad. It won't get you anywhere. PyCharm - a professional Python development environment capable of handling large projects. You won't need most of the functionality for a long time, but it is a well-written editor. vim - a console-based text editor for Unix systems. The tool of choice for many system administrators.

Questions Question 1 Which text editors are installed on your system?

Question 2 Which Python version are you running?

Installing Python

8

Python 3 Basics Tutorial

First steps on the IPython Shell There are two ways to use Python: The interactive mode or IPython shell and writing programs. We will use the interactive mode to store data on U.S. baby names. 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: How to store a number? How to add two numbers together? How to store text? How to convert a number to text and back?

First steps on the IPython Shell

9

Python 3 Basics Tutorial

Using Python as a calculator The Challenge: Boys' names total In the table, you find the five most popular boys' names from the year 2000. What is the total number of boys in the top5? name

number

Jacob

34465

Michael

32025

Matthew

28569

Joshua

27531

Christopher

24928

Using Python as a calculator

10

Python 3 Basics Tutorial

Warming up Enter Python in the interactive mode. You should see a message In [1]:

Complete the following calculations by filling in the blanks: 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).

Warming up

11

Python 3 Basics Tutorial

Definitions IPython shell The IPython shell allows you to enter Python commands one by one and executes them promptly. The IPython shell is a luxury version of the simpler Python shell. It is also called interactive mode or interactive Python command line. You can use any Python command from the IPython Shell: In [1]: 1 + 1 Out[1]: 2 In [2]: 4 * 16 Out[2]: 64 In [3]:

Results of each command are automatically printed to the screen.

How to leave the IPython shell? You can leave the command line by Ctrl-z (Windows) or Ctrl-d (Linux). If a program seems to be stuck, you can interrupt the shell with Ctrl-c.

Integer numbers The numerical values in the calculations are called integers. An integer is a number that has no decimal places. In Python, integers are a predefined data type. Later, we will learn to know other kinds of numbers and data types.

Operators The arithmetical symbols like + - * / connecting two numbers are called operators. Generally, operators connect two values.

Arithmetical operators

Definitions

12

Python 3 Basics Tutorial

a = 7 b = 4 c = a - b d = a * b e = a / b f = a % b # modulo, 3 g = a ** 2 # 49 h = 7.0 // b # floor division, 1.0

Definitions

13

Python 3 Basics Tutorial

Exercises Complete the following exercises:

Exercise 1: There are more operators in Python. Find out what the following operators do? 3 ** 3 24 % 5 23 // 10

Exercise 2: Which of the following Python statements are valid? Try them in the IPython shell. 0 + 1 2 3 4-5 6 * * 7 8 / 9

Exercise 3: Which operations result in 8? [ ] 65 // 8 [ ] 17 % 9 [ ] 2 ** 4 [ ] 64 ** 0.5

Exercises

14

Python 3 Basics Tutorial

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.

The Challenge: Calculate an average What is the average number of the top five boy names? Calculate the number and store it in a variable. Make a very rough estimate before you do the calculation.

Storing numbers

15

Python 3 Basics Tutorial

Warming up Let's define some variables: In [1]: emily = 25952 In [2]: hannah = 23073 In [3]: khaleesi = 5 In [4]: emily Out[4]: ______ In [5]: hannah + 1 Out[5]: ______ In [6]: 3 * khaleesi Out[6]: ______

Let's change the content: In [7]: emily = emily + 1 In [8]: emily Out[8]: _____ In [9]: all_babies = 0 In [10]: all_babies = _____ + _____ + _____ In [11]: all_babies Out[11]: 49031

Insert the correct values and variable names into the blanks.

Warming up

16

Python 3 Basics Tutorial

Definitions Variables Variables are 'named containers' used to store values within Python. Variable names may be composed of letters, underscores and, after the first position, also digits. Lowercase letters are common, uppercase letters are usually used for constants like PI . Variables can be used for calculating in place of the values they contain.

Variable assignments The operator = is used in Python to define a variable. A Python statement containing an = is called a variable assignment. The value on the right side of the equal sign will be

stored in a variable with the name on the left side.

Changing variables You may assign to the same variable name twice: In [1]: emily = 25952 In [2]: emily = 25953 In [3]: emily Out[3]: ______

In this case, the first value is overwritten by the second assignment. There is no way to obtain it afterwards.

Python Statements The lines you are writing all the time are also called Python Statements. A Statement is the smallest executable piece of code. So far, you have seen at least three different kinds of statements: Calculate a number Put a number into a variable

Definitions

17

Python 3 Basics Tutorial

Print the number from a variable on the screen In the next lessons, you will learn to know lots of other statements.

Definitions

18

Python 3 Basics Tutorial

Exercises Complete the following exercises:

Exercise 1: Which of the following variable names are correct? Try assigning some numbers to them. Emily EMILY emily brown emily25 25emily emily_brown emily.brown

Exercise 2: Which are correct variable assignments? [ ] a = 1 * 2 [ ] 2 = 1 + 1 [ ] 5 + 6 = y [ ] seven = 3 * 4

Exercises

19

Python 3 Basics Tutorial

Storing text The Challenge first name

Andrew

last name

O'Malley

gender

M

year of birth

2000

Write the information from each row of the table into a separate string variable, then combine them to a single string, e.g.: O'Malley, Andrew, M, 2000

Storing text

20

Python 3 Basics Tutorial

Warming up So far, we have only worked with numbers. Now we will work with text as well. first = 'Emily' last = "Smith" first last name = first + " " + last name

What do the following statements do: name[0] name[3] name[-1]

Warming up

21

Python 3 Basics Tutorial

Definitions String Text values are called strings. In Python, strings are defined by single quotes, double quotes or three quotes of either. The following are equivalent: first = 'Emily' first = "Emily" first = '''Emily''' first = """Emily"""

String concatenation The operator + also works for strings, only that it concatenates the strings. It does not matter whether you write the strings as variables or as explicit values. The following three statements are equivalent: name = first + last name = first + "Smith" name = "Emily" + "Smith"

Indexing Using square brackets, any character of a string can be accessed. This is called indexing. The first character has the index [0] , the second [1] and the fourth has the index [3] . name[0] name[3]

With negative numbers, you can access single characters from the end, the index [-1] being the last, [-2] the second last character and so on: name[-1] name[-2]

Definitions

22

Python 3 Basics Tutorial

Note that none of these modify the contents of the string variable.

Creating substrings Substrings can be formed by applying square brackets with two numbers inside separated by a colon (slices). The second number is not included in the substring itself. s = 'Emily Smith' s[1:6] s[6:11] s[0:2] s[:3] s[-4:]

Definitions

23

Python 3 Basics Tutorial

Exercises Exercise 1: Is it possible to include the following special characters in a string? . 7 @ ? / & * \ Ä ß " ' á

Exercise 2: What do the following statements do? first = `Hannah` first = first[0] name = first name = ""

Exercise 3: Explain the code text = "" characters = "ABC" text = characters[0] + text text = characters[1] + text text = characters[2] + text text

Exercises

24

Python 3 Basics Tutorial

Converting numbers to text and back Now you know how to store numbers and how to store text. Being able to convert the two into each other will come in handy. For that, we will use type conversions.

The Challenge: A data record with types field

value

type

first name

Andrew

string

last name

O'Malley

string

gender

M

string

year of birth

2000

integer

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.

Converting numbers to text and back

25

Python 3 Basics Tutorial

Warming up Now we are going to combine strings with integer numbers. name = 'Emily Smith' born = _____ ____ = '15' text = ____ + ' was born in the year ' + _____ year = born + _____ text year

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?

Warming up

26

Python 3 Basics Tutorial

Definitions Type conversions If you have an integer number i , you can make a string out of it with str(i) : text = str(2000)

If you have a string s , you can make an integer out of it with int(s) : number = int("2000")

Both int() and str() change the type of the given data. They are therefore called type conversions.

Functions With int() and str() , you have just learned to know two functions. In Python, functions consist of a name followed by parentheses. They can have parameters, so that a function is used like: y = f(x)

Using a function is a regular Python statement (or part thereof). It is executed only once

Definitions

27

Python 3 Basics Tutorial

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: 12345678901234567890123456789012345678901234567890

Exercises

28

Python 3 Basics Tutorial

Writing Python programs Using the interactive IPython 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 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.

Goals The new Python commands cover: How to write to the screen. How to read from the keyboard. How to repeat instructions. How to store many items in a list. How to make decisions.

Writing Python programs

29

Python 3 Basics Tutorial

Writing to the screen In this section, you will write your first Python program. It will be the most simple Python program possible. We simply will have the program write names of babies to the screen.

The Challenge: Write a table with names Many names of fictious characters that have been used as baby names. Write a program that produces an output similar to: Harry Hermione Severus Tyrion Daenerys Snow Luke Leia Darth

Extra challenges: Use a single print statement to produce the output. Store the names in separate variables first, then combine them. Use string formatting.

Writing to the screen

30

Python 3 Basics Tutorial

Warming up Open a text editor window (not a Python console). Type: print("Hannah") print(23073)

Now save the text to a file with the name first_program.py . Then run the program. In Canopy, you do this by pressing the 'play' button. In IDLE, you can execute a program by pressing F5. On Unix, you go open a terminal (a regular one, not IPython) and write: python3 first_program.py

Warming up

31

Python 3 Basics Tutorial

Definitions Python programs A Python program is simply a text file that contains Python statements. The Python interpreter reads the file and executes the statements line by line. All program files should have the extension .py Only one command per line is allowed.

Developing programs on Unix When developing on Unix, the first line in each Python program should be: #!/usr/bin env python3

print The command print() Writes textual output to the screen. It accepts one or more arguments in parentheses - all things that will be printed. You can print both strings and integer numbers. You can also provide variables as arguments to print() . We need print because typing a variable name in a Python program does not give you any visible output. The Python print statement is very versatile and accepts many combinations of strings, numbers, function calls, and arithmetic operations separated by commas.

Examples:

Definitions

32

Python 3 Basics Tutorial

print('Hello World') print(3 + 4) print(3.4) print("""Text that stretches over multiple lines. """) print('number', 77) print() print(int(a) * 7)

String formatting Variables and strings can be combined, using formatting characters. This works also within a print statement. In both cases, the number of values and formatting characters must be equal. s = 'Result: %i' % (77) print('Hello %s!' % ('Roger') a = 5.099999 b = 2.333333 print('(%6.3f/%6.3f)' % (a, b)

The formatting characters include: %i – an integer. %4i – an integer formatted to length 4. %6.2f – a float number with 6 digits (2 after the dot). %10s – a right-oriented string with length 10.

Escape characters Strings may contain also the symbols: \t (tabulator), \n (newline), \r (carriage return), and \\ (backslash).

Definitions

33

Python 3 Basics Tutorial

Exercises Exercise 1 Explain the following program: name = "Emily" year = 2000 print(name, year)

Exercise 2 Write into a program: name = "Emily" name

What happens?

Exercise 3 Which print statements are correct? [ ] print("9" + "9") [ ] print "nine" [ ] print(str(9) + "nine") [ ] print(9 + 9) [ ] print(nine)

Exercises

34

Python 3 Basics Tutorial

Reading from the keyboard Next, we will connect the keyboard to our program.

The Challenge: Enter a baby name Write a program that asks for a name and an age, then writes a sentence with the entered data: Bobby is 3 years old.

Extra challenge: Add 1 to the age entered.

Reading from the keyboard

35

Python 3 Basics Tutorial

Warming up What happens when you write the follwing lines in the IPython shell: In [1]: a = input() In [2]: a

Warming up

36

Python 3 Basics Tutorial

Definitions input Text can be read from the keyboard with the input function. input works with and without a message text. The value returned is always a string: a = input() b = input('Please enter a number')

Although the input command is rarely seen in big programs, it often helps to write small, understandable programs, especially for learning Python.

Definitions

37

Python 3 Basics Tutorial

Exercises Exercise 1 Which input statements are correct? [ ] a = input() [ ] a = input("enter a number") [ ] a = input(enter your name) [ ] a = input(3)

Exercises

38

Python 3 Basics Tutorial

Repeating instructions So far, each Python instruction was executed only once. That makes programming a bit useless, because our programs are limited by our typing speed. In this section you will learn the for statements that repeats one or more instructions several times.

The Challenge: count characters Write a program that calculates the number of characters in Emily Smith .

Extra challenge Duplicate each character, so that Emily becomes EEmmiillyy .

Repeating instructions

39

Python 3 Basics Tutorial

Warming up What does the following program do? text = "" characters = "Hannah" for char in characters: text = char + text print(text)

Warming up

40

Python 3 Basics Tutorial

Definitions Loops with for The for loop allows you to repeat one or more instructions. It requires a sequence of items that the loop iterates over. This can be e.g. a string. Later we will see how you can run for loops over other things e.g. a list, a tuple, a dictionary, a file or a function. Some examples: for char in 'ABCD': print(char) for i in range(3): print(i) for elem in [1,2,3,4]: print(elem)

When to use for? When you want repeat an operation

When you want to do something to all characters of a string. When you want to do something to all elements of a list. When you already know the number of iterations.

Reserved words The two words for and in are also called reserved words. They have a special meaning in Python, which means that you cannont call a variable for or in . There are 33 reserved words in Python 3. You can see the complete list with the commands:

Definitions

41

Python 3 Basics Tutorial

import keyword keyword.kwlist

Code blocks and indentation The line with the for statement, a code block starts. A code block contains one or more line that belong to the for and are executed within the loop. Python recognizes this code block by indentation, meaning that each line starts with four extra spaces. Indentation is a central element of Python syntax. Indentation must not be used for decorative purposes. There are other Python commands that are also followed by code blocks. All of them end with a colon ( : ) at the end of the line.

Code blocks in the IPython shell Define code blocks by indenting extra lines: In [1] for i in range(3): ... print(i) ... 0 1 2 In [2]

Definitions

42

Python 3 Basics Tutorial

Exercises Exercise 1 Which of these for commands are correct? [ ] for char in "ABCD": [ ] for i in range(10): [ ] for num in (4, 6, 8): [ ] for k in 3+7: [ ] for (i=0; i