Python introduction

Dr. Chao Zhang & Anahita Iravanizad

06, Oct, 2020 (Day 2) @ Mathematics, TU Chemnitz

Recap of yesterday: local installation

  • Conda/Anaconda/Miniconda
  • Install Miniconda under Windows/Linux
  • Install Python packages with Conda
  • Three ways to run Hello world
  • Python is an interpreted language

Goal of today: Python fundamentals

  • How to store/represent data in programs?
  • What kinds of data do programs store?
  • How to use if, while, for?
  • What are the useful built-in functions?
  • How to write a function?
  • How to read and write files?
  • How to write a class?

Use variables to store values

Variables are names for values.

  • In Python the = symbol assigns the value on the right to the name on the left.
  • Why use variables: reuse/modification
  • print to display variables
In [4]:
x = 1
print(x)
1
In [5]:
x = 2
y = 2
z = x + y
print(z)
4
In [6]:
x = 2
y = 2
z = (x+y)*(x+y) + x*x*x + x*y
print(z)
28

Variable names

  • can only contain letters, digits, and underscore _ (typically used to separate words in long variable names)
  • cannot start with a digit
  • are case sensitive (Age $\neq$ AGE)
  • two naming strategies: isValid and is_valid
In [ ]:
x = 1
In [7]:
place = "Chemnitz"
year = 2020
lastYear = 2019
time_step = 0.01
is_male = True
isFemale = False
In [ ]:
2ab = 10
In [ ]:
x = 1
print(X)

Variables must be created before they are used.

In [ ]:
print(last_name)

Variables can be used in calculations

In [10]:
year = 2020
next_year = year + 1
print(next_year)
2021

Data types in Python

  • Strings "Chemnitz"
  • Numbers 2.333
  • Lists [1,2,3,4]
  • Tuples (1,2)
  • Sets {"red", "blue", "yellow"}
  • Booleans True

Strings are ordered sequence of characters

  • Single quotation marks '' works the same as double quotation marks "
  • Triple qutation marks for long (multiple line) centences
In [ ]:
"Hello"
In [ ]:
'Hello'
In [ ]:
city = "Chemnitz"
In [18]:
Lyrics = """
Ground Control to Major Tom (ten, nine, eight, seven, six)
Commencing countdown, engines on (five, four, three)
Check ignition and may God's love be with you (two, one, liftoff)
"""
In [19]:
print(Lyrics)
Ground Control to Major Tom (ten, nine, eight, seven, six)
Commencing countdown, engines on (five, four, three)
Check ignition and may God's love be with you (two, one, liftoff)

Escape character

  • \n to switch line and \' and \" for quotation marks
In [15]:
txt = "This is first line\nThis is \"second\" line"
print(txt)
This is first line
This is "second" line

Useful functions

  • + to connect strings
  • .lower(), .upper(), len()
  • .index("a"), .replace("a", "b")
In [17]:
txt = "Superman" + "likes" + "Python"
print(txt)
SupermanlikesPython
In [18]:
txt = "TU Chemnitz"
txt.lower()
Out[18]:
'tu chemnitz'
In [21]:
txt.index("e")
Out[21]:
5
In [22]:
msg = "There is nathing wrong here"
msg.replace("a", "o")
Out[22]:
'There is nothing wrong here'

Accessing character through index

  • use [2] for example
  • index from 0 in Python
  • slicing
In [27]:
txt = "Chemnitz"
print(txt[4])
n
In [28]:
print(txt[1:3]) # : can be viewed as "to" in English 
he

1) Practice time

  • write a short programme to ask for the user's information and then display the information
  • The user information includes name, age and university
  • Hint: A useful function to get user input: input()
In [29]:
msg = input("What are you doing?")
print(msg)
What are you doing?Having a class
Having a class

1) Practice time

  • write a short programme to ask for the user's information and then display the information
  • The user information includes name, age and university
In [ ]:
name = input("What's your name?")
age = input("How old are you?")
department = input("What department are you from?")

info = name + ", " + age + " years old, is from " + department
print(info)

Numbers

  • integer int
  • float/decimal float
  • sign -
  • scientific notation E/e
  • complex j
  • =, +, -, *, /, **
  • %, +=, -=, *=
  • integer
In [ ]:
2020
  • float
In [ ]:
2.333
  • sign
In [ ]:
-2.333
  • scientific notation, e.g. $2\times 10^6$
In [ ]:
2e6
  • complex, 1+2j
In [ ]:
1 + 2j
  • +, -, *, /
  • ** (power), % (modulo operator)
  • +=, -=, *=, /=
    • a += b is shorthand for a = a + b
    • ...
  • Parenthesis () to change order
In [ ]:
2+3-4*5/6
In [ ]:
7%2
In [36]:
i = 10
i = i+1
print(i)
11
In [ ]:
i=10
i+=1
print(i)
In [ ]:
i=10
i/=2
print(i)
In [39]:
(2-3)*3
Out[39]:
-3
  • useful functions abs, pow, min, max, round
In [ ]:
abs(-2020)
In [ ]:
pow(2,4)
In [ ]:
min(12,23,32,9,12)
In [ ]:
max(12,23,32,9,12)

Converting numbers to strings

  • str() to conver to strings
In [ ]:
txt = str(2.333)
print(type(txt))
In [ ]:
type(1.03)
In [ ]:
int(1.2)
In [ ]:
float(3)

2) Practice time

  • Write a imperial/metric convertor
  • The programme will successively ask the user to input the distance in feet and inches
    • for example: 2, 3
  • and then return the length in metric system
    • for example: 2 feet, 3 inches = 0.6858 metres
  • Hints: 1 foot = 0.3048 metres, and 1 inch = 0.0254 metres

2) Practice time

  • Write a imperial/metric convertor
  • The programme will successively ask the user to input the distance in feet and inches
    • for example: 2, 3
  • and then return the length in metric system
    • for example: 2 feet, 3 inches = 0.6858 metres
  • Hints: 1 foot = 0.3048 metres, and 1 inch = 0.0254 metres
In [ ]:
feet = input("Please input the value in feet")
inches = input("Please input the value in inches")
feet = float(feet)
inches = float(inches)

result = 0.3048*feet + 0.0254*inches
print(str(feet) + " feet, " + str(inches) + " inches = " + str(result) + " meters")
In [ ]:
print(len(msg), msg[0])

Boolean

  • True or False
  • >, <, ==
  • Will be useful later in comparison of conditions
In [ ]:
100>99
In [ ]:
result = 100<99
print(result)
In [ ]:
result = 'hello' == "hello"
print(result)

Lists

  • A list stores many values in a single structure
  • Contained within square brackets []
  • Values separated by commas ,
In [40]:
pressures = [11, 22, 33, 44, 55]
print(pressures)
print(len(pressures))
[11, 22, 33, 44, 55]
5
  • Use an item’s index to fetch it from a list.
In [ ]:
print('zeroth item of pressures:', pressures[0])
print('fourth item of pressures:', pressures[4])
  • Access multiple elements by slicing
In [ ]:
pressures[2:4]
In [ ]:
pressures[1:]
In [ ]:
pressures[1:4:2]
  • Lists’ values can be replaced by assigning to them.
In [ ]:
pressures[0] = 0.265
print('pressures is now:', pressures)
  • Appending items to a list
In [119]:
primes = [2, 3, 5]
print('primes is initially:', primes)
primes.append(7)
print('primes has become:', primes)
primes is initially: [2, 3, 5]
primes has become: [2, 3, 5, 7]
In [125]:
primes = [2, 3, 5]
primes.extend([7,11,13])
print(primes)
[2, 3, 5, 7, 11, 13]
  • Use del to remove items from a list
In [ ]:
primes = [2, 3, 5, 7, 9]
print('primes before removing last item:', primes)
del primes[4]
print('primes after removing last item:', primes)
  • The empty list contains no values
  • Use [] on its own to represent a list that doesn’t contain any values.
In [41]:
results = []
  • Lists may contain values of different types
In [ ]:
goals = [1, 'Create lists.', 2, 'Extract items from lists.', 3, 'Modify lists.']
In [ ]:
print(goals)
  • Two dimension list
In [126]:
values = [[1,2,3],
          [4,5,6],
          [7,8,9]]
In [ ]:
print(values)
In [ ]:
print(values[1])

Tuples

  • A container similar to list
  • Tuples are written with round brackets()
  • immutable == not editable
  • A good property: it makes you feel safe as the object is in a 'protected' state
In [ ]:
coordinates = (1,3)
In [ ]:
coordinates[1]
In [ ]:
coordinates[1] = 2
In [ ]:
coordinates = (2,3)

Sets

  • Another container similar to list
  • A set is a collection which is unordered, unindexed but unique.
  • Sets are written with curly brackets {}.
  • A good property: you will feel confident as there won't be duplicate elements
In [97]:
colors = {"red", "blue", "yellow"}
In [95]:
colors = {"red", "blue", "yellow", "red"}
In [96]:
print(colors)
{'red', 'blue', 'yellow'}
In [ ]:
colors[0]
In [98]:
colors.add("purple")
In [103]:
for c in colors:
    print(c)
red
blue
purple
yellow

Statements

  • comparison and logical operators
  • if statement
  • while loop
  • for loop
  • comparison conditions ==, !=, >, <, <=, =>
In [ ]:
x = 1
y = 2
print(x > y)
print(x <= y)
  • logical operator and or not
In [ ]:
x = 1
y = 2
z = 3
print((x<y) and (y<z))
print((x>y) or (y<z))
print(not(x>y))
  • if...else statement
  • elif is short for else if
In [ ]:
x = 1
y = 2
if(x>y):
    print("x > y")
elif(x==y):
    print("x = y")
else:
    print("x < y")
  • while loop
    • break
In [ ]:
i=0
while(i<10):
    print(i)
    i += 1
In [26]:
i=0
while (True):
    print(i)
    i += 1
    if (i>10):
        break
0
1
2
3
4
5
6
7
8
9
10
  • for loop
In [ ]:
for i in range(10):
    print(i)
  • A nested for loop
In [ ]:
for i in range(1, 3):
    for j in range(1, 3):
        print(i, j)

3) Practice time

  • Print out the Nine-nine table
  • Hint: use print (5, end = '') to avoid switching to a new line

3) Practice time

  • Print out the Nine-nine table
  • Hint: use print (5, end = '') to avoid switching to a new line
In [114]:
for i in range(1, 10): #i is row number
    for j in range(1, 10): # j is column number
        if (i>=j):
            print (j,"x", i,"=", i*j, " ", end = '')
    print('\n')
1 x 1 = 1  

1 x 2 = 2  2 x 2 = 4  

1 x 3 = 3  2 x 3 = 6  3 x 3 = 9  

1 x 4 = 4  2 x 4 = 8  3 x 4 = 12  4 x 4 = 16  

1 x 5 = 5  2 x 5 = 10  3 x 5 = 15  4 x 5 = 20  5 x 5 = 25  

1 x 6 = 6  2 x 6 = 12  3 x 6 = 18  4 x 6 = 24  5 x 6 = 30  6 x 6 = 36  

1 x 7 = 7  2 x 7 = 14  3 x 7 = 21  4 x 7 = 28  5 x 7 = 35  6 x 7 = 42  7 x 7 = 49  

1 x 8 = 8  2 x 8 = 16  3 x 8 = 24  4 x 8 = 32  5 x 8 = 40  6 x 8 = 48  7 x 8 = 56  8 x 8 = 64  

1 x 9 = 9  2 x 9 = 18  3 x 9 = 27  4 x 9 = 36  5 x 9 = 45  6 x 9 = 54  7 x 9 = 63  8 x 9 = 72  9 x 9 = 81  

Built-in functions

  • What are the useful built-in functions?
  • Where to find help on built-in functions?
In [ ]:
x = [1,2,3,4]
len(x)
In [ ]:
round(2.3)
In [ ]:
print("It is a good day!")
In [ ]:
min([1,2,3,4])
In [ ]:
max([1,2,3,4])

Any data type has its built-in functions

  • In IPython or Jupyter notebook, type . after a defined variable name (no space in between), and hit Tab, you'll see all of its built-in functions
  • Use help to find how to use a function (no parenthesis after function's name), e.g. help(msg.length)
In [27]:
txt = "TU Chemnitz"
txt.split()
Out[27]:
['TU', 'Chemnitz']
In [134]:
values = [1,2,3,4,5]
help(values.count)
Help on built-in function count:

count(value, /) method of builtins.list instance
    Return number of occurrences of value.

Error message of function

In [ ]:
name = "Chemnitz"
round(name)

Writing Functions

  • Why do we use functions?
  • How to write my own functions?
  • Difference between function definition and function call

Why do we use functions?

  • One function is like a component in a machine
  • With functions, complex programes can be break into small/simpler functions
  • Enables reuse

Define a function

  • Begin the definition of a new function with def.
  • Followed by the name of the function.
  • Then parameters in parentheses.
    • Empty parentheses if the function doesn’t take any inputs.
  • Then a colon.
  • Then an indented block of code.
  • Functions may return a result to their caller using return
In [ ]:
def print_greeting():
    print('Hello!')
In [ ]:
def addition(x, y):
    return x+y

Call/use a function

  • call with the name of a function
  • followed by parenttheses
  • Possibly with parameters
In [ ]:
print_greeting()
In [ ]:
addition(23,34)
  • Arguments in call are assigned to parameters in definition
  • If you don’t name the arguments when using them in the call, the arguments will be matched to parameters in the order the parameters are defined in the function
In [ ]:
print_date(1871, 3, 19)
In [ ]:
print_date(month=3, day=19, year=1871)

4) Practice time

  • Define a function to find odd values between 1 and n
  • and use this function
  • Hint: if i%2 == 1, then i is an odd number

4) Practice time

  • Define a function to find odd integers between 1 and n (n not included)
  • and use this function
  • Hint: if i%2 == 1, then i is an odd number
In [ ]:
def find_odd(n):
    result = []
    for i in range(1, n):
        if ((i%2)==1):
            result.append(i)
    return result

Common errors in using functions

Identifying Syntax Errors

  • indentation
  • parentheses
In [ ]:
def a_test_function
  print("This is first line")
   print("This is second line")
  print("This is third and the longest line")

Handling files

  • Use open() function to open a file with mode r, a or w
    • r: read only, a: append, w:overwrite
  • open() will return a file object
  • Don't forget close() to close a file
In [19]:
f = open("readme.txt", 'r')
f.close()

Read mode

  • read() method to read content of the file
  • readline() to read a line of content
In [20]:
f = open("readme.txt", 'r')
txt = f.read()
print(txt)
f.close()
These materials are prepared for the Python introduction block-course at TU Chemnitz.
https://www.tu-chemnitz.de/mathematik/numa/lehre/python-2020/
Author: Chao Zhang
Email: chao.zhang@math.tu-chemnitz.de
Date: 03.10.2020
Now the file has more content!This is a test line
In [2]:
f = open("readme.txt", 'r')
while True:
    line = f.readline()
    print(line)
    if(not line):
        break
f.close()
These materials are prepared for the Python introduction block-course at TU Chemnitz.

https://www.tu-chemnitz.de/mathematik/numa/lehre/python-2020/

Author: Chao Zhang

Email: chao.zhang@math.tu-chemnitz.de

Date: 03.10.2020


Write mode

  • a: append to the end of an existing file
  • w: overwrite an existing file
In [24]:
f = open("readme.txt", "a")
f.write("We will add this test line\n")
f.close()

#open and read the file after the appending:
f = open("readme.txt", "r")
print(f.read())
These materials are prepared for the Python introduction block-course at TU Chemnitz.
https://www.tu-chemnitz.de/mathematik/numa/lehre/python-2020/
Author: Chao Zhang
Email: chao.zhang@math.tu-chemnitz.de
Date: 03.10.2020
Now the file has more content!This is a test lineWe will add this test lineWe will add this test lineWe will add this test line
We will add this test line

In [7]:
f = open("test.txt", "w")
f.write("I'm going to overwrite this file!")
f.close()

#open and read the file after the appending:
f = open("test.txt", "r")
print(f.read())
I'm going to overwrite this file!

5) Practice time

  • Write the Nine-nine table to a text file

5) Practice time

  • Write the Nine-nine table to a text file
In [18]:
f = open("nine_nine.txt", "w")
for i in range(1, 10): #i is row number
    for j in range(1, 10): # j is column number
        if (i>=j):
            line = str(j)+"x"+str(i)+"="+str(i*j) + " "
            f.write (line)
    f.write('\n')
f.close()

Classes/objects: your customized datatype

  • Python is an object-oriented language
  • Almost everyting in Python is an object, e.g. strings, numbers, lists.
  • An object has its attributes and methods
In [77]:
txt = "Chemnitz"
print(type(txt))
<class 'str'>

Class Robot with property

  • Class definition
    • __init__() function: the special function gets called whenever a new object of that class is instantiated.
    • The self parameter is a reference to the current instance of the class
    • It is used to access variables that belongs to the class.
    • We're going to define a Robot class which has a property type
In [130]:
class Robot:
    def __init__(self, tt):
        self.type = tt
  • Class instantiation (to create an instance of the class)
In [131]:
my_r = Robot("smart")
In [132]:
print(my_r.type)
smart

Class Robot with methods

  • Class definition
In [151]:
class Robot:
    def __init__(self, tt):
        self.type = tt
    def report_type (self):
        print("I'm of type", self.type)
  • Class instantiation (create an instance of the class)
In [152]:
my_r = Robot("strong")
In [153]:
my_r.report_type()
I'm of type strong

Robot with more methods

  • Class definition
In [154]:
class Robot:
    def __init__(self, tt, val1, val2):
        self.type = tt
        self.x = val1
        self.y = val2
        
    def report_type (self):
        print("I'm of type", self.type)
        
    def report_location(self):
        print("I'm now at (", self.x, ",", self.y, ")")
        
    def move(self,val1, val2):
        self.x += val1
        self.y += val2
  • Class instantiation (create an instance of the class)
In [155]:
my_r = Robot("strong", 0, 0)
In [156]:
my_r.report_location()
I'm now at ( 0 , 0 )
In [157]:
my_r.move(1,0)
my_r.report_location()
I'm now at ( 1 , 0 )

6) Practice time

  • Define a Toy class that has an attribute color and a method report_color

6) Practice time

  • Define a Toy class that has an attribute color and a method report_color
In [158]:
class Toy:
    def __init__(self, cc):
        self.color = cc
    def report_color(self):
        print("I'm", self.color)
In [159]:
my_t = Toy("red")
my_t.report_color()
I'm red

Summary of today: Python fundamentals

  • Store data in variables
  • Data types : strings, numbers, booleans, lists, sets and tuples
    • Difference between lists, sets and tuples
  • Comparison conditions
  • if, while, for statements
  • Use built-in functions
  • Write your own function
  • User input and file handling
  • Create you own class
  • Practice time

Q&A

Numpy and Matplotlib

  • What is a module?
  • Why do we need Numpy?
  • How to start using Numpy?
  • How to use Matplotlib to plot out data?