Introduction to Python - Basics #2
This section builds upon the foundational concepts introduced earlier, diving into conditional statements, loops, functions, and the importance of syntax. These are essential for writing programs that make decisions and perform repetitive tasks. Let’s explore these topics with examples and explanations below.
1. Conditional Statements
Python uses if, elif, and else statements to make decisions based on conditions:
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
2. Loops
Loops allow us to execute a block of code multiple times. Python supports for and while loops:
# Example of a for loop
for i in range(5):
print(i) # Prints numbers from 0 to 4
# Example of a while loop
x = 0
while x < 5:
print(x)
x += 1 # Increment x
3. Functions
A function is a block of code designed to perform a specific task. We use the def keyword to define a function:
def greet(name):
print("Hello, " + name + "!")
greet("Hannah") # Outputs: Hello, Hannah!
4. The Importance of Syntax and Spacing
Python relies heavily on proper indentation to define blocks of code. Unlike some other programming languages, Python does not use braces ({}) to separate blocks. Instead, it uses consistent spacing:
# Correct syntax
if x > 5:
print("x is greater than 5")
# Incorrect syntax (will cause an error)
if x > 5:
print("x is greater than 5") # No indentation
- Indentation: Use 4 spaces for each indentation level.
- Consistency: Mixed use of tabs and spaces can cause errors. Stick to one.
- Readability: Proper formatting makes code easier to understand and debug.
1. What does the following code output?
x = 10
if x > 5:
print("Greater than 5")
2. Which of the following is a valid Python loop?
3. What keyword is used to define a function in Python?
4. What will the following code output?
def greet():
print("Hello!")
greet()
5. Which operator is used for exponentiation in Python?
6. What will happen if you forget to properly indent a block of code in Python?
7. Why is consistent spacing important in Python?