Curs 1
Curs 1
The minimum number of points that one needs to pass this exam:
120 points summed up from all tests
30 points minimum for each category (course, project and lab activity + lab test)
……..
FIRST PYTHON PROGRAM
The famous “Hello world”
C/C++
void main(void)
{
printf("Hello world");
}
Python 3.x
print ("Hello world“)
VARIABLES
Variable are defined and use as you need them.
Python 3.x
x = 10 #x is a number
s = ”a string” #s is a string
b = True #b is a Boolean value
Variables don’t have a fixed type – during the execution of a program, a variable
can have multiple types.
Python 3.x
x = 10
#do some operations with x
x = ”a string”
#x is now a string
BASIC TYPES
Python 3.x
x = 10 #x is an integer (32 bit precision)
x = 999999999999999999999999999999999 #x is a long (unlimited precision)
x = 1.123 #x is an float
x = 1.2j #x is a complex number
x = True #x is a bool ( a special case of integer )
x = None #x is a NoneType(the closest C/C++ equivalent is NULL/nullptr)
A special operator exists // that means integer division (for integer operators)
Python 3.x
x = 10.0//3 #x will be a float with value 3.0
x = 11.9//3 #x will be a float with value 3.0
NUMERICAL OPERATIONS
Bit-wise operators (& , | , ^ , <<, >> ). In particular & operator can be used to make
sure that a behavior specific to a C/C++ operation can be achieve
Python 3.x
x = 10 < 20 > 15 #x is True
#identical to (10<20) and (20>15)
All of these operators produce a bool result. There are two special values (keywords)
defined in Python for constant bool values:
❖ True
❖ False
STRING TYPES
Python 3.x
s = ”a string\nwith lines”
s = ’a string\nwith lines’
s = r”a string\nwithout any line”
s = r’a string\nwithout any line’
If only one parameter has to be replaced, the same expression can be written in a
simplified form:
Python 3.x
s = "Grade: %d"%10
Two special keywords str and repr can be used to convert variables from any type to
string.
Python 3.x
s = str (10) #s is ”10”
s = repr (10.25) #s is ”10.25”
STRING TYPES
Formatting can be extended by adding naming to formatting variables.
Python 3.x
s = "Name: %(name)8s Grade: %(student_grade)d" % {"name":"Ion" ,
"student_grade":10}
A special character “\” can be place at the end of the string to concatenate it with
another one from the next line.
Python 3.x
s = "Python"\
"Exam“
#s is ”PythonExam”
STRING TYPES
Starting with version 3.6, Python also supports formatted string literals. These are strings
preceded by an “f” or “F” character
Python 3.6+
a = 100
s = f"A = {a}" #s will be ‘A = 100’
s = f"A = {a+10}" #s will be ‘A = 110’
s = f"A = {float(a)}" #s will be ‘A = 100.0’
s = f"A = {float(a):10}" #s will be ‘A = 100.0’ (preceded by spaces)
s = f"A = {a#:0x}" #s will be ‘A = 0x64’
There are some special characters that can be used to trigger a string representation for an
object: !s (means str), !r (means repr), !a (means ascii)
More on this topic: https://docs.python.org/3/tutorial/inputoutput.html
STRING TYPES
Strings also support different ways to access characters or substrings
Python 3.x
s = "PythonExam" #s is “PythonExam”
And slicing:
Python 3.x
s = "PythonExam" #s is “PythonExam”
s[1:7:2] #Result is ”yhn” (Going from index 1, to index 7
#with step 2 (1,3,5) ➔ PythonExam
STRING TYPES
Every string is considered a class and has member functions associated with it.
These methods are accessible through “.” operator.
❖ Str.startswith(“…”) ➔ checks if a string starts with another one
❖ Str.endswith(“…”) ➔ checks if a string ends with another one
❖ Str.replace(toFind,replace,[count]) ➔ returns a string where the substring <toFind> is replaced by
substring <replace>. Count is a optional parameter, if given only the firs <count> occurrences are
replaced
❖ Str.index(toFind) ➔ returns the index of <toFind> in current string
❖ Str.rindex(toFind) ➔ returns the right most index of <toFind> in current string
❖ Other functions: lower(), upper(), strip(), rstrip(), lstrip(), format(), isalpha(), isupper(), islower(),
find(…), count(…), etc
STRING TYPES
Strings splitting via .split function
Python 3.x
s = "AB||CD||EF||GH"
s.split("||")[2] #Result is ”EF”. Split produces an array of 4
#elements AB,CD,EF and GH. The second element is EF
s.split("||")[-1] #Result is ”GH”.
s.split("||",1)[0] #Result is ”AB”. In this case the second parameter
#tells the function to stop after <count> (in this
#case 1) splits. Split produces an array of 2
#elements AB and CD||EF||GH. The fist element is AB
s.split("||",2)[2] #Result is ”EF||GH”. Split produces an array of 3
#elements AB, CD and EF||GH.
Strings also support another function .rsplit that is similar to .split function with the only
difference that the splitting starts from the end and not from the beginning.
BUILT-IN FUNCTIONS FOR STRINGS
Python has several build-in functions design to work characters and strings:
❖ chr (charCode) ➔ returns the string formed from one character corresponding to the
code charCode. charCode is a Unicode code value.
❖ ord (character) ➔ returns the Unicode code corresponding to that specific character
❖ hex (number) ➔ converts a number to a lower-case hex representation
❖ oct (number) ➔ converts a number to a base-8 representation
❖ format ➔ to format a string with different values
STATEMENTS
Python is heavily based on indentation to express a complex instruction
Python 3.x
a = 3
while a > 0:
a = a - 1 Output
print (a) 2
if a==2: break
else:
print ("Done")
WHILE - STATEMENT
Similarly, the continue keyword can be used to switch the execution from the while
loop to the point where the while condition is tested.
Python 3.x
Output
a = 10
9
while a > 0:
7
a = a – 1
5
if a % 2 == 0: continue
3
print (a)
1
else:
Done
print ("Done")
DO…WHILE - STATEMENT
Python does not have a special keyword to express a do … while statement. However, using
the while…else statement a similar behavior can be achieved.
Example:
C/C++ Python 3.x
do { while x > 10:
x = x - 1; x = x - 1
} else:
while (x > 10); x = x - 1
FOR- STATEMENT
For statement is different in Python that the one mostly used in C/C++ like languages.
It resembles more a foreach statement (in terms that it only iterates through a list of objects,
values, etc). Besides this, all of the other known keywords associated with a for (break and
continue) work in a similar way.
Python 3.x
for <list_of_iterators_variables> in <list>:
complex or simple statement
Python 3.x
for <list_of_iterators_variables> in <list>:
complex or simple statement
else:
complex or simple statement
FOR- STATEMENT
A special keyword range that can be used to simulate a C/C++ like behavior.
Output
Python 3.x
0
for index in range (0,3):
1
print (index)
2
for statement will be further discuss in the course no. 2 after the concept of list is
presented.
FUNCTIONS
Functions in Python are defined using def keyword
Python 3.x
def function_name (param1,param2,… paramn ):
complex or simple statement
And finally, return keyword can be used to return values from a function. There is no
notion of void function (similar cu C/C++ language) → however, this behavior can be
duplicated by NOT using the return keyword.
FUNCTIONS
Example of a function that performs a simple arithmetic operation
Python 3.x
def myFunc (x, y, z):
return x * 100 + y * 10 + z
print ( myFunc (1,2,3) ) #Output:123
Python 3.x
def myFunc (x, y=6, z=7):
return x * 100 + y * 10 + z
print (myFunc (1) ) #Output:167
print (myFunc (2,9) ) #Output:297
print (myFunc (z=5,x=3) ) #Output:365
print (myFunc (4,z=3) ) #Output:463
print (myFunc (z=5) ) #ERROR: missing x
❖ These lines can be added for windows as well (“#” character means comment in
python so they don’t affect the execution of the file too much
❖ Write the python code into the file
❖ Execute the file.
❖ You can use the python interpreter directly (usually C:\Python27\python.exe or
C:\Python310\python.exe for Windows) and pass the file as a parameter
❖ Current distributions of python make some associations between .py files and their interpreter. In this
cases you should be able to run the file directly without using the python executable.