Python Basics Session2
Python Basics Session2
الحقيقة المعززة/ التعلم العميق/ التعلم اآللي/ دورة لغة البايثون في مجال تطبيقات الذكاء الصنعي
03/10/2023
1
الجمهورية العربية السورية
المعهد العالي للعلوم التطبيقية والتكنولوجيا
2
الجمهورية العربية السورية
المعهد العالي للعلوم التطبيقية والتكنولوجيا
3) Control Statements:
if / else / elif / Comparison ( == , < , > , <= , >= , !=)
while loops
For loops
4) Functions:
Definition / parameters / return values /
Multiple Return Values
Optional Parameters – Default Values
Positional Parameters
Functions & Modules ( math)
3
الجمهورية العربية السورية
5- Input/Output: المعهد العالي للعلوم التطبيقية والتكنولوجيا
String Formatting
Files (read / write / close )
with statement
4
2) Data Types:
• Tuple (Count / index / sum):
• Data type: tuple / ordered collection similar to list
• Constant list / no change of values (tuple vs. list) (tuple is faster)
• s = 1, "spam", 9.0, 42 student = (“name”,id,year)
print(s) (1, 'spam', 9.0, 42)
• s = (1, "spam", 9.0, 42)
print(s) (1, 'spam', 9.0, 42)
• Count appearance of an element: s.count(x)
• s = (1, "spam", 9.0, 42)
• print(s.count("spam"))
• Position of an element: s.index(x) similar to list / Exception if not existed
• Sum of the elements: sum(s) similar to list / Exception if different types 5
2) Data Types:
• Lists are mutable ()قابل للتغير
• Strings and tuples are immutable )(غير قابل للتغيير
• No assignment s[i] = ...
• No appending and removing of elements
• Functions like x.upper() return a new string!
• s1 = " spam "
• s2 = s1. upper ()
• print(s1) spam
• print(s2) SPAM
6
2) Data Types:
• Operations on sequences:(x in s / x not in s / len / min / max):
• Strings, lists and tuples have much in common: They are sequences.
Does/doesn’t s contain an element?
x in s , x not in s a= [1,2,3,[5,6]]
a= (1,2,3) print(a)
print(1 in a) True print(max(a)) TypeError:
print(9 in a) False '>' not supported between instances of 'list' and 'int'
print(9 not in a) True
• print(len(a))
• print(min(a))
• print(max(a)) 7
2) Data Types:
• indexing in python: Slicing of a List
• a = "Python Kurs"
• print(a) Python Kurs
• print(a[2]) t
• print(a[-4]) K
• print(a[-500]) print(a[500]) IndexError: string index out of range
• print(a[2:3]) t
• print(a[2:2]) print(a[3:3])
• print(type(a[2:2])) <class 'str'>
• print(a[2:1])
• print(a[-4: -1]) Kur print(a[-1: -4])
• print(a[-4:]) Kurs
• print(a[:]) Python Kurss
• print(a[-6: -8: -1]) no
8
• print(a[-6: -5: -1])
2) Data Types:
• Boolean Values (True / False) :
• Data type bool: True , False
• Values that are evaluated to False : bool()
• None (data type NoneType )
a = None
print(bool(a))
• False print(bool(2>1))
• 0 (in every numerical data type) print(bool(0)) / print(bool(0)) vs. print(bool(0.1))
• Empty strings, lists and tuples: ‘’ , [] , ()
• Empty dictionaries: {}
• Empty sets set()
9
الجمهورية العربية السورية
المعهد العالي للعلوم التطبيقية والتكنولوجيا
10
3) Control Statements:
• if a == 3:
print (“Ok")
• Blocks are defined by indentation
• Standard: Indentation with four spaces
if a == 3: • Comparison of content: == , < , > , <= , >= , !=
print (" Three ") • And/or operator: a and b , a or b
elif a == 10:
• Chained comparison: a <= x < b , a == b == c , . . .
print (" Ten ")
elif a == -3: if a <= b <= c <= d <= 0:
print (" Minus Three ") • Negation: not a
else: if not (a==b) and (c <3):
print (" something else ") pass
11
• Hint: pass is a No Operation (NOOP) function
3) Control Statements:
• i=0
• while i < 10:
print(i)
i += 1
• break and continue work for while loops, too. Examples (Break /
Continue)
• Substitute for do-while loop:
while True :
# important code
if condition :
break
12
3) Control Statements:
• for i in range (10):
print (i) # 0, 1, 2, 3, ... , 9
• for i in range (3, 10):
print (i) # 3, 4, 5, ... , 9
• for i in range (0, 10, 2):
print (i) # 0, 2, 4, 6, 8
4) Functions:
Definition / parameters / return values /
Multiple Return Values
Optional Parameters – Default Values
Positional Parameters
Functions & Modules ( math)
15
4) Functions:
• def add(a, b): • Return Values and Parameters:
""" Returns the sum • Types of parameters and return values are unspecified
of a and b.""" • Functions without explicit return value return None
mysum = a + b • def hello_world ():
print(" Hello World !")
return mysum a = hello_world ()
print (a)
result = add (3, 5)
Hello World !
print ( result ) None
16
4) Functions: • Optional Parameters – Default Values:
• Multiple Return Values: • Parameters can be defined with default
• Multiple return values values.
are realized using tuples • Hint: It is not allowed to define non-
or lists: default parameters after default
• def foo (): parameters
a= 17 • def fline (x, m=1, b =0): # f(x) = m*x + b
b = 42 return m*x + b
• for i in range (5):
return (a, b) • end in print defines
print ( fline (i), end=" ")
• ret = foo() • # force newline the last character,
• (x, y) = foo () • print ()
default is linebreak
for i in range (5):
print ( fline (i , -1 ,1) , end=" ")
17
4) Functions:
• Positional Parameters:
• Parameters can be passed to a function in a different order than
specified:
• def printContact (name ,age , location ):
print (" Person : ", name )
print ("Age : ", age , " years ")
print (" Address : ", location )
• printContact ( name =" Peter Pan", location =" Neverland ", age =10)
18
4) Functions:
• Functions are Objects:
• Functions are objects and as such can be assigned and passed on:
• def foo( fkt ):
print (fkt (33))
• foo ( float )
33.0
• foo (str)
33
• foo ( complex )
(33+0 j) 19
4) Functions:
• Functions & Modules:
• Functions thematically belonging together can be stored in a separate
Python file.
• This file is called module and can be loaded in any Python script.
• Multiple modules available in the Python Standard Library
• (part of the Python installation)
• Command for loading a module: import <filename>
• (filename without ending .py)
• import math
• s = math.sin(math.pi)
20
الجمهورية العربية السورية
المعهد العالي للعلوم التطبيقية والتكنولوجيا
5- Input/Output:
String Formatting
) Files (read / write / close
with statement
21
5) Input/Output :
• Format string + class method x.format()
• print ("The answer is {0:4d}". format (42)) ‘The answer is 42 ‘
• s = " {0}: {1:08.3f}".format(" spam ", 3.14) ’spam : 0003.140 ’
format purpose
m.nf floating point m filed size, n digits after the decimal point (default: 6)
(s = " {0}: {1:020.8f}".format(" spam ", 3.14)) spam : 00000000003.14000000
s = " {0}: {1:20.8f}".format(" spam ", 3.14) spam : 3.14000000
s = " {0}: {1:020f}".format(" spam ", 3.14) spam : 0000000000003.140000
s = " {0}: {1:05f}".format(" spam ", 3.14) spam : 3.140000
m.ne floating point (exponential) m filed size, 1 digit before and n digits behind the
decimal point (default: 6)
s = " {0}: {1:020.8e}".format(" spam ", 3.14) spam : 0000003.14000000e+00
24
5) Input/Output : for line in file1 :
print (line )
• Files:
• file1 = open ("spam .txt ", "r") • Read: f.read(size) (how many chars)
• file2 = open ("test.txt", "w")
• Read a line: f.readline()
• Read mode: r
• Write mode (new file): w (delete
• Read multiple lines: f.readlines()
contents if exists) 123456789
aaaaa
• Write mode, appending to the end: a
bbbbbbbb
• Read and write (update): r+
ccccccccc
(update data starting from the first ddddd
char)
['123456789\n', 'aaaaa\n', 'bbbbbbbb\n', 'ccccccccc\n', 'ddddd']
• Write: f.write(str)
• Write multiple lines: f.writelines(sequence)
• Close file: f.close() 25
5) Input/Output :
• file1 = open ("test4.txt ", "w") file1 = open ("test4.txt ", "w")
• lines = [" spam \n", " test1 \n", “AAAA\n"] lines = [" spam ", " test1 ", "AAAA"]
• file1.writelines( lines ) file1.writelines(lines)
• file1.close () file1.close()
26
5) Input/Output :
• The with statement:
• File handling (open/close) can be done by the context manager
with .
• with open (" test .txt ") as f:
for line in f:
print ( line )
• with open("test4.txt","w") as f:
for i in range(5):
f.write(str(i)+"\n")
27