Basic Python Concepts
Instructor: Dr. Merouane Boudraa
Email: merouaneboudraa98@[Link]
1. Syntax and Structure
Python is known for its clean and readable syntax. Indentation plays a crucial role in Python
and defines how code is grouped.
Indentation
• In Python, indentation (spaces or tabs) defines code blocks.
• It is required inside functions, loops, and conditional statements.
Example (Correct Indentation):
def greet(name):
print("Hello, " + name) # This line is indented and part of the
function
greet("Ahmed")
Comments
Single-line Comments
Use # to write comments that Python ignores.
# This is a comment
age = 25 # This comment explains that age is assigned a value
Multi-line Comments / Documentation
Use triple quotes (''' or """):
"""
This function takes a name as input
and prints a personalized greeting.
"""
def greet(name):
print("Hello, " + name)
2. Basic Input and Output
Example:
name = input("Enter your name: ")
print("Hello, " + name + "!")
3. Data Types and Variables
Variables
Variables store data and are created with an assignment:
age = 25
name = "Ahmed"
print(age)
print(name)
Rules for Naming Variables
• Must start with a letter or underscore (_)
• Cannot start with a number
• No spaces or special characters
• Case-sensitive (Age ≠ age)
Basic Data Types
Type Example Meaning
int 10 Whole number
float 3.14 Decimal number
str "Hello" Text
bool True / False Logical value
Type Conversion
Input is always a string; you can convert types like this:
age = input("Enter your age: ")
age = int(age)
print("Next year, you will be", age + 1)
Conversions: int(), float(), str(), bool()
4. Operators
Arithmetic Operators
+, -, *, /, ** (exponent)
Comparison Operators
Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal 5 != 3 True
> Greater than 7>2 True
< Less than 4<1 False
>= Greater or equal 6 >= 6 True
<= Less or equal 2 <= 3 True
Example:
x = 10
y = 5
print(x > y)
print(x == y)
print(x != y)
Logical Operators
Operator Meaning Example Result
and True if both true (5 > 3 and 2 > 4) False
or True if at least one true (5 > 10 or 3 < 5) True
not Reverses True/False not(5 > 2) False
Example:
age = 20
print(age > 18 and age < 30)
print(age < 18 or age > 65)
print(not(age == 20))
5. Conditional Statements (if, elif, else)
Structure:
if condition:
# code if true
elif another_condition:
# code if second condition true
else:
# code otherwise
Example:
temperature = 25
if temperature > 30:
print("It’s a hot day!")
elif temperature >= 20:
print("It’s a nice day!")
else:
print("It’s cold!")
Nested Conditions
age = 18
has_license = True
if age >= 18:
if has_license:
print("You can drive!")
else:
print("You need a driving license.")
else:
print("You are too young to drive.")
Correct vs Wrong Indentation
Wrong:
if age > 18:
print("Adult")
Correct:
if age > 18:
print("Adult")
6. Loops
For Loop
Used to iterate over sequences.
Example 1:
for i in range(1, 6):
print(i)
While Loop
Runs while a condition is True.
count = 1
while count <= 5:
print(count)
count += 1
break and continue
• break stops the loop immediately.
• continue skips the current iteration and continues with the next.
for i in range(1, 10):
if i == 5:
break
print(i)
for i in range(1, 10):
if i % 2 == 0:
continue
print(i)
Nested Loops
for i in range(1, 4):
for j in range(1, 4):
print(f"i={i}, j={j}")
7. Lists
What Is a List?
A list is:
• ordered
• mutable
• dynamic
• allows duplicates
Example:
my_list = [10, "hello", 3.14, True]
Creating Lists
students = []
numbers = [1, 2, 3, 4]
info = ["Ahmed", 25, 75.5, True]
Accessing Items
fruits = ["apple", "banana", "orange"]
print(fruits[0]) # apple
print(fruits[2]) # orange
print(fruits[-1]) # orange
print(fruits[-2]) # banana
Changing List Elements
fruits = ["apple", "banana", "orange"]
fruits[1] = "kiwi"
Adding Items
[Link]("mango")
[Link](1, "grapes")
Removing Items
[Link]("banana")
[Link](2)
[Link]()
del fruits[0]
[Link]()
List Slicing
numbers = [1, 2, 3, 4, 5, 6]
print(numbers[1:4]) # [2, 3, 4]
print(numbers[:3]) # [1, 2, 3]
print(numbers[::-1]) # print list in reverse order[6, 5, 4,3,2,1]
Looping Through Lists
for item in fruits:
print(item)
for i in range(len(fruits)):
print(i, fruits[i])
Useful List Methods
1. Adding Items
Method Description
append(x) Add element at end
insert(i, x) Insert at index
extend(list) Add multiple items
2. Removing Items
Method Description
remove(x) Remove first occurrence
pop(i) Remove element at index
clear() Empty list
3. Searching / Counting
Method Description
index(x) Index of x
count(x) Count occurrences
4. Sorting / Reversing
Method Description
sort() Sort list
reverse() Reverse list
sorted(list) Return new sorted list
5. Copying
new_lst = [Link]()
6. Other Useful Functions
Function Description
len() Number of elements
max() Largest element
min() Smallest element
sum() Sum of numbers
any() True if any element is True
all() True if all elements are True