Python Crash Course: Part 2


Crash Course Part 1  |  Crash Course Part 2  |  Crash Course Part 3

Introduction

Welcome back to our Python Crash Course series! This is the second article in our series designed to impart the absolute essentials of Python, crafted especially for newcomers to the language and to the world of programming. If you’ve just begun your journey in computer science and are seeking a friendly guide to enhance your practical Python skills, you’ve come to the right place!

In our first article, we introduced Python, set up our environment, and explored the basics of variables, data types, and operations. We’ve already taken our first steps into Python programming by printing the classic “Hello, World!” to our screens. Now that we’ve laid the groundwork, it’s time to dig deeper and discover some of the structures that make Python such a powerful and versatile language. We will be covering conditional statements, loops, functions, and exception handling.

Conditional Statements

Conditional statements, often referred to as if-then statements, allow us to make decisions in our program and perform different actions based on certain conditions. In Python, we have three forms of these: if, else, and elif.

An if statement will execute a block of code if a certain condition is true. For example:

age = 16
if age >= 16:
    print("You're old enough to drive!")

In this code, the message is printed only if the variable age is greater than or equal to 16.

An else statement can be used with an if statement to handle the cases when the if condition is not true:

age = 13
if age >= 16:
    print("You're old enough to drive!")
else:
    print("Sorry, you're not old enough yet.")

In this example, the else block will execute if age is less than 16.

The elif statement allows us to check multiple conditions and execute a different block of code for each one:

age = 21
if age >= 35:
    print("You're old enough to become President!")
elif age >= 21:
    print("You're old enough to drink!")
elif age >= 18:
    print("You're old enough to vote!")
else:
    print("Sorry, you're not old enough yet.")

Here, the elif statements are checked in order. When a true condition is found, the corresponding block of code is executed.

Finally, we can use if statements inside other if statements. This is called nested conditions:

age = 17
if age >= 16:
    print("You're old enough to drive!")
    if age >= 18:
        print("You're also old enough to vote!")

In this case, the second if statement will only be checked if the first one is true.

Loops

A loop is a control structure that repeats a block of code. In Python, we have two types of loops: for and while.

A for loop iterates over a sequence of elements, like a list or a string:

for letter in 'Python':
    print(letter)

This code will print each letter in the word ‘Python’ on a new line.

A while loop repeats a block of code as long as a certain condition is true:

number = 1
while number <= 5:
    print(number)
    number += 1

This code will print the numbers from 1 to 5. It's important to have a well-defined exit condition to prevent infinite loops!

Python also has break and continue statements to control the flow of loops. The break statement stops the loop entirely, while the continue statement skips to the next iteration of the loop:

for number in range(1, 10):
    if number == 5:
        break
    print(number)

In this example, the numbers 1 to 4 will be printed, and then the loop will stop when number is equal to 5.

Functions

A function is a reusable block of code that performs a specific task. They are vital for organizing and modularizing our code.

In Python, we define a function using the def keyword, followed by the function name, parentheses, and a colon. The code block of the function is indented under the definition:

def greet():
    print("Hello, World!")

We call the function by using its name followed by parentheses:

greet()

Functions can take parameters, which are values that we can pass into the function when we call it:

def greet(name):
    print("Hello, " + name + "!")

And finally, functions can return values, which are results that the function sends back to the place where it was called:

def square(number):
    return number * number

Exception Handling

An exception is an error that occurs while a program is running. Python has many built-in exceptions, like ValueError or TypeError, and we can handle these exceptions using try and except blocks:

try:
    number = int(input("Enter a number: "))
except ValueError:
    print("That's not a valid number!")

In this code, if the user enters something that can't be converted to an integer, a ValueError is raised, and the code inside the except block is executed.

We can handle multiple exceptions by adding more except clauses:

try:
    number = int(input("Enter a number: "))
    result = 42 / number
except ValueError:
    print("That's not a valid number!")
except ZeroDivisionError:
    print("You can't divide by zero!")

Python's exceptions are organized in a hierarchy, and we can catch multiple exceptions by handling their common superclass. For example, both ValueError and ZeroDivisionError are subclasses of Exception, so we can handle them both with a single except Exception clause. But be careful, this will also catch all other kinds of exceptions!

Conclusion

And there we have it! You have successfully reached the end of our second article and made significant strides in your Python journey. From understanding the control and flow of your program with conditional statements and loops, to mastering the art of creating and using functions, and gracefully handling exceptions, you have amassed a wealth of knowledge that's essential to any Python programmer.

Remember, like any other skill, programming requires practice. So don't forget to experiment with the code examples and exercises shared in this article. In our upcoming third and final article in this series, we'll dive into more complex Python concepts and continue building your programming prowess. We hope you're excited for the next stage of this Python adventure. Happy coding, and we'll see you in the next article!