Python Crash Course
Python Crash Course
Python Basics
Topic Description
Strings
String creation
Printing
Indexing
Escape sequences
String operations
Booleans
True and False values
Boolean operations
Lists
Indexing
Slicing
List manipulation
Copying / cloning lists
Tuples
Sets
Dictionaries
Creating dictionaries
Accessing values
Dictionary operations
Operators
Identity is , is not
Membership in , not in
Conditional Statements
┌─────────────────────────┐
│ if condition: │
│ # code block │
│ elif condition: │
│ # code block │
│ else: │
│ # code block │
└─────────────────────────┘
if - Primary condition
elif - Alternative conditions
else - Default fallback
Branching logic
Loops
Functions
Lambda Expressions
lambda arguments: expression
Functional Programming
map() - Transform items
filter() - Select items
Built-in Methods
String methods
List methods
Dictionary methods
Learning Objectives
After completing this session, you will be able to:
Basic Skills
Write basic Python code
Work with various data types
Convert data from one type to another
Use expressions and variables
Data Manipulation
Perform string operations and manipulation
Work with lists, tuples, sets, and dictionaries
Control Flow
Apply conditional statements
Use loops effectively
Advanced Concepts
Create and use functions
Apply functional programming tools like lambda , map , and filter
hallo world
hallo world
hallo&world
hallo world
Data Types
5 + 2 = 7
5 - 2 = 3
5 * 2 = 10
5 / 2 = 2.5
5 % 2 = 1
5 // 2 = 2
In [6]: num = 1
num = 1.0
print(0.1+0.2)
0.30000000000000004
0.3
Strings
String Creation
In [8]: #### note ( double_quotes ): It helps when your string contains quotes.
single_quotes = 'Hello'
double_quotes = "World"
triple_quotes = '''Multi
line
string'''
triple_double = """Another
multi-line"""
print(text)
Indexing
H
o
l
l
Slicing
Pyt
thon
Pyth
Pto
nohtyP
text[6:11] - text[-4:-1]
text[:5] - text[-11:-1]
text[6:] - text[:-4]
text[:] - text[-4:]
text[-4] - text[6:-2]
text[-11] - text[-11:5]
text[1::2] - text[:-1]
text[::-1] - text[-5:-2]
text[::-2] - text[3:9:2]
text[6::-1] - text[9:3:-1]
Basic Slicing text[0:5] 'Hello' Start to position 5 - Negative Slicing text[-1:-4] '' Empty (backwards)
text[:5] 'Hello' From start to 5 - text[-11:-1] 'Hello worl' 11th last to 1st last
text[6:] 'world' From 6 to end - text[:-4] 'Hello wo' All except last 4
Negative Indexing text[-1] 'd' Last character - Mixed Positive & Negative text[0:-4] 'Hello wo' Start to 4th from end
text[-4] 'o' 4th from end - text[6:-2] 'wor' 6th to 2nd from end
text[-11] 'H' 11th from end - text[-11:5] 'Hello' 11th from end to 5th
Step Slicing text[::2] 'Hlowrd' Every 2nd character - Tricky Examples text[-1:] 'd' Last character as slice
text[1::2] 'el ol' Every 2nd from index 1 - text[:-1] 'Hello worl' All except last
text[::-1] 'dlrow olleH' Reverse string - text[-5:-2] 'wor' 5th last to 2nd last
text[::-2] 'drwo lH' Reverse every 2nd - text[3:9:2] 'lo o' Index 3 to 9, step 2
text[6::-1] ' olleH' From index 6 backwards - text[9:3:-1] 'lrow o' Index 9 to 3 backwards
String Operations
Basic Operations
Operation Example Output Description
String Methods
Method Example Output Description
Checking Methods
Method Example Output Description
FIND vs INDEX
Method Found Not Found Raises Error?
Examples:
Membership Operators
Operator Example Output Description
When to Use?
Use find() when:
Casting
In [11]: num = 1
num1 = 1.0
string = "a"
string1 = "1"
string2 = "1.0"
Out[11]: (1.0, 1, 1)
Out[12]: True
Expression Output
bool(1)
bool(0)
bool("")
bool("a")
bool([])
bool([1, 2])
bool(100)
bool(-5)
bool(0.0)
List
In [13]: # List Creation
# Sample list with mixed types
mixed_list = ["Michael Jackson", 10.1, 1982, [1, 2], ("A", 1)]
print("Mixed list:", mixed_list)
# Accessing Elements
print("ACCESSING ELEMENTS")
my_list = ['a', 'b', 'c']
print("my_list:", my_list)
print("my_list[0]:", my_list[0])
# Adding Elements
# Using extend()
L = ["Michael Jackson", 10.2]
print("Original L:", L)
[Link](['pop', 10])
print("After extend:", L)
# Using append()
L = ["Michael Jackson", 10.2]
print("\nOriginal L:", L)
[Link](['pop', 10])
print("After append:", L)
# Modifying Elements
print("MODIFYING ELEMENTS")
# Deleting Elements
print("DELETING ELEMENTS")
# String Split
print("STRING SPLIT")
result = 'fady maher'.split()
print("'hard rock'.split():", result)
Mixed list: ['Michael Jackson', 10.1, 1982, [1, 2], ('A', 1)]
ACCESSING ELEMENTS
my_list: ['a', 'b', 'c']
my_list[0]: a
nest: [1, 2, 3, [4, 5, ['target']]]
nest[3]: [4, 5, ['target']]
nest[3][2]: ['target']
nest[3][2][0]: target
Original L: ['Michael Jackson', 10.2]
After extend: ['Michael Jackson', 10.2, 'pop', 10]
In [14]: s = {1,2,3,4,1,2}
t = (1,'a')
t[0]
Out[14]: 1
In [15]: t[0] = 0
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[15], line 1
----> 1 t[0] = 0
In [16]: s = "Fady"
s[0] = 'd'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[16], line 2
1 s = "Fady"
----> 2 s[0] = 'd'
Dictionary
In [17]: my_dict = {
"key1": 1,
"key2": 1.0,
"key3": "fady",
"key4": "hossam",
"key5": True,
"key6": [1, 2.0]
}
print("my_dict:", my_dict)
print("Type:", type(my_dict))
print("Length:", len(my_dict))
my_dict: {'key1': 1, 'key2': 1.0, 'key3': 'fady', 'key4': 'hossam', 'key5': True, 'key6': [1, 2.0]}
Type: <class 'dict'>
Length: 6
my_dict['key3']: fady
my_dict['key6']: [1, 2.0]
my_dict.get('key4'): hossam
my_dict.get('key10'): None
Items: dict_items([('key1', 1), ('key2', 1.0), ('key3', 'fady'), ('key4', 'hossam'), ('key5', True), ('key6', [1, 2.0])])
my_dict["key3"] = "ahmed"
print("After modifying key3:", my_dict)
MUTABLE vs IMMUTABLE
In [22]: # IMMUTABLE OBJECTS - Cannot be changed after creation
[Link](4)
print(f"After [Link](4):")
print(f"list1: {list1}") # list1 also changed!
print(f"list2: {list2}")
----------------------------------------------------------------------
In [23]: num1 = 1
num2 = 2
if num1 == 3 :
print("num1 == 3")
else:
if num1 > num2 :
print("num1 > num2")
else:
print("num1 < num2")
In [24]: num1 = 1
num2 = 2
if (num1 == 3) :
print("num1 == 3")
else:
if (num1 > num2) :
print("num1 > num2")
else:
print("num1 < num2")
In [26]: if num1 == 3 : {
print("num1 == 3")
}
elif num1 > num2 : {
print("num1 > num2")
}
else:{
print("num1 < num2")
}
LOOPS
I like apple
I like banana
I like cherry
I like orange
I like apple
I like banana
I like cherry
I like orange
finished
I like apple
I like banana
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
Even number: 0
Even number: 2
Even number: 4
Even number: 6
Even number: 8
Index 0: red
Index 1: green
Index 2: blue
In [33]: count = 0
print("Count from 0 to 4:")
while count < 5:
print(f" Count: {count}")
count += 1
Count from 0 to 4:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
In [34]: num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue # Skip even numbers
print(f" Odd: {num}")
Odd: 1
Odd: 3
Odd: 5
Odd: 7
Odd: 9
list comprehension
In [35]: # Traditional way with for loop
squares_loop = []
for i in range(10):
squares_loop.append(i ** 2)
print(f" {squares_loop}")
IS vs ==
== (Equality Operator)
Compares VALUES
Checks if two objects have the same content
Returns True if values are equal
is (Identity Operator)
In [69]: a = 5
b = 5
print(f"a = {a}, b = {b}")
print(f"a == b: {a == b} (values equal)")
print(f"a is b: {a is b} (same object)") # -5 to 256
print(f"id(a): {id(a)}")
print(f"id(b): {id(b)}")
a = 5, b = 5
a == b: True (values equal)
a is b: True (same object)
id(a): 140721730663464
id(b): 140721730663464
In [70]: x = 1000
y = 1000
print(f"x = {x}, y = {y}")
print(f"x == y: {x == y} (values equal)")
print(f"x is y: {x is y} (different objects)")
print(f"id(x): {id(x)}")
print(f"id(y): {id(y)}")
x = 1000, y = 1000
x == y: True (values equal)
x is y: False (different objects)
id(x): 1817023736368
id(y): 1817023736016
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
functions
In [72]: def square(number=2):
return number ** 2
'''
def square(number : int = 2):
return number ** 2
'''
# Way 1: Call with default parameter
result = square()
print("square() :", result)
square() : 4
square(3) : 9
square(number=5): 25
9
out2 = None
Type: <class 'NoneType'>
result1 = func()
print(f" Result: {result1}")
print(f" ID: {id(result1)}")
result3 = func([1])
print(f" Result: {result3}")
print(f" ID: {id(result3)}")
result4 = func()
print(f" Result: {result4}")
print(f" ID: {id(result4)}")
# The default list [] is created ONCE when the function is DEFINED, not each time the function is CALLED!
Result: [5]
ID: 1817024847296
Result: [1, 5]
ID: 1817024853760
Result: [5, 5]
ID: 1817024847296
Result: [5, 5, 5]
ID: 1817024847296
In [78]: func.__defaults__
result = sum_all(1, 2, 3, 4, 5)
print(f"Sum: {result}")
lambda
In [81]: funcv1 = lambda number : number * 2
In [82]: funcv1(2)
Out[82]: 4
In [84]: funcv2(2,3)
Out[84]: 6
map
map(function, sequence)
[2, 4, 6, 8, 10]
filter :
filter(function, sequence)
[2, 4]
Import
In [87]: import app
In [88]: [Link]()
hallo world