Step 1: Functions
Functions allow you to encapsulate code for reuse.
# Defining a function
def greet(name):
print(f"Hello, {name}!")
# Calling a function
greet("Alisha")
Explanation: Functions take input arguments, perform actions, and can optionally return a value using return.
Function with Return Value
def square(num):
return num * num
result = square(5)
print(result) # Output: 25
Step 2: Conditional Statements
Use if, elif, and else to control program flow.
age = 18
if age >= 18:
print("You are an adult")
elif age >= 13:
print("You are a teenager")
else:
print("You are a child")
Explanation: Conditions are evaluated in order. The first True condition executes its block.
Step 3: For Loops
For loops iterate over a sequence (list, tuple, string, range).
# Loop over a list
fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:
print(fruit)
# Loop with range
for i in range(1, 6): # 1 to 5
print(i)
Step 4: While Loops
While loops execute as long as the condition is True.
count = 1
while count <= 5:
print(count)
count += 1
Step 5: Combining Loops and Conditionals
Example: Print only even numbers from a list.
numbers = [1, 2, 3, 4, 5, 6]
for num in numbers:
if num % 2 == 0:
print(num)
Step 6: PyCharm Project Layout
FunctionsLoopsProject
├── functions_demo.py
├── if_demo.py
├── for_loop_demo.py
└── while_loop_demo.py
# Example: functions_demo.py
def square(num):
return num * num
print(square(7))
Step 7: Tips & Best Practices
- Use functions to avoid repeating code and improve readability.
- Use meaningful variable names inside loops and functions.
- Be careful with loop conditions to avoid infinite loops.
- Use
break and continue wisely in loops.
- Indentation is crucial in Python for loops and conditionals.
✔ End of Day 7 – You now understand Functions, Conditional Statements, Loops, and can structure projects in PyCharm efficiently!