SlideShare a Scribd company logo
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 to Python Prog. - Lecture 1
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
PyCharm's top features. [Hidden] qualities of one of the most… | by Nicolò Gasparini | Analytics Vidhya | Medium
Introduction to Python Prog. - Lecture 1
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
- 12510
› 5 x 100 = 5
› 2 x 101 = 20
› 1 x 102 = 100
12510
Decimal Numbering System (Base 10)
+
+
- Technique:
• Multiply each bit by 2n, where n is the weight of the bit
• Add the results
– Convert the binary number 110012 to decimal
› 24 23 22 21 20
› 1 1 0 0 1
› 16 8 0 0 1 +
› 16 + 8 + 0 + 0 + 1 = 25
Binary to Decimal (Base 2)
×
Result: 2510
- Technique:
• Divide the number repeatedly by 2, while keeping track of the remainders.
• Arrange the remainders in reverse order.
– Convert the decimal number 2510 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:
110012
- Technique:
• Group the binary digits into sets of four.
• Convert each group to its corresponding hexadecimal digit.
– Convert the binary number 110110112 to hexadecimal
› 23 22 21 20 23 22 21 20
› 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: DB16
- Technique:
• Convert each hexadecimal digit to its binary representation.
• Similar to binary to hexadecimal but in a reversed way.
– Convert the hexadecimal number DB16 to binary
› D B
› 23 22 21 20 23 22 21 20
› 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:
110110112
- Technique:
• Sum of the positional values of each hexadecimal digit.
– Convert the hexadecimal number DB16 to decimal
› D B
› 13 x 161 + 11 x 160
› 208 + 11
Hexadecimal to Decimal (Base 16)
B: 11 , D: 13
Result: 21910
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 21910 to hexadecimal
Number Remainder
÷ 16 219 0.6875 x 16 = 11 ( B )
÷ 16 13 0.8125 x 16 = 13 ( D )
÷ 16 0 —
Result:
DB16
Introduction to Python Prog. - Lecture 1
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 Code
Interpreter
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.
Introduction to Python Prog. - Lecture 1
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
Introduction to Python Prog. - Lecture 1
print(type(x))
Python’s Core Data Types
Introduction to Python Prog. - Lecture 1
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")
Array
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
Introduction to Python Prog. - Lecture 1
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)'
Introduction to Python Prog. - Lecture 1
Comments
# Single Line Comment
"""
Multi-Line Comment
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.
Introduction to Python Prog. - Lecture 1
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
𝐴𝐵 𝐴 + 𝐵 ҧ
𝐴 𝐴 ⊕ 𝐵
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:
Introduction to Python Prog. - Lecture 1
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):
case value1:
// code to be executed
case value2:
// code to be executed
...
case _:
// code to be executed if all cases are not matched
Rules for Match Statement
1. The match expression must be of an integer or character type.
2. The case value must be an integer or character constant.
3. The case value can 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 - JohnataDavi/uri-online-judge: List of URI resolved issues in some languages such as C ++, Java, Python, SQL, among others.
End of lecture 1
ThankYou!

More Related Content

Similar to Introduction to Python Prog. - Lecture 1 (20)

PPTX
Python-Beginer-PartOnePython is one of the top programming languages in the w...
ahmedosman389
 
PPTX
Python
Suman Chandra
 
PPTX
Introduction to python
MaheshPandit16
 
PPTX
Review old Pygame made using python programming.pptx
ithepacer
 
PPTX
funadamentals of python programming language (right from scratch)
MdFurquan7
 
PDF
Python for data science by www.dmdiploma.com
ShwetaAggarwal56
 
PPTX
Python Tutorial for Beginner
rajkamaltibacademy
 
PDF
Python for Scientific Computing
Albert DeFusco
 
PPTX
Python_ppt for basics of python in details
Mukul Kirti Verma
 
PDF
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 
PPTX
python introduction initial lecture unit1.pptx
ChandraPrakash715640
 
PDF
Free Complete Python - A step towards Data Science
RinaMondal9
 
PPTX
presentation_python_7_1569170870_375360.pptx
ansariparveen06
 
PPT
Python tutorialfeb152012
Shani729
 
PDF
pyton Notes1
Amba Research
 
PPTX
Python Basics
Adheetha O. V
 
PDF
Intro-to-Python-Part-1-first-part-edition.pdf
ssuser543728
 
PPTX
Welcome to python workshop
Mukul Kirti Verma
 
PPTX
Introduction to Programming.pptx ok ok ok
846Sarthakpandey
 
Python-Beginer-PartOnePython is one of the top programming languages in the w...
ahmedosman389
 
Introduction to python
MaheshPandit16
 
Review old Pygame made using python programming.pptx
ithepacer
 
funadamentals of python programming language (right from scratch)
MdFurquan7
 
Python for data science by www.dmdiploma.com
ShwetaAggarwal56
 
Python Tutorial for Beginner
rajkamaltibacademy
 
Python for Scientific Computing
Albert DeFusco
 
Python_ppt for basics of python in details
Mukul Kirti Verma
 
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 
python introduction initial lecture unit1.pptx
ChandraPrakash715640
 
Free Complete Python - A step towards Data Science
RinaMondal9
 
presentation_python_7_1569170870_375360.pptx
ansariparveen06
 
Python tutorialfeb152012
Shani729
 
pyton Notes1
Amba Research
 
Python Basics
Adheetha O. V
 
Intro-to-Python-Part-1-first-part-edition.pdf
ssuser543728
 
Welcome to python workshop
Mukul Kirti Verma
 
Introduction to Programming.pptx ok ok ok
846Sarthakpandey
 

More from Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt (20)

PDF
How to install CS50 Library (Step-by-step guide)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Understanding Singular Value Decomposition (SVD)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Understanding K-Nearest Neighbor (KNN) Algorithm
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Understanding Convolutional Neural Networks (CNN)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Luhn's algorithm to validate Egyptian ID numbers
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Complier Design - Operations on Languages, RE, Finite Automata
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 5
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Understanding Convolutional Neural Networks (CNN)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Complier Design - Operations on Languages, RE, Finite Automata
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 5
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Ad

Recently uploaded (20)

PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PDF
Electrical Engineer operation Supervisor
ssaruntatapower143
 
PDF
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
PPTX
Introduction to Design of Machine Elements
PradeepKumarS27
 
PDF
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PPTX
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
PDF
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PDF
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
PDF
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
PDF
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
PDF
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
PPTX
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
PPTX
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
Electrical Engineer operation Supervisor
ssaruntatapower143
 
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
Introduction to Design of Machine Elements
PradeepKumarS27
 
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
Design Thinking basics for Engineers.pdf
CMR University
 
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
Ad

Introduction to Python Prog. - Lecture 1

  • 1. Introduction to Python Programming By Mohamed Gamal © Mohamed Gamal 2024
  • 2. Resources • Textbooks: • Learning Python Powerful Object-Oriented Programming 5th Edition • Head First Python, A Brain-Friendly Guide 2nd Edition • Other Resources
  • 3. • The topics of today’s lecture: Agenda
  • 5. 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.
  • 6. The Abacus – The abacus, a simple counting aid, may have been invented in Babylonia (now Iraq) in the fourth century B.C.
  • 8. 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.
  • 10. 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.
  • 11. 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.
  • 12. Python Careers and Applications • Python Developer • ML/AI Engineer • Data Scientist • Web Development • DevOps Engineer • Software Engineer • Game developer • Job Scheduling and Automation • … • etc.
  • 14. How to get started? – Download and install Python – Interactive Prompt – Using an Integrated Development Environment (IDE) – Online Python Interpreter PyCharm's top features. [Hidden] qualities of one of the most… | by Nicolò Gasparini | Analytics Vidhya | Medium
  • 16. Basic Notations Binary Digit → Bit 0, 1 8 bits = 1 byte ON 1 OFF 0
  • 17. - 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
  • 18. 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
  • 19. - 12510 › 5 x 100 = 5 › 2 x 101 = 20 › 1 x 102 = 100 12510 Decimal Numbering System (Base 10) + +
  • 20. - Technique: • Multiply each bit by 2n, where n is the weight of the bit • Add the results – Convert the binary number 110012 to decimal › 24 23 22 21 20 › 1 1 0 0 1 › 16 8 0 0 1 + › 16 + 8 + 0 + 0 + 1 = 25 Binary to Decimal (Base 2) × Result: 2510
  • 21. - Technique: • Divide the number repeatedly by 2, while keeping track of the remainders. • Arrange the remainders in reverse order. – Convert the decimal number 2510 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: 110012
  • 22. - Technique: • Group the binary digits into sets of four. • Convert each group to its corresponding hexadecimal digit. – Convert the binary number 110110112 to hexadecimal › 23 22 21 20 23 22 21 20 › 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: DB16
  • 23. - Technique: • Convert each hexadecimal digit to its binary representation. • Similar to binary to hexadecimal but in a reversed way. – Convert the hexadecimal number DB16 to binary › D B › 23 22 21 20 23 22 21 20 › 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: 110110112
  • 24. - Technique: • Sum of the positional values of each hexadecimal digit. – Convert the hexadecimal number DB16 to decimal › D B › 13 x 161 + 11 x 160 › 208 + 11 Hexadecimal to Decimal (Base 16) B: 11 , D: 13 Result: 21910 Note: another way is to first convert the hexadecimal number to binary and then convert the binary number to decimal.
  • 25. 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 21910 to hexadecimal Number Remainder ÷ 16 219 0.6875 x 16 = 11 ( B ) ÷ 16 13 0.8125 x 16 = 13 ( D ) ÷ 16 0 — Result: DB16
  • 27. How does it work?
  • 28. How does it work? Input Output Processing
  • 29. How does it work? Source Code Machine Code 0001011 Processing
  • 30. How does it work? Source Code Machine Code Interpreter Processing
  • 31. Your First Python Program >>> print("Hello World") Hello World >>> name = input("Enter your name: ") >>> print("Hello, " + name)
  • 33. 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.
  • 35. 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.
  • 36. 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).
  • 37. List of reserved Keywords
  • 38. 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.
  • 39. Random Access Memory (RAM) Finite!!!
  • 40. Variables in Memory x = 10 10 RAM Memory Location reserved and named as x x
  • 44. 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.
  • 45. 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.
  • 46. 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")
  • 47. Array 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.)
  • 48. 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:
  • 49. 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
  • 51. 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)
  • 52. 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)
  • 53. 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
  • 54. 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())
  • 55. 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())
  • 56. 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.
  • 57. 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)
  • 58. 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.
  • 59. 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
  • 60. 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)'
  • 62. Comments # Single Line Comment """ Multi-Line Comment 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.
  • 64. Operators in Python – Python has many operators defined. – The operators fall into several categories: arithmetic relational (Comparison) bitwise assignment logical membership
  • 65. 1) Arithmetic Operators – The basic operators for performing arithmetic operations are the same in many computer languages
  • 66. 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 (–):
  • 67. 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)
  • 68. 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)
  • 69. 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)
  • 70. 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}")
  • 71. 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 → → → → → → →
  • 72. 3) Relational (Comparison) Operators Evaluated from left to right
  • 73. 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
  • 74. 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
  • 75. 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
  • 76. 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
  • 77. 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)
  • 78. 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
  • 79. 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)
  • 80. 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)
  • 81. Name AND OR NOT XOR Algebraic Expression 𝐴𝐵 𝐴 + 𝐵 ҧ 𝐴 𝐴 ⊕ 𝐵 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
  • 82. 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)
  • 83. 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
  • 84. 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)
  • 85. 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)
  • 86. 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)
  • 87. 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.
  • 88. 5) Bitwise Operators – Right shift
  • 89. 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.
  • 90. 5) Bitwise Operators – Left shift
  • 91. 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.
  • 92. 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)
  • 93. 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)
  • 94. 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
  • 95. 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:
  • 97. Expression Statement 1 Statement 2 Statement n ⋮ Statement 1 Statement 2 Statement n ⋮ True False Flowchart of if-else decision making statements
  • 98. 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")
  • 99. 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")
  • 100. 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")
  • 101. Another Example #2 age = 25 if age >=18: print("eligible to vote") else: print("not eligible to vote")
  • 102. 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.
  • 103. 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")
  • 104. Match Statement match (expression): case value1: // code to be executed case value2: // code to be executed ... case _: // code to be executed if all cases are not matched Rules for Match Statement 1. The match expression must be of an integer or character type. 2. The case value must be an integer or character constant. 3. The case value can be used only inside the match statement.
  • 105. 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!")
  • 106. 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.
  • 107. 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
  • 108. 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
  • 110. 🔥 GitHub - JohnataDavi/uri-online-judge: List of URI resolved issues in some languages such as C ++, Java, Python, SQL, among others.
  • 111. End of lecture 1 ThankYou!