Book Image

Learn Python Programming - Second Edition

By : Fabrizio Romano
4.5 (2)
Book Image

Learn Python Programming - Second Edition

4.5 (2)
By: Fabrizio Romano

Overview of this book

Learn Python Programming is a quick, thorough, and practical introduction to Python - an extremely flexible and powerful programming language that can be applied to many disciplines. Unlike other books, it doesn't bore you with elaborate explanations of the basics but gets you up-and-running, using the language. You will begin by learning the fundamentals of Python so that you have a rock-solid foundation to build upon. You will explore the foundations of Python programming and learn how Python can be manipulated to achieve results. Explore different programming paradigms and find the best approach to a situation; understand how to carry out performance optimization and effective debugging; control the flow of a program; and utilize an interchange format to exchange data. You'll also walk through cryptographic services in Python and understand secure tokens. Learn Python Programming will give you a thorough understanding of the Python language. You'll learn how to write programs, build websites, and work with data by harnessing Python's renowned data science libraries. Filled with real-world examples and projects, the book covers various types of applications, and concludes by building real-world projects based on the concepts you have learned.
Table of Contents (16 chapters)

Name localization

Now that we are familiar with all types of comprehensions and generator expression, let's talk about name localization within them. Python 3.* localizes loop variables in all four forms of comprehensions: list, dict, set, and generator expressions. This behavior is therefore different from that of the for loop. Let's see a simple example to show all the cases:

# scopes.py
A = 100
ex1 = [A for A in range(5)]
print(A) # prints: 100

ex2 = list(A for A in range(5))
print(A) # prints: 100

ex3 = dict((A, 2 * A) for A in range(5))
print(A) # prints: 100

ex4 = set(A for A in range(5))
print(A) # prints: 100

s = 0
for A in range(5):
s += A
print(A) # prints: 4

In the preceding code, we declare a global name, A = 100, and then we exercise the four comprehensions: list, generator expression, dictionary, and set. None of them alter the global name, A. Conversely, you...