Introduction to Python Prog. - Lecture 1

1mohamedgamal54 32 views 111 slides Sep 12, 2024
Slide 1
Slide 1 of 111
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111

About This Presentation

Introduction to Python Programming Language for absolute beginners level.


Slide Content

Introduction to Python
Programming
By Mohamed Gamal
© Mohamed Gamal 2024

Resources
•Textbooks:
•Learning Python Powerful Object-Oriented Programming 5th Edition
•Head First Python, A Brain-Friendly Guide 2nd Edition
•Other Resources

•The topics of today’s lecture:
Agenda

Introduction
–Programming a computer simply means telling it what to do.
–Computers are incredibly stupid, they do exactly what you tell them
to do, no more, no less.

The Abacus
–The abacus, a simple counting aid, may have been invented in
Babylonia (now Iraq) in the fourth century B.C.

Python.org

What is Python?
–Python is a very popular free open-source general-
purpose interpreted, interactive high-level
programming scripting language that blends
procedural, functional, and object-oriented
paradigms.
–Python is dynamically-typed and garbage-collected
programming language.
–It was created by the Dutch programmer Guido van
Rossum during 1985-1990. Python source code is
available under the GNU General Public License
(GPL).
–Despite all the reptiles on Python books and icons,
the truth is that Python is named after the British
comedy group Monty Python—makers of the 1970s
BBC comedy series Monty Python’s Flying Circus
and a handful of later full-length films, including
Monty Python and the Holy Grail, that are still
widely popular today. Python’s original creator was
a fan of Monty Python, as are many software
developers.

Genealogy of Python
Programming Language

Why even use Python?
–Software Quality: Python emphasizes readability and maintainability, supporting
advanced programming paradigms like OOP and functional programming.
–Developer Productivity: Python increases productivity with shorter code, less debugging,
and no compile steps, making it faster than languages like C++ and Java.
–Portability: Python code runs on all major platforms with minimal changes, and it
supports portable GUIs, databases, web systems, and OS interfaces.
–Support Libraries: Python's extensive standard and third-party libraries support a wide
range of tasks, from text processing to numeric programming with tools like NumPy.
–Component Integration: Python integrates easily with C/C++, Java, .NET, COM, Silverlight,
serial ports, and network interfaces like SOAP and XML-RPC.
–Enjoyment: Python’s simplicity and comprehensive toolset make programming enjoyable,
enhancing productivity.

Downsides of Python?
–The main downside of Python is its execution speed, which can be slower than
fully compiled languages like C and C++.
–Python's standard implementations compile code to byte code, providing
portability but not the speed of binary machine code.
–This can be an issue for tasks requiring close hardware interaction.

Python Careers and Applications
•Python Developer
•ML/AI Engineer
•Data Scientist
•Web Development
•DevOps Engineer
•Software Engineer
•Game developer
•Job Scheduling and Automation
•…
•etc.

Stackoverflow – 2023

How to get started?
–Download and install Python
–Interactive Prompt
–Using an Integrated Development Environment (IDE)
–Online Python Interpreter
Py Cha rm's top fea tures. [Hidden] qua lities of one of the most… | by Nicolò Ga spa rini | A na ly tics V idhy a | M edium

Basic
Notations
Binary Digit → Bit
0, 1
8 bits = 1 byte
ON
1
OFF
0

-Binary System
-Decimal System
-Hexadecimal System
›Computers use binary system
›Decimal system is used in general
›Hexadecimal system is also used in computer systems
Numbering System
Numbering System Base Range
Binary Base 2 0 – 1
Decimal Base 10 0 – 9
Hexadecimal Base 16 0 – 9, A – F

Decimal Binary Hexadecimal
0 0000 0
1 0001 1
2 0010 2
3 0011 3
4 0100 4
5 0101 5
6 0110 6
7 0111 7
8 1000 8
9 1001 9
10 1010 A
11 1101 B
12 1100 C
13 1101 D
14 1110 E
15 1111 F

-125
10
›5 x 10
0
= 5
›2 x 10
1
= 20
›1 x 10
2
= 100

125
10
Decimal Numbering System (Base 10)
+
+

-Technique:
•Multiply each bit by 2
n
, where n is the weight of the bit
•Add the results
–Convert the binary number 11001
2 to decimal
›2
4
2
3
2
2
2
1
2
0

› 1 1 0 0 1
›16 8 0 0 1 +
›16 + 8 + 0 + 0 + 1 = 25
Binary to Decimal (Base 2)
×
Result: 25
10

-Technique:
•Divide the number repeatedly by 2, while keeping track of the remainders.
•Arrange the remainders in reverse order.
–Convert the decimal number 25
10 to binary
Decimal to Binary (Base 10)
Number Remainder
÷ 2 25 1
÷ 2 12 0
÷ 2 6 0
÷ 2 3 1
÷ 2 1 1
÷ 2 0 —
Result:
11001
2

-Technique:
•Group the binary digits into sets of four.
•Convert each group to its corresponding hexadecimal digit.
–Convert the binary number 11011011
2 to hexadecimal
› 2
3
2
2
2
1
2
0
2
3
2
2
2
1
2
0
› 1 1 0 1 1 0 1 1
› 8+4+0+1 8+0+2+1
› D B
Binary to Hexadecimal (Base 2)
A: 10 D: 13
B: 11 E: 14
C: 12 F: 15
Result: DB
16

-Technique:
•Convert each hexadecimal digit to its binary representation.
•Similar to binary to hexadecimal but in a reversed way.
–Convert the hexadecimal number DB
16 to binary
› D B
› 2
3
2
2
2
1
2
0
2
3
2
2
2
1
2
0
› 8 + 4 + 0 + 1 8 + 0 + 2 + 1
› 1 1 0 1 1 0 1 1
Hexadecimal to Binary (Base 16)
B: 11 , D: 13
Result:
11011011
2

-Technique:
•Sum of the positional values of each hexadecimal digit.
–Convert the hexadecimal number DB
16 to decimal
› D B
› 13 x 16
1
+ 11 x 16
0
› 208 + 11
Hexadecimal to Decimal (Base 16)
B: 11 , D: 13
Result: 219
10
Note: another way is to first convert the hexadecimal number to
binary and then convert the binary number to decimal.

Decimal to Hexadecimal (Base 10)
-Technique:
•Divide the number repeatedly by 16, while keeping track of the remainders.
•Multiply the quotient by 16 to get the first result
•Divide the integer by 16 again …
•Arrange the remainders in reverse order.
–Convert the decimal number 219
10 to hexadecimal
Number Remainder
÷ 16 219 0.6875x 16 = 11 ( B )
÷ 16 13 0.8125 x 16 = 13 ( D )
÷ 16 0 —
Result:
DB
16

How does it work?

How does it work?
Input Output
Processing

How does it work?
Source Code Machine Code
0001011
Processing

How does it work?
Source Code Machine CodeInterpreter
Processing

Your First Python Program
>>> print("Hello World")
Hello World
>>> name = input("Enter your name: ")
>>> print("Hello, " + name)

file.py
file.pyc
Python

Structure of a Python program
–Python programs can be decomposed into modules, statements, expressions,
and objects, as follows:
1)Programs are composed of modules (i.e., files).
2)Modules contain statements.
3)Statements contain expressions.
4)Expressions create and process objects.

Variables (Identifiers) in Python
–One feature present in all computer languages is the variable or more
formally the identifier.
–Identifiers allow us to name data and other objects in the program.
–Each identified object in the computer is stored at a unique address.
–You can think of the variables in your program as a set of boxes, each
with a label giving its name.
–Python language is case sensitive.
–Declaration of variable consists of just the name.

Naming Conventions rules for Variables
–It should begin with an alphabet (a-z or A-Z).
–There may be more than one alphabet, but without any spaces between them.
–Digits may be used but only after alphabet.
–No special symbol can be used except for the underscore ( _ ) symbol. When
multiple words are needed, an underscore should separate them.
–No keywords can be used as a variable name.
–All statements in Python language are case sensitive. Thus, a variable ‘A’ (in
uppercase) is considered different from a variable declared ‘a’ (in lowercase).

List of reserved Keywords

Understanding Variables
>>> month="May"
>>> id(month)
2167264641264
>>> age=18
>>> id(age)
140714055169352
>>> _counter = 100
>>> salary = 1000.0
>>> name1 = "Mohamed Gamal“
>>> x = y = z = 50
•Python's built-in id() function returns the address where the object is stored.

Random Access Memory (RAM)
Finite!!!

Variables in Memory
x = 10
10
RAM
Memory Location reserved
and named as x
x

print(type(x))
Python’s Core Data Types

1) Numbers
>>> 510
>>> int("11", 2)
>>> int("11", 10)
>>> int("11", 16)
>> 0x11
>>> 123 + 222 # Integer addition
345
>>> 1.5 * 4 # Floating-point multiplication
6.0
>>> 2 ** 100 # 2 to the power 100
1267650600228229401496703205376
>>> 5 + 6j # complex number
>>> type(5.2)
<class 'float'>
•Includes
»integers that have no fractional part.
»floating-point numbers that do.
»more exotic types:
–Complex numbers with imaginary
parts.
–decimals with fixed precision.
–rationals with numerator and
denominator.
–full-featured sets.
•Check Python math library.

2) Booleans
>>> a = True
>>> type(a)
<class 'bool’>
>>> b = False
>>> a + b
1
•Python Boolean type is one of built-in data types which represents one of the two values either
True or False.
•The name "Boolean" comes from George Boole, a 19th-century British mathematician and logician.

3) Strings >>> 'Mohamed Gamal' # a string
'Mohamed Gamal'
>>> "Mohamed Gamal"
'Mohamed Gamal'
>>> '''Mohamed Gamal'''
'Mohamed Gamal’
>>> type('Mohamed Gamal')
<class 'str’>
>>> len('Mohamed Gamal')
13
•Python string is a sequence of one or more
Unicode characters, enclosed in single, double
or triple quotation marks (also called inverted
commas).
•Python strings are immutable which means
when you perform an operation on strings, you
always produce a new string object of the same
type, rather than mutating an existing string.
>>> str = 'Hello World!'
>>> print(str)
>>> print(str[0])
>>> print(str[2:5])
>>> print(str[2:])
>>> print(str * 2)
>>> print(str + "TEST")

A
rr
ay
M o h a m e d
0 1 2 3 4 5 6
Array Length = 7
First Index = 0
Last index = 6
← Array indices
← Array values
name = "Mohamed"
Tip: Arrays in programming are similar to vectors or matrices in
mathematics.
All the array elements occupy
contiguous space in memory.
The topmost element is name[0], there’s no name[7]
3) Strings (Cont.)

3) Strings (Cont.)
name = "Mohamed"
# print each character memory address
for i in range(len(name)):
print(name[i], id(name[i]))
print(name[0])
print(name[6])
print(name[-1])
print(name[2:6])
print(name[3:])
print(name[:])
str1 = "Hello"
str2 = "World"
str3 = str1 + str2
print(str3)
print(str1 * 5)
print(str2.upper())
Example 1: Example 2:

Escape Sequence
Escape Sequence Meaning
\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\'
Single Quote
\"
Double Quote
\?
Question Mark

4) Lists
>>> myList = [2024, "Python", 3.11, 5+6j, 1.23E -4]
>>> type(myList)
<class 'list'>
>>> [['One', 'Two', 'Three'], [1,2,3], [1.0, 2.0,
3.0]]
•Python Lists are the most versatile
compound data types.
•A Python list contains items separated by
commas and enclosed within square
brackets ([ ]).
•To some extent, Python lists are similar to
arrays in C. One difference between them is
that all the items belonging to a Python list
can be of different data type whereas C
array can store elements related to a
particular data type.
>>> list = [ 'abcd', 786, 2.23, 'Mona', 70.2 ]
>>> tinylist = [123, 'ali']
>>> print(list)
>>> print(list[0])
>>> print(list[1:3])
>>> print(list[2:])
>>> print(tinylist * 2)
>>> print(list + tinylist)
>>> list[1] = 'Mohamed'
>>> list.append(10)
>>> list.remove('Mona') # or list.pop(2)

4) Lists (Cont.)
>>> list1 = ['Physics', 'Biology', 'Chemistry', 'Maths']
>>> list1.sort() # sort list alphabetically
>>> print(list1)
>>> numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
>>> numbers.reverse() # reverse list items
>>> print(numbers)
>>> sorted_desc = sorted(numbers, reverse=True) # sort list in descending order
>>> print(sorted_desc)
>>> numbers.index(9) # find the index of the element '9'
>>> numbers.insert(2, "Python") # add element "Python" at index '2'
>>> print(numbers)
>>> numbers.clear() # delete all list elements
>>> print(numbers)

5) Tuples
>>> myTuple = (2024, "Python", 3.11, 5+6j, 1.23E -4)
>>> type(myTuple)
<class 'tuple'>
>>> (['One', 'Two', 'Three'], 1,2.0,3, (1.0, 2.0,
3.0))
>>> 2024, "Python", 3.11, 5+6j, 1.23E -4
(2024, 'Python', 3.11, (5+6j), 0.000123)
•Python tuple is another sequence data
type that is similar to a list.
•A tuple is an immutable sequence of
values. Unlike lists, tuples cannot be
modified after they are created.
•A Python tuple consists of a number of
values separated by commas and
enclosed within parentheses ( ).
>>> tuple = ( 'abcd', 786, 2.23, 'Mona', 70.2 )
>>> tinytuple = (123, 'ali')
>>> print(tuple)
>>> print(tuple[0])
>>> print(tuple[1:3])
>>> print(tuple[2:])
>>> print(tinytuple * 2)
>>> print(tuple + tinytuple)
>>> del tuple

6) Dictionaries
>>> myDict = { 1:'one', 2:'two', 3:'three' }
>>> type(myDict)
<class 'dict'>
•Python dictionaries are kind of hash table
type.
•A dictionary key can be almost any Python
type, but are usually numbers or strings.
•Values, on the other hand, can be any
arbitrary Python object.
•Python dictionary is like associative arrays
or hashes and consist of <key: value> pairs.
•The pairs are separated by comma and put
inside curly brackets {}. To establish
mapping between key and value, the colon
':' symbol is put between the two.
>>> dict = { }
>>> dict['one'] = "This is one"
>>> dict[2] = "This is two"
>>> tinydict = {'name': 'john','code':6734, 'dept':
'sales'}
>>> print (dict['one'])
>>> print (dict[2])
>>> print (tinydict)
>>> print (tinydict.keys())
>>> print (tinydict.values())

6) Dictionaries (Cont.)
>>> student_info = {
'id': 123456789,
'name’: "john",
'age': 24,
'major': "Computer Science"
}
>>> name = student_info["name"]
>>> print(f"Name: {name}")
>>> student_info["age"] = 20
>>> graduation_year = student_info.pop("age")
>>> print(student_info)
>>> all_keys = student_info.keys()
>>> print("Keys:", all_keys)
>>> all_values = student_info.values()
>>> print("Values:", all_values)
>>> print (numbers.items())

7) Sets and frozensets
>>> mySet = {2024, "Python", 3.11, 5+6j, 1.23E -4}
{(5+6j), 3.11, 0.000123, 'Python', 2024}
>>> type(mySet)
<class 'set’>
>>> mySet.add("C++")
>>> mySet.remove("3.11")
>>> {['One', 'Two', 'Three'], 1,2,3, (1.0, 2.0, 3.0)}
# Error
>>> myFrozenSet = frozenset({2024, "Python", 3.11,
5+6j, 1.23E-4})
>>> type(myFrozenSet)
<class 'frozenset'>
>>> frozenset({['One', 'Two', 'Three'], 1, 2, 3, (1.0,
2.0, 3.0)}) # Error
•Set is a Python implementation of set as
defined in Mathematics.
•An object cannot appear more than once in
a set, whereas in List and Tuple, same object
can appear more than once.
•Items in the set collection can be of different
data types.
•A set is mutable and can store only
immutable objects such as number (int,
float, complex or bool), string or tuple.
•A frozenset in Python is an immutable
version of a set. This means that once a
frozenset is created, you cannot modify it.

7) Sets and frozensets (Cont.)
>>> s1 = { 1, 2, 3, 4, 5 }
>>> s2 = { 4, 5, 6, 7, 8 }
>>> s3 = s1 | s2 # union two sets
>>> print (s3)
>>> s3 = s1.union(s2) # union two sets
>>> print (s3)
>>> s3 = s1 & s2 # intersect two sets
>>> print (s3)
>>> s3 = s1 – s2 # difference b/w two sets
>>> print (s3)

Python Data Type Conversion
>>> print("Conversion to integer data type")
>>> a = int(1) # a will be 1
>>> b = int(2.2) # b will be 2
>>> c = int("3.3") # c will be 3
>>> print("Conversion to floating point number")
>>> a = float(1) # a will be 1.0
>>> b = float(2.2) # b will be 2.2
>>> c = float("3.3") # c will be 3.3
>>> print("Conversion to string")
>>> a = str(1) # a will be "1"
>>> b = str(2.2) # b will be "2.2"
>>> c = str("3.3") # c will be "3.3"
•int()
•float()
•long()
•complex()
•chr()
•str()
•list()
•tuple()
•set()
•frozenset()
•dict()
There’re several built-in functions to perform
conversion from one data type to another.

Python Implicit Casting
>>> a = 10 # int object
>>> b = 10.5 # float object
>>> c = a+b
20.5
•When any language interpreter automatically converts object of one type into another, this
is called automatic or implicit casting.
•Python is a strongly typed language.
>>> a = True
>>> b = 10.5
>>> c = a + b
11.5

Conversion of Sequence Types
•List, Tuple and String are Python's
sequence types.
•They are ordered or indexed
collection of items.
>>> a = [1, 2, 3, 4, 5] # List Object
>>> b = (1, 2, 3, 4, 5) # Tupple Object
>>> c = "Hello" # String Object
>>> list(c)
['H’, 'e’, 'l’, 'l’, 'o']
>>> list(b)
[1, 2, 3, 4, 5]
>>> tuple(c)
('H', 'e', 'l', 'l', 'o’)
>>> tuple(a)
(1, 2, 3, 4, 5)
>>> str(a)
'[1, 2, 3, 4, 5]'
>>> str(b)
'(1, 2, 3, 4, 5)'

Comments
# Single Line Comment
"""
Multi-LineComment
This is Line 2
This is Line 3
"""
•Single Line Comments
•Multi-Line Comments
–Comments in Python are used to provide information about lines of code.

Operators in Python
–Python has many operators defined.
–The operators fall into several categories:
arithmetic
relational
(Comparison)
bitwise
assignment logical membership

1) Arithmetic Operators
–The basic operators for performing arithmetic operations are the same in many
computer languages

a = 10
b = 20
print("a + b = ", a + b)
a = 10
b = 20.5
print("a + b = ", a + b)
a = 10 + 5j
b = 20.5
print("a + b = ", a + b)
a = 10
b = 20
print("a + b = ", a + b)
a = 10
b = 20.5
print("a + b = ", a + b)
a = 10 + 5j
b = 20.5
print("a + b = ", a + b)
Addition (+): Subtraction (–):

a = 10
b = 20.5
print("a * b = ", a * b)
a = -5.55
b = 6.75e-3
print("a * b = ", a * b)
a = 10 + 5j
b = 20.5
print ("a * b = ", a * b)
Multiplication (*):Division ( / ):
a = 10
b = 20
print("a / b = ", a/b)
a = -2.50
b = 1.25e2
print("a / b = ", a/b)
a = 7.5 + 7.5j
b = 2.5
print ("a / b = ", a/b)

Modulus ( % ): Exponent ( ** ):
a = 10
b = 2
print("a % b = ", a % b)
a = 7.7
b = 2.5
print("a % b = ", a % b)
a=0
b=10
print("a % b = ", a % b)
a = 10
b = 2
print ("a ** b = ", a**b)
a = 7.7
b = 2
print ("a ** b = ", a**b)
a = 12.4
b = 0
print ("a ** b = ", a**b)

Floor Division Operator ( // ):
a = -10
b = 1.5
print ("a // b = ", a//b)
•Floor division is also called as integer division.
a = 9
b = 2
print("a // b = ", a//b)
a = 10
b = 1.5
print("a // b = ", a//b)

2) Assignment Operator
–The assignment operator ‘ = ’ assigns a value to a variable.
–The assignment operator works from right to left.
a = 1
a = b
c = a = b ‘equivalent to c = (a = b)’
print(f"a = {a}, b = {b}, c = {c}")

2) Assignment Operators (Cont.)
–The standard programming for changing a variable's value by a specific
quantity:
i = i + 10
i = i – 10
i = i * 10
i = i / 10
i = i // 10
i = i ** 10
i = i % 10
i += 10
i –= 10
i *= 10
i /= 10
i //= 10
i **= 10
i %= 10






3) Relational (Comparison) Operators
Evaluated from left to right

3) Relational Operators – Equal to (==)
–The function of the ‘equal to’ operator ( == ) is to check if two of the
available operands are equal to each other or not.
–If it is so, then it returns to be true, or else it returns false.
–Examples:
3 == 3 will return true
2 == 3 will return false

3) Relational Operators – Not Equal (!=)
–The function of the ‘not equal’ operator ( != ) is to check if two of the
available operands are not equal to each other.
–If they’re, then it returns true, otherwise false.
–Examples:
2 != 3 will return true
3 != 3 will return false

3) Relational Operators – Less Than (<)
–The function of the ‘less than’ operator ( < ) is to check if the first
available operand is less than the second one.
–If so, then it returns true, otherwise false.
–Examples:
3 < 3 will return false
2 < 3 will return true

3) Relational Operators – Less or Equal (<=)
–The function of the ‘less than or equal’ operator ( <= ) is to check if the
first available operand is less than or equal to the second one.
–If so, then it returns true, otherwise false.
–Examples:
3 <= 3 will return true
2 <= 3 will return true
8 < 5 < 2 will return false
(8 < 5) → False or 0
0 < 2 → True

3) Relational Operators – Greater Than (>)
–The function of the ‘greater than’ operator ( > ) is to check if the first
available operand is greater than the second one.
–If so, then it returns true, otherwise false.
–Examples:
4 > 3 will return true
2 > 3 will return false
8 > 5 > 2 will return false (8 > 5) and (5 > 2)

3) Relational Operators – Greater or Equal (>=)
–The function of the ‘greater than or equal’ operator ( >= ) is to check if
the first available operand is greater than or equal to the second one.
–If so, then it returns true, otherwise false.
–Examples:
4 >= 3 will return true
2 >= 3 will return false

More Examples:
a = (1, 2, 3)
b = (1, 2, 5)
print ("a == b ? ", a == b)
a = 5
b = 7
print(a > b)
a = 10
b = 10.0
print ("a == b ? ", a == b)
a = 'Hello'
b = 'World'
print ("a == b ? ", a == b)
a = {1: 1, 2: 2}
b = {1: 1, 2: 2, 3: 3}
print ("a == b ? ", a==b)

4) Logical Operators
–We have three major logical operators in the Python
Important: Short-Circuiting in Logical Operators in Python.
Logical NOT (not)
Logical OR (or)
Logical AND (and)
False and (1 / 0)
True or (1 / 0)

Name AND OR NOT XOR
Algebraic
Expression
&#3627408436;&#3627408437;&#3627408436;+&#3627408437; ҧ&#3627408436; &#3627408436;⊕&#3627408437;
Symbol
Truth
Table
A
B
C
A
B
C A C
A C
0 1
1 0
A B C
0 0 0
0 1 0
1 0 0
1 1 1
A B C
0 0 0
0 1 1
1 0 1
1 1 1
Logic Gates
A B C
0 0 0
0 1 1
1 0 1
1 1 0
A
B
C

Examples:
A = 10
B = 20
print(A > 0 and A < 4)
print(A > 12 or B > 10)
print (not (A + B) > 15)
A = 10
B = 20
print(A and B)
print(A or B)
print (not A)

5) Bitwise Operators
–Types of bitwise operators found in Python programming language
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise complement
<< Shift left
>> Shift right

5) Bitwise Operators - AND
Example:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise AND operation of 12 and 25
00001100
& 00011001
________
00001000 = 8 (In decimal)

5) Bitwise Operators - OR
Example:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise OR operation of 12 and 25
00001100
| 00011001
________
00011101 = 29 (In decimal)

5) Bitwise Operators - XOR
Example:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise XOR operation of 12 and 25
00001100
^ 00011001
________
00010101 = 21 (In decimal)

5) Bitwise Operators – Complement (Not)
Example:
35 = 00100011 (In Binary)
Bitwise complement operation of 35
~ 00100011
________
11011100 = –36 (In decimal)
–Also called as one’s complement operator.

5) Bitwise Operators – Right shift

5) Bitwise Operators – Right shift
Example:
212 = 11010100 (In binary)
212 >> 2 = 00110101 (In binary) [Right shift by two bits]
212 >> 7 = 00000001 (In binary)
212 >> 8 = 00000000
212 >> 0 = 11010100 (No Shift)
–Right shift operator shifts all bits towards right by certain number of
specified bits.

5) Bitwise Operators – Left shift

5) Bitwise Operators – Left shift
Example:
212 = 11010100 (In binary)
212 << 1 = 110101000 (In binary) [Left shift by one bit]
212 << 0 = 11010100
212 << 4 = 110101000000 (In binary) = 3392 (In decimal)
–Left shift operator shifts all bits towards left by certain number of
specified bits.

6) Membership Operators
–The Python membership operators are used to test if a value or variable is found in a
sequence (like a list, tuple, or string) or a collection (like a set or dictionary).
–There are two membership operators:
•in operator
•not in operator
fruits = ['apple', 'banana', 'cherry']
print('banana' in fruits)
print('grape' not in fruits)
sentence = "The quick brown fox"
print('slow' in sentence)
print('quick' not in sentence)

7) Identity Operators
–In Python, identity operators are used to compare the memory locations of two objects to
determine if they are the same object, not just if they have the same value.
–There are two identity operators:
•is operator
•is not operator
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a is b)
print(c is a)
print(b is not c)

Operators Precedence
Category Operator Associativity
Parentheses and braces (), [], {} Left to right
Exponentiation ** Right to left
Unary +, -, ~ Right to left
Multiplication, division, floor
division, and modulus
*, @, /, /*, % Left to right
Addition and subtraction +, - Left to right
Bitwise shift operators <*, >* Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical, Comparison … operators=*, !*, >, >*, <, <*, is, is not, in, not in Left to right
Boolean NOT not Right to left
Boolean AND and Left to right
Boolean OR or Left to right

a = 20
b = 10
c = 15
d = 5
e = 0
e = (a + b) * c / d # ( 30 * 15 ) / 5
print ("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ", e)
e = (a + b) * (c / d); # (30) * (15/5)
print ("Value of (a + b) * (c / d) is ", e)
e = a + (b * c) / d; # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e)
Precedence Examples:

Expression
Statement 1
Statement 2
Statement n

Statement 1
Statement 2
Statement n

True False
Flowchart of if-else decision making statements

Syntax
if (expression):
statement(s)
if (expression):
statement(s)
else:
statement(s)
x = 7
if x == 5:
print("Yes")
x = 7
if x == 5:
print("Yes")
else:
print("No")

if else-if ladder
if (expression):
statement
elif:
statement
else:
statement
x = 5
if x == 5:
print("x = 5")
elif x > 5:
print("x > 5")
else:
print("x < 5")

Another Example #1
x = 7
if x == 5:
print("x = 5")
elif x > 5 and x < 10:
print("5 < x < 10")
else:
print("x < 5 or x > 10")

Another Example #2
age = 25
if age >=18:
print("eligible to vote")
else:
print("not eligible to vote")

Ternary If Statement
>>> num1 = 10
>>> num2 = num1 if num1 == 10 else 20
>>> print(f"num1 = {num1}, num2 = {num2}" )
>>> x = 5
>>> result = "Positive" if x > 0 else ("Zero" if x == 0 else "Negative")
>>> print(result)
>>> a = 5
>>> b = 10
>>> max_value = a if a > b else b
>>> print(max_value)
•In Python, you can use the ternary if (conditional expression) to assign a value based on a
condition in a single line.

What will be the output?
a = 1
if a == 0:
print("a = 0")
a = 12
if a = 0:
print("a = 0")
a = 5
if 1 < a < 10:
print("True")
a = 7
if a:
print("a is non-zero")

Match Statement
match (expression):
casevalue1:
// codetobeexecuted
casevalue2:
// codetobeexecuted
...
case _:
// codetobeexecutedifallcasesarenotmatched
Rules for Match Statement
1.Thematch expressionmust be of an integer or character type.
2.Thecase valuemust be an integer or character constant.
3.Thecase valuecan be used only inside the match statement.

Match Statement – Example 1
# Define the grade variable
grade = 'A'
# Use the match statement to handle different cases
match grade:
case 'A':
print("Excellent!")
case 'B':
print("Good!")
case _:
print("Failed!")

Match Statement – Example 2
# Define the grade variable
grade = 'A'
# Use the match statement to handle different cases
match grade:
case 'A' | 'B':
print("Good!")
case _:
print("Failed!")
You can combine multiple cases.

user = "admin"
match user:
case "admin" | "manager":
print("Full access granted")
case "guest":
print("Limited access granted")
case _:
print(“Access denied")
Match Statement – Example 3

details = ["Morning", "Mohamed"]
# details = ["Afternoon", "Guest"]
# details = ["Evening", "Mohamed", "Ahmed", "Mona"]
match details:
case [time, name]:
print(f'Good {time} {name}!')
case [time, *names]:
msg = ''
for name in names:
msg += f'Good {time} {name}!'
print(msg)
Match Statement – Example 4

Vending Machine

??????GitHub - Johna ta Da v i/ uri- online - judg e : List of URI resolv ed issues in some la ng ua g es such a s C ++, Ja v a , Py thon, S Q L, a mong others.

End of lecture 1
Thank You!