Python Tutorial 3.5 Pdfeverfoundry



4. More Control Flow Tools — Python 3.5.4 documentation

Besides the while statement just introduced, Python knows the usualcontrol flow statements known from other languages, with some twists.

4.1. if Statements¶

3.5.4 Documentation » The Python Tutorial » In the following examples, input and output are distinguished by the presence or absence of prompts (. Before getting started, you may want to find out which IDEs and text editors are tailored to make Python editing easy, browse the list of introductory books, or look at code samples that you might find helpful. There is a list of tutorials suitable for experienced programmers on the BeginnersGuide/Tutorials page. There is also a list of resources in other languages which might be. Python 3 i About the Tutorial Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985 – 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL).

Perhaps the most well-known statement type is the if statement. Forexample:

There can be zero or more elif parts, and the else part isoptional. The keyword ‘elif‘ is short for ‘else if’, and is usefulto avoid excessive indentation. An if ... elif ...elif ... sequence is a substitute for the switch orcase statements found in other languages.

4.2. for Statements¶

The for statement in Python differs a bit from what you may be usedto in C or Pascal. Rather than always iterating over an arithmetic progressionof numbers (like in Pascal), or giving the user the ability to define both theiteration step and halting condition (as C), Python’s for statementiterates over the items of any sequence (a list or a string), in the order thatthey appear in the sequence. For example (no pun intended):

If you need to modify the sequence you are iterating over while inside the loop(for example to duplicate selected items), it is recommended that you firstmake a copy. Iterating over a sequence does not implicitly make a copy. Theslice notation makes this especially convenient:

4.3. The range() Function¶

If you do need to iterate over a sequence of numbers, the built-in functionrange() comes in handy. It generates arithmetic progressions:

The given end point is never part of the generated sequence; range(10) generates10 values, the legal indices for items of a sequence of length 10. Itis possible to let the range start at another number, or to specify a differentincrement (even negative; sometimes this is called the ‘step’):

To iterate over the indices of a sequence, you can combine range() andlen() as follows:

In most such cases, however, it is convenient to use the enumerate()function, see Looping Techniques.

A strange thing happens if you just print a range:

In many ways the object returned by range() behaves as if it is a list,but in fact it isn’t. It is an object which returns the successive items ofthe desired sequence when you iterate over it, but it doesn’t really makethe list, thus saving space.

We say such an object is iterable, that is, suitable as a target forfunctions and constructs that expect something from which they canobtain successive items until the supply is exhausted. We have seen thatthe for statement is such an iterator. The function list()is another; it creates lists from iterables:

Later we will see more functions that return iterables and take iterables as argument.

4.4. break and continue Statements, and else Clauses on Loops¶

The break statement, like in C, breaks out of the innermost enclosingfor or while loop.

Loop statements may have an else clause; it is executed when the loopterminates through exhaustion of the list (with for) or when thecondition becomes false (with while), but not when the loop isterminated by a break statement. This is exemplified by thefollowing loop, which searches for prime numbers:

(Yes, this is the correct code. Look closely: the else clause belongs tothe for loop, not the if statement.)

When used with a loop, the else clause has more in common with theelse clause of a try statement than it does that ofif statements: a try statement’s else clause runswhen no exception occurs, and a loop’s else clause runs when no breakoccurs. For more on the try statement and exceptions, seeHandling Exceptions.

The continue statement, also borrowed from C, continues with the nextiteration of the loop:

4.5. pass Statements¶

The pass statement does nothing. It can be used when a statement isrequired syntactically but the program requires no action. For example:

This is commonly used for creating minimal classes:

Python Tutorial 3.5 Pdfeverfoundry Cm

Another place pass can be used is as a place-holder for a function orconditional body when you are working on new code, allowing you to keep thinkingat a more abstract level. The pass is silently ignored:

4.6. Defining Functions¶

We can create a function that writes the Fibonacci series to an arbitraryboundary:

The keyword def introduces a function definition. It must befollowed by the function name and the parenthesized list of formal parameters.The statements that form the body of the function start at the next line, andmust be indented.

The first statement of the function body can optionally be a string literal;this string literal is the function’s documentation string, or docstring.(More about docstrings can be found in the section Documentation Strings.)There are tools which use docstrings to automatically produce online or printeddocumentation, or to let the user interactively browse through code; it’s goodpractice to include docstrings in code that you write, so make a habit of it.

The execution of a function introduces a new symbol table used for the localvariables of the function. More precisely, all variable assignments in afunction store the value in the local symbol table; whereas variable referencesfirst look in the local symbol table, then in the local symbol tables ofenclosing functions, then in the global symbol table, and finally in the tableof built-in names. Thus, global variables cannot be directly assigned a valuewithin a function (unless named in a global statement), although theymay be referenced.

The actual parameters (arguments) to a function call are introduced in the localsymbol table of the called function when it is called; thus, arguments arepassed using call by value (where the value is always an object reference,not the value of the object). [1] When a function calls another function, a newlocal symbol table is created for that call.

A function definition introduces the function name in the current symbol table.The value of the function name has a type that is recognized by the interpreteras a user-defined function. This value can be assigned to another name whichcan then also be used as a function. This serves as a general renamingmechanism:

Coming from other languages, you might object that fib is not a function buta procedure since it doesn’t return a value. In fact, even functions without areturn statement do return a value, albeit a rather boring one. Thisvalue is called None (it’s a built-in name). Writing the value None isnormally suppressed by the interpreter if it would be the only value written.You can see it if you really want to using print():

It is simple to write a function that returns a list of the numbers of theFibonacci series, instead of printing it:

This example, as usual, demonstrates some new Python features:

  • The return statement returns with a value from a function.return without an expression argument returns None. Falling offthe end of a function also returns None.
  • The statement result.append(a) calls a method of the list objectresult. A method is a function that ‘belongs’ to an object and is namedobj.methodname, where obj is some object (this may be an expression),and methodname is the name of a method that is defined by the object’s type.Different types define different methods. Methods of different types may havethe same name without causing ambiguity. (It is possible to define your ownobject types and methods, using classes, see Classes)The method append() shown in the example is defined for list objects; itadds a new element at the end of the list. In this example it is equivalent toresult=result+[a], but more efficient.

4.7. More on Defining Functions¶

It is also possible to define functions with a variable number of arguments.There are three forms, which can be combined.

4.7.1. Default Argument Values¶

The most useful form is to specify a default value for one or more arguments.This creates a function that can be called with fewer arguments than it isdefined to allow. For example:

This function can be called in several ways:

  • giving only the mandatory argument:ask_ok('Doyoureallywanttoquit?')
  • giving one of the optional arguments:ask_ok('OKtooverwritethefile?',2)
  • or even giving all arguments:ask_ok('OKtooverwritethefile?',2,'Comeon,onlyyesorno!')

This example also introduces the in keyword. This tests whether ornot a sequence contains a certain value.

The default values are evaluated at the point of function definition in thedefining scope, so that

will print 5.

Important warning: The default value is evaluated only once. This makes adifference when the default is a mutable object such as a list, dictionary, orinstances of most classes. For example, the following function accumulates thearguments passed to it on subsequent calls:

This will print

If you don’t want the default to be shared between subsequent calls, you canwrite the function like this instead:

4.7.2. Keyword Arguments¶

Functions can also be called using keyword argumentsof the form kwarg=value. For instance, the following function:

accepts one required argument (voltage) and three optional arguments(state, action, and type). This function can be called in anyof the following ways:

but all the following calls would be invalid:

In a function call, keyword arguments must follow positional arguments.All the keyword arguments passed must match one of the argumentsaccepted by the function (e.g. actor is not a valid argument for theparrot function), and their order is not important. This also includesnon-optional arguments (e.g. parrot(voltage=1000) is valid too).No argument may receive a value more than once.Here’s an example that fails due to this restriction:

When a final formal parameter of the form **name is present, it receives adictionary (see Mapping Types — dict) containing all keyword arguments except forthose corresponding to a formal parameter. This may be combined with a formalparameter of the form *name (described in the next subsection) whichreceives a tuple containing the positional arguments beyond the formal parameterlist. (*name must occur before **name.) For example, if we define afunction like this:

It could be called like this:

and of course it would print:

Note that the list of keyword argument names is created by sorting the resultof the keywords dictionary’s keys() method before printing its contents;if this is not done, the order in which the arguments are printed is undefined.

4.7.3. Arbitrary Argument Lists¶

Finally, the least frequently used option is to specify that a function can becalled with an arbitrary number of arguments. These arguments will be wrappedup in a tuple (see Tuples and Sequences). Before the variable number of arguments,zero or more normal arguments may occur.

Normally, these variadic arguments will be last in the list of formalparameters, because they scoop up all remaining input arguments that arepassed to the function. Any formal parameters which occur after the *argsparameter are ‘keyword-only’ arguments, meaning that they can only be used askeywords rather than positional arguments.

4.7.4. Unpacking Argument Lists¶

The reverse situation occurs when the arguments are already in a list or tuplebut need to be unpacked for a function call requiring separate positionalarguments. For instance, the built-in range() function expects separatestart and stop arguments. If they are not available separately, write thefunction call with the *-operator to unpack the arguments out of a listor tuple:

In the same fashion, dictionaries can deliver keyword arguments with the **-operator:

4.7.5. Lambda Expressions¶

Small anonymous functions can be created with the lambda keyword.This function returns the sum of its two arguments: lambdaa,b:a+b.Lambda functions can be used wherever function objects are required. They aresyntactically restricted to a single expression. Semantically, they are justsyntactic sugar for a normal function definition. Like nested functiondefinitions, lambda functions can reference variables from the containingscope:

The above example uses a lambda expression to return a function. Another useis to pass a small function as an argument:

Python Tutorial 3.5 Pdfeverfoundry Spells

4.7.6. Documentation Strings¶

Here are some conventions about the content and formatting of documentationstrings.

The first line should always be a short, concise summary of the object’spurpose. For brevity, it should not explicitly state the object’s name or type,since these are available by other means (except if the name happens to be averb describing a function’s operation). This line should begin with a capitalletter and end with a period.

If there are more lines in the documentation string, the second line should beblank, visually separating the summary from the rest of the description. Thefollowing lines should be one or more paragraphs describing the object’s callingconventions, its side effects, etc.

The Python parser does not strip indentation from multi-line string literals inPython, so tools that process documentation have to strip indentation ifdesired. This is done using the following convention. The first non-blank lineafter the first line of the string determines the amount of indentation forthe entire documentation string. (We can’t use the first line since it isgenerally adjacent to the string’s opening quotes so its indentation is notapparent in the string literal.) Whitespace “equivalent” to this indentation isthen stripped from the start of all lines of the string. Lines that areindented less should not occur, but if they occur all their leading whitespaceshould be stripped. Equivalence of whitespace should be tested after expansionof tabs (to 8 spaces, normally).

Here is an example of a multi-line docstring:

4.7.7. Function Annotations¶

Function annotations are completely optional metadatainformation about the types used by user-defined functions (see PEP 484for more information).

Annotations are stored in the __annotations__ attribute of the functionas a dictionary and have no effect on any other part of the function. Parameterannotations are defined by a colon after the parameter name, followed by anexpression evaluating to the value of the annotation. Return annotations aredefined by a literal ->, followed by an expression, between the parameterlist and the colon denoting the end of the def statement. Thefollowing example has a positional argument, a keyword argument, and the returnvalue annotated:

4.8. Intermezzo: Coding Style¶

Now that you are about to write longer, more complex pieces of Python, it is agood time to talk about coding style. Most languages can be written (or moreconcise, formatted) in different styles; some are more readable than others.Making it easy for others to read your code is always a good idea, and adoptinga nice coding style helps tremendously for that.

For Python, PEP 8 has emerged as the style guide that most projects adhere to;it promotes a very readable and eye-pleasing coding style. Every Pythondeveloper should read it at some point; here are the most important pointsextracted for you:

Python Tutorial 3.5 Pdfeverfoundry Edition

  • Use 4-space indentation, and no tabs.

    4 spaces are a good compromise between small indentation (allows greaternesting depth) and large indentation (easier to read). Tabs introduceconfusion, and are best left out.

  • Wrap lines so that they don’t exceed 79 characters.

    This helps users with small displays and makes it possible to have severalcode files side-by-side on larger displays.

  • Use blank lines to separate functions and classes, and larger blocks ofcode inside functions.

  • When possible, put comments on a line of their own.

  • Use docstrings.

  • Use spaces around operators and after commas, but not directly insidebracketing constructs: a=f(1,2)+g(3,4).

  • Name your classes and functions consistently; the convention is to useCamelCase for classes and lower_case_with_underscores for functionsand methods. Always use self as the name for the first method argument(see A First Look at Classes for more on classes and methods).

  • Don’t use fancy encodings if your code is meant to be used in internationalenvironments. Python’s default, UTF-8, or even plain ASCII work best in anycase.

  • Likewise, don’t use non-ASCII characters in identifiers if there is only theslightest chance people speaking a different language will read or maintainthe code.

Footnotes

[1]Actually, call by object reference would be a better description,since if a mutable object is passed, the caller will see any changes thecallee makes to it (items inserted into a list).
© Copyright 2001-2017, Python Software Foundation.
The Python Software Foundation is a non-profit corporation. Please donate.
Last updated on Aug 07, 2017. Found a bug?
Created using Sphinx 1.4.4.

In the following examples, input and output are distinguished by the presence orabsence of prompts (>>> and ): to repeat the example, you must typeeverything after the prompt, when the prompt appears; lines that do not beginwith a prompt are output from the interpreter. Note that a secondary prompt on aline by itself in an example means you must type a blank line; this is used toend a multi-line command.

Many of the examples in this manual, even those entered at the interactiveprompt, include comments. Comments in Python start with the hash character,#, and extend to the end of the physical line. A comment may appear at thestart of a line or following whitespace or code, but not within a stringliteral. A hash character within a string literal is just a hash character.Since comments are to clarify code and are not interpreted by Python, they maybe omitted when typing in examples.

Some examples:

3.1. Using Python as a Calculator¶

Let’s try some simple Python commands. Start the interpreter and wait for theprimary prompt, >>>. (It shouldn’t take long.)

3.1.1. Numbers¶

The interpreter acts as a simple calculator: you can type an expression at itand it will write the value. Expression syntax is straightforward: theoperators +, -, * and / work just like in most other languages(for example, Pascal or C); parentheses (()) can be used for grouping.For example:

The integer numbers (e.g. 2, 4, 20) have type int,the ones with a fractional part (e.g. 5.0, 1.6) have typefloat. We will see more about numeric types later in the tutorial.

Division (/) always returns a float. To do floor division andget an integer result (discarding any fractional result) you can use the //operator; to calculate the remainder you can use %:

With Python, it is possible to use the ** operator to calculate powers 1:

The equal sign (=) is used to assign a value to a variable. Afterwards, noresult is displayed before the next interactive prompt:

If a variable is not “defined” (assigned a value), trying to use it willgive you an error:

There is full support for floating point; operators with mixed type operandsconvert the integer operand to floating point:

In interactive mode, the last printed expression is assigned to the variable_. This means that when you are using Python as a desk calculator, it issomewhat easier to continue calculations, for example:

This variable should be treated as read-only by the user. Don’t explicitlyassign a value to it — you would create an independent local variable with thesame name masking the built-in variable with its magic behavior.

In addition to int and float, Python supports other types ofnumbers, such as Decimal and Fraction.Python also has built-in support for complex numbers,and uses the j or J suffix to indicate the imaginary part(e.g. 3+5j).

3.1.2. Strings¶

Besides numbers, Python can also manipulate strings, which can be expressedin several ways. They can be enclosed in single quotes ('...') ordouble quotes ('...') with the same result 2. can be usedto escape quotes:

In the interactive interpreter, the output string is enclosed in quotes andspecial characters are escaped with backslashes. While this might sometimeslook different from the input (the enclosing quotes could change), the twostrings are equivalent. The string is enclosed in double quotes ifthe string contains a single quote and no double quotes, otherwise it isenclosed in single quotes. The print() function produces a morereadable output, by omitting the enclosing quotes and by printing escapedand special characters:

If you don’t want characters prefaced by to be interpreted asspecial characters, you can use raw strings by adding an r beforethe first quote:

String literals can span multiple lines. One way is using triple-quotes:''...'' or ''...''. End of lines are automaticallyincluded in the string, but it’s possible to prevent this by adding a atthe end of the line. The following example:

produces the following output (note that the initial newline is not included):

Strings can be concatenated (glued together) with the + operator, andrepeated with *:

Two or more string literals (i.e. the ones enclosed between quotes) nextto each other are automatically concatenated.

This feature is particularly useful when you want to break long strings:

This only works with two literals though, not with variables or expressions:

If you want to concatenate variables or a variable and a literal, use +:

Strings can be indexed (subscripted), with the first character having index 0.There is no separate character type; a character is simply a string of sizeone:

Indices may also be negative numbers, to start counting from the right:

Note that since -0 is the same as 0, negative indices start from -1.

In addition to indexing, slicing is also supported. While indexing is usedto obtain individual characters, slicing allows you to obtain substring:

Note how the start is always included, and the end always excluded. Thismakes sure that s[:i]+s[i:] is always equal to s:

Slice indices have useful defaults; an omitted first index defaults to zero, anomitted second index defaults to the size of the string being sliced.

One way to remember how slices work is to think of the indices as pointingbetween characters, with the left edge of the first character numbered 0.Then the right edge of the last character of a string of n characters hasindex n, for example:

The first row of numbers gives the position of the indices 0…6 in the string;the second row gives the corresponding negative indices. The slice from i toj consists of all characters between the edges labeled i and j,respectively.

For non-negative indices, the length of a slice is the difference of theindices, if both are within bounds. For example, the length of word[1:3] is2.

Attempting to use an index that is too large will result in an error:

However, out of range slice indexes are handled gracefully when used forslicing:

Python strings cannot be changed — they are immutable.Therefore, assigning to an indexed position in the string results in an error:

If you need a different string, you should create a new one:

The built-in function len() returns the length of a string:

See also

Text Sequence Type — str

Strings are examples of sequence types, and support the commonoperations supported by such types.

String Methods

Strings support a large number of methods forbasic transformations and searching.

Formatted string literals

String literals that have embedded expressions.

Format String Syntax

Information about string formatting with str.format().

printf-style String Formatting

The old formatting operations invoked when strings arethe left operand of the % operator are described in more detail here.

3.1.3. Lists¶

Python knows a number of compound data types, used to group together othervalues. The most versatile is the list, which can be written as a list ofcomma-separated values (items) between square brackets. Lists might containitems of different types, but usually the items all have the same type.

Like strings (and all other built-in sequence types), lists can beindexed and sliced:

Python tutorial 3.5 pdfeverfoundry installer

All slice operations return a new list containing the requested elements. Thismeans that the following slice returns ashallow copy of the list:

Lists also support operations like concatenation:

Unlike strings, which are immutable, lists are a mutabletype, i.e. it is possible to change their content:

You can also add new items at the end of the list, by usingthe append()method (we will see more about methods later):

Assignment to slices is also possible, and this can even change the size of thelist or clear it entirely:

The built-in function len() also applies to lists:

It is possible to nest lists (create lists containing other lists), forexample:

3.2. First Steps Towards Programming¶

Of course, we can use Python for more complicated tasks than adding two and twotogether. For instance, we can write an initial sub-sequence of theFibonacci seriesas follows:

This example introduces several new features.

  • The first line contains a multiple assignment: the variables a and bsimultaneously get the new values 0 and 1. On the last line this is used again,demonstrating that the expressions on the right-hand side are all evaluatedfirst before any of the assignments take place. The right-hand side expressionsare evaluated from the left to the right.

  • The while loop executes as long as the condition (here: a<10)remains true. In Python, like in C, any non-zero integer value is true; zero isfalse. The condition may also be a string or list value, in fact any sequence;anything with a non-zero length is true, empty sequences are false. The testused in the example is a simple comparison. The standard comparison operatorsare written the same as in C: < (less than), > (greater than), (equal to), <= (less than or equal to), >= (greater than or equal to)and != (not equal to).

  • The body of the loop is indented: indentation is Python’s way of groupingstatements. At the interactive prompt, you have to type a tab or space(s) foreach indented line. In practice you will prepare more complicated inputfor Python with a text editor; all decent text editors have an auto-indentfacility. When a compound statement is entered interactively, it must befollowed by a blank line to indicate completion (since the parser cannotguess when you have typed the last line). Note that each line within a basicblock must be indented by the same amount.

  • The print() function writes the value of the argument(s) it is given.It differs from just writing the expression you want to write (as we didearlier in the calculator examples) in the way it handles multiple arguments,floating point quantities, and strings. Strings are printed without quotes,and a space is inserted between items, so you can format things nicely, likethis:

    The keyword argument end can be used to avoid the newline after the output,or end the output with a different string:

Footnotes

1

Since ** has higher precedence than -, -3**2 will beinterpreted as -(3**2) and thus result in -9. To avoid thisand get 9, you can use (-3)**2.

2

Unlike other languages, special characters such as n have thesame meaning with both single ('...') and double ('...') quotes.The only difference between the two is that within single quotes you don’tneed to escape ' (but you have to escape ') and vice versa.