Dr. Chao Zhang & Anahita Iravanizad
06, Oct, 2020 (Day 2) @ Mathematics, TU Chemnitz
Hello world
if
, while
, for
?Variables are names for values.
=
symbol assigns the value on the right to the name on the left.print
to display variablesx = 1
print(x)
1
x = 2
y = 2
z = x + y
print(z)
4
x = 2
y = 2
z = (x+y)*(x+y) + x*x*x + x*y
print(z)
28
_
(typically used to separate words in long variable names)Age
$\neq$ AGE
)isValid
and is_valid
x = 1
place = "Chemnitz"
year = 2020
lastYear = 2019
time_step = 0.01
is_male = True
isFemale = False
2ab = 10
x = 1
print(X)
print(last_name)
year = 2020
next_year = year + 1
print(next_year)
2021
"Chemnitz"
2.333
[1,2,3,4]
(1,2)
{"red", "blue", "yellow"}
True
''
works the same as double quotation marks "
"Hello"
'Hello'
city = "Chemnitz"
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)
"""
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)
\n
to switch line and \'
and \"
for quotation markstxt = "This is first line\nThis is \"second\" line"
print(txt)
This is first line This is "second" line
+
to connect strings.lower()
, .upper()
, len()
.index("a")
, .replace("a", "b")
txt = "Superman" + "likes" + "Python"
print(txt)
SupermanlikesPython
txt = "TU Chemnitz"
txt.lower()
'tu chemnitz'
txt.index("e")
5
msg = "There is nathing wrong here"
msg.replace("a", "o")
'There is nothing wrong here'
[2]
for example0
in Pythontxt = "Chemnitz"
print(txt[4])
n
print(txt[1:3]) # : can be viewed as "to" in English
he
input()
msg = input("What are you doing?")
print(msg)
What are you doing?Having a class Having a class
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)
int
float
-
E
/e
j
=
, +
, -
, *
, /
, **
%
, +=
, -=
, *=
2020
2.333
-2.333
2e6
1 + 2j
+
, -
, *
, /
**
(power), %
(modulo operator)+=
, -=
, *=
, /=
a += b
is shorthand for a = a + b
()
to change order2+3-4*5/6
7%2
i = 10
i = i+1
print(i)
11
i=10
i+=1
print(i)
i=10
i/=2
print(i)
(2-3)*3
-3
abs
, pow
, min
, max
, round
abs(-2020)
pow(2,4)
min(12,23,32,9,12)
max(12,23,32,9,12)
str()
to conver to stringstxt = str(2.333)
print(type(txt))
type(1.03)
int(1.2)
float(3)
2
, 3
2 feet, 3 inches = 0.6858 metres
1 foot = 0.3048 metres
, and 1 inch = 0.0254 metres
2
, 3
2 feet, 3 inches = 0.6858 metres
1 foot = 0.3048 metres
, and 1 inch = 0.0254 metres
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")
print(len(msg), msg[0])
True
or False
>
, <
, ==
100>99
result = 100<99
print(result)
result = 'hello' == "hello"
print(result)
[]
,
pressures = [11, 22, 33, 44, 55]
print(pressures)
print(len(pressures))
[11, 22, 33, 44, 55] 5
print('zeroth item of pressures:', pressures[0])
print('fourth item of pressures:', pressures[4])
pressures[2:4]
pressures[1:]
pressures[1:4:2]
pressures[0] = 0.265
print('pressures is now:', pressures)
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]
primes = [2, 3, 5]
primes.extend([7,11,13])
print(primes)
[2, 3, 5, 7, 11, 13]
del
to remove items from a listprimes = [2, 3, 5, 7, 9]
print('primes before removing last item:', primes)
del primes[4]
print('primes after removing last item:', primes)
[]
on its own to represent a list that doesn’t contain any values.results = []
goals = [1, 'Create lists.', 2, 'Extract items from lists.', 3, 'Modify lists.']
print(goals)
values = [[1,2,3],
[4,5,6],
[7,8,9]]
print(values)
print(values[1])
()
coordinates = (1,3)
coordinates[1]
coordinates[1] = 2
coordinates = (2,3)
{}
.colors = {"red", "blue", "yellow"}
colors = {"red", "blue", "yellow", "red"}
print(colors)
{'red', 'blue', 'yellow'}
colors[0]
colors.add("purple")
for c in colors:
print(c)
red blue purple yellow
if
statementwhile
loopfor
loop==
, !=
, >
, <
, <=
, =>
x = 1
y = 2
print(x > y)
print(x <= y)
and
or
not
x = 1
y = 2
z = 3
print((x<y) and (y<z))
print((x>y) or (y<z))
print(not(x>y))
if...else
statementelif
is short for else if
x = 1
y = 2
if(x>y):
print("x > y")
elif(x==y):
print("x = y")
else:
print("x < y")
while
loopi=0
while(i<10):
print(i)
i += 1
i=0
while (True):
print(i)
i += 1
if (i>10):
break
0 1 2 3 4 5 6 7 8 9 10
for
loopfor i in range(10):
print(i)
for
loopfor i in range(1, 3):
for j in range(1, 3):
print(i, j)
print (5, end = '')
to avoid switching to a new lineprint (5, end = '')
to avoid switching to a new linefor 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
x = [1,2,3,4]
len(x)
round(2.3)
print("It is a good day!")
min([1,2,3,4])
max([1,2,3,4])
.
after a defined variable name (no space in between), and hit Tab
, you'll see all of its built-in functions help
to find how to use a function (no parenthesis after function's name), e.g. help(msg.length)
txt = "TU Chemnitz"
txt.split()
['TU', 'Chemnitz']
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.
name = "Chemnitz"
round(name)
def
.def print_greeting():
print('Hello!')
def addition(x, y):
return x+y
print_greeting()
addition(23,34)
print_date(1871, 3, 19)
print_date(month=3, day=19, year=1871)
i%2 == 1
, then i
is an odd numberi%2 == 1
, then i
is an odd numberdef find_odd(n):
result = []
for i in range(1, n):
if ((i%2)==1):
result.append(i)
return result
def a_test_function
print("This is first line")
print("This is second line")
print("This is third and the longest line")
open()
function to open a file with mode r
, a
or w
r
: read only, a
: append, w
:overwriteopen()
will return a file objectclose()
to close a filef = open("readme.txt", 'r')
f.close()
read()
method to read content of the filereadline()
to read a line of contentf = 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
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
a
: append to the end of an existing filew
: overwrite an existing filef = 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
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!
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()
txt = "Chemnitz"
print(type(txt))
<class 'str'>
Robot
with property¶__init__()
function: the special function gets called whenever a new object of that class is instantiated.self
parameter is a reference to the current instance of the classRobot
class which has a property type
class Robot:
def __init__(self, tt):
self.type = tt
my_r = Robot("smart")
print(my_r.type)
smart
Robot
with methods¶class Robot:
def __init__(self, tt):
self.type = tt
def report_type (self):
print("I'm of type", self.type)
my_r = Robot("strong")
my_r.report_type()
I'm of type strong
Robot
with more methods¶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
my_r = Robot("strong", 0, 0)
my_r.report_location()
I'm now at ( 0 , 0 )
my_r.move(1,0)
my_r.report_location()
I'm now at ( 1 , 0 )
Toy
class that has an attribute color
and a method report_color
Toy
class that has an attribute color
and a method report_color
class Toy:
def __init__(self, cc):
self.color = cc
def report_color(self):
print("I'm", self.color)
my_t = Toy("red")
my_t.report_color()
I'm red
if
, while
, for
statementsinput
and file handlingNumpy
?Numpy
?Matplotlib
to plot out data?