Python & SQL BibleChapter 34

3.4 Practice Exercises

Section 4 of 4-~ 12 min read-Synced from Cuantum content

Exercise 1: Conditional Statements

Create a Python program that asks the user for an integer and prints whether the number is even or odd.

# Here's a sample solutionnumber = int(input("Enter a number: "))if number % 2 == 0:    print(f"{number} is even")else:    print(f"{number} is odd")

Exercise 2: Loops

Write a Python program that prints all the numbers from 0 to 6 except 3 and 6.

# Here's a sample solutionfor x in range(6):    if (x == 3 or x==6):        continue    print(x, end=' ')

Exercise 3: Error and Exception Handling

Write a Python program that prompts the user for an integer and prints the square of it. Use a while loop with a try/except block to account for incorrect inputs.

# Here's a sample solutionwhile True:    try:        n = int(input("Enter an integer: "))        print("The square of the number is", n**2)        break    except ValueError:        print("That was not a valid integer. Please try again...")

Exercise 4: Iterables and Iterators

Create a Python iterator that returns the Fibonacci series. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1.

# Here's a sample solutionclass Fibonacci:    def __iter__(self):        self.a = 0        self.b = 1        return self     def __next__(self):        fib = self.a        self.a, self.b = self.b, self.a + self.b        return fib fib = Fibonacci()for i in range(10):    print(next(fib), end=" ")

These exercises should help in understanding and applying the concepts discussed in this chapter. Make sure to try out these exercises and experiment with the code to deepen your understanding of control flow in Python.

Chapter 3 Conclusion

In this chapter, we delved into the core elements that allow you to control the flow of your Python programs. We started with control structures in Python, including conditional statements and loops, which are the basic building blocks of any programming language. We learned how to use 'if', 'elif', and 'else' statements to make decisions in our code, and how 'for' and 'while' loops enable us to execute a block of code multiple times, reducing repetition and making our code more efficient.

We then explored error and exception handling in Python, understanding the difference between syntax errors and exceptions. We saw how Python's try-except-else-finally blocks allow us to handle exceptions gracefully, improving the robustness of our code and enhancing the user experience.

Our exploration of Python's control flow wouldn't be complete without understanding the concepts of iterables and iterators. We learned about Python's iteration protocol and how we can leverage it to create custom iterator objects. We also touched on the itertools module, which provides powerful functions for manipulating iterators.

Finally, we discussed generators, a special type of iterator. We learned how they allow us to create iterables in a more memory-efficient way, especially useful when working with large data streams.

The concepts covered in this chapter are fundamental to programming in Python. Understanding them deeply and knowing how to use them effectively will allow you to write more flexible, efficient, and robust Python programs.

Now that we have a firm understanding of Python's control flow, we're equipped to dive into more complex topics, like functions, modules, and object-oriented programming. As always, don't forget to experiment with the code and solve the practice problems - the best way to learn is by doing!

That concludes our exploration of Python's control flow. See you in the next chapter!