Graphics Reference
In-Depth Information
>>> my_variable = 10
>>> type(my_variable)
<class 'int'>
>>> my_variable = "Hello!"
>>> type(my_variable)
<class 'str'>
Variables must be given a value before they can be accessed in any way, even in conditionals. Undefined
variables in your code will result in a NameError in Python.
The difference between global and local variables will become clearer when the topic of defining functions
is addressed. In short, variables that are initialized inside the definition of a function are local to that function,
meaning that they cannot be accessed directly from outside the function in which they were defined. Global
variables, on the other hand, are defined outside all functions and can be accessed from within any function.
You'll read more about this later in this chapter.
Control Flow
Control refers to the order in which a sequence of programming instructions is followed; repetition, iteration,
and conditionality are all part of the control flow of a program. A core set of statements is used in Python to
determine control flow. These include the for and if/else statements.
Indentation, not Brackets
One of the most immediately noticeable differences between Python and other common programming languages
is the way it identifies control structures. Most languages do this with some kind of brackets. C, Perl, and Java,
among others, use curly brackets to delimit control structures. Python, on the other hand, does not use brackets at
all, but rather groups levels of embedding in control structures according to the left-side indentation of the code.
This results in a visual immediacy for the code; control issues tend to pop out with Python code. However, it
means that the interpreter is unforgiving with regard to white-space inconsistency. It also means that editing
Python in more than one editor whose tab settings are different may result in errors. Some editors have features
that enable you to visualize white space and distinguish between spaces and tabs. If you think you might be using
more than one editor, be sure to check that the settings are consistent across editors.
The most common and simplest way to create a for loop is to iterate through a list, which is done like this:
>>> my_list = ['a','b','c']
>>> for item in my_list:
... print(item)
...
a
b
c
TorunthisinthePythonConsolewindow,enteronelineatatimeofyourcode.Besuretoindentthecontent
ofthe for loop.Whenyou'veenteredthecomplete program(afterthe print( item ) line)pressEntertwice.
Inthisexampleanewvariable, item ,isinitializedattheoutsetofthe for loop.Astheloopiteratesthrough
the list, this variable takes the value of each element of the list one by one. Note that there is no iteration on the
index of the list items. In general, such explicit index iteration is not necessary. However, if you want to iterate
Search WWH ::




Custom Search