WEB Programmer - Python

Unit 3

Unit 3: The Python programming language

AIMS & OBJECTIVES

1) The purpose of this Unit is to enhance migrants’ basic soft skills and competencies, which are needed in today’s labor market and help them in their fist steps while in search for a job.

2) The main part of this presentation is the compilation of programmers with Python

3) The Unit aims at helping the reader to understand «generators in Python», «callback», «assert statement» and «loop».

LEARNING OUTCOMES

After completing the course you will attain a fundamental understanding of the Python programming language, object oriented programming base, essential skills to specialize on particular branches — machine learning, data science etc.

KEYWORDS

  • Python
  • most popular programming languages (human readable)
  • Guido van Rossum
  • machine learning
  • working with variables
  • evaluative logic
  • branching with a conditional operator
  • development of interfaces

TABLE OF CONTENTS

3.1. Branching with a conditional operator

if test-expression:

statement-to-execute when the test-expression is true

statement-to-execute when the test-expression is true

else:

statement-run-when-test-expression-false

statement-run-when-test-expression-false

After the if check block, the elif (elseif) keyword can also be used, which implies an alternative check and the execution of the corresponding instructions. This keyword must be bound to the word if, must be terminated with a colon, and its statements must also be indented. Then, to complete the alternate validation, a final else keyword can be added in case the validation fails. The syntax for the complete if: elif: else statement looks like this:

if test-expression-1:

statement-run-when-test-expression-1 is true

statement-run-when-test-expression-1 is true

elif test-expression-2:

statement-run-when-test-expression-2 is true

statement-run-when-test-expression-2 is true

 

else:

statement-run-when-the-test-expressions-false

 

statement-run-when-the-test-expressions-false

 

3.1. Branching with a conditional operator

  1. Start a new Python program by initializing a variable containing an integer value using user input.

num = int (input (‘Please Enter A Number:’))

  1. Now check the variable and print the appropriate result.

if num> 5:

print (‘Number Exceeds 5’)

elifnum <5:

print (‘Number is Less Than 5’)

else:

print (‘Number Is 5’)

  1. Then test the variable again, using the two expressions and outputting

 the result only if successful.

if num> 7 and num <9:

print (‘Number is 8’)

if num == 1 or num == 3:

print (‘Number Is 1 or 3’)

  1. Save the file in the working directory, open a command prompt and run the program – you will

see the result of the conditional branch

3.2. While loop

A loop is a piece of code in a program that automatically repeats itself. One complete execution of instructions within a loop is called an iteration or pass. The size of the loop is controlled by a check condition created inside the loop. The loop continues as long as the test expression is True, and ends at the point when it becomes False.

In Python programming, loops are created using the while keyword. It is followed by a test expression followed by a colon character. Below should be the instructions to be executed when the expression is checked successfully. Each line must have the same indentation from the line with the while keyword. This block must include in some place an instruction that changes the value of the test expression to the opposite, otherwise the loop will be infinite.

When working interactively, the indentation of Python code blocks must also be

Respected  – as in this example, which generates a sequence of Fibonacci numbers

using a while loop:

Loops can be nested one into another, and at each iteration of the outer loop, all

iterations of the inner loop have already been completed. For convenience, you can

initialize the so-called “counter” variable before each definition of the loop, setting

 it to its initial value and increasing it at each iteration, as well as including this

variable in the test expression. The loop will end if the expression fails.

3.2. While loop

Loops can be nested one into another, and at each iteration of the outer loop, all iterations of the inner loop have already been completed. For convenience, you can initialize the so-called “counter” variable before each definition of the loop, setting it to its initial value and increasing it at each iteration, as well as including this variable in the test expression. The loop will end if the expression fails.

  1. Start a new Python program by initializing a counter variable and defining an outer loop using that variable in the test expression.

I = 1

while i <4:

  1. Then add indented instructions to print out the counter value and increment its value at each iteration

of the loop.

print (‘\ nOuter Loop Iteration:’, i)

i + = 1

  1. Now (still indented) initialize the second counter variable and define the inner loop using that variable

in the test expression.

j = 1

while j <4:

  1. Finally, add further indented instructions to print the counter value and increment the counter value

with each iteration.

print (‘\ tInner Loop Iteration:’, j)

j + = 1

  1. Save the file in the working directory, open a command prompt and run the program – you will see the output at each iteration of the loop.

3.3. Exiting the loop

In order to forcibly exit the loop when some condition is met, use the break keyword. It is located inside the loop statement after the expression being tested. When the test returns True, the loop ends immediately and the program transfers control to the next instruction. For example, if break is in a nested inner loop, then control will be transferred to the next iteration of the outer loop.

  1. Start a new Python program with a statement that creates a loop that runs three times.

for i inrange (1, 4):

  1. Add an indented statement that creates a nested inner loop that runs three times as well.

for j inrange (1, 4):

  1. Now in the inner loop, with another indent, add the output of the counter values (both

the inner loop and the outer loop) for each pass of the inner loop.

print (‘Running i =’, i, ‘j =’, j)

  1. Save the file in the working directory, open a command line and run the program – you will see the

output of the counter values in each iteration of the loop

3.3. Exiting the loop

  1. Now add a break statement to the very beginning of the inner loop statement block to exit from it – then save the file and run the program again.

if i == 2 and j == 1:

print (‘Breaks inner loop at i = 2 j = 1′)

break

Sometimes you need to skip one of the loop iterations if some condition is met. To do this, use the continue keyword, which is located inside the block of loop statements and is preceded by a test expression. When the test returns True, this iteration ends and the program continues on to the next.

  1. Add the continue keyword to the very beginning of the inner loop block to skip the first iteration of the inner loop, then save the file and restart the program.

if i == 1 and j == 1:

print (‘Continues inner loop at i = 1 j = 1′)

continue

3.4. Scope of Variables

Most Python programs can contain a significant number of UDFs that are called as needed.

You can create a custom function using the def (definition) keyword, followed by the function name of your choice and parentheses. A programmer can choose any identifier as a name for his function, except for Python keywords and existing built-in function names. The function definition line must end with a colon character. The instructions to be executed when the function is called (the function body) are indented on the lines below. The syntax for defining a function is as follows:

def function-name ():

executable-expression

executable-expression

After the instructions in the function body are executed, the program transfers control to the point that follows the call to this function. This modularity principle, which isolates parts of a program that must be executed periodically, is very useful in programming.

3.4. Scope of Variables

Most Python programs can contain a significant number of UDFs that are called as needed.

You can create a custom function using the def (definition) keyword, followed by the function name of your choice and parentheses. A programmer can choose any identifier as a name for his function, except for Python keywords and existing built-in function names. The function definition line must end with a colon character. The instructions to be executed when the function is called (the function body) are indented on the lines below. The syntax for defining a function is as follows:

def function-name ():

executable-expression

executable-expression

After the instructions in the function body are executed, the program transfers control to the point that follows the call to this function. This modularity principle, which isolates parts of a program that must be executed periodically, is very useful in programming.

3.4. Scope of Variables

When creating custom functions, it is necessary to understand the principle of accessibility of variables in the program (scope of variables).

  • Variables created outside of a function can be accessed from statements inside functions — they are global.
  • Variables created inside functions cannot be accessed from the outside – they have local scope.

The limited availability of local variables means that variables with the same name can appear in different functions without any consequences.

If you want a local variable to be accessed from anywhere, you must first declare it using the global keyword followed by the variable name. After that, you can assign a value to it as many times as you like, and it will be available from anywhere in the program. In cases where two variables – global and local – have the same name, the function will use the local version.

3.4. Scope of Variables

  1. Start a new Python program by initializing a variable.

global_var = 1

  1. Now create a function named my_vars to display the value contained in the global variable.

defmy_vars ():

print (‘Global Variable:’, global_var)

  1. Then, using indentation, add a block to the function, where you initialize the local variable and print the value it contains.

local_var = 2

print (‘Local variable:’, local_var)

  1. Now add instructions to the function block, not forgetting the indentation, and force a global variable by assigning an initial value to it.

global inner_var

inner_var = 3

  1. Then add a call to this function to execute the instructions it contains.

my_vars ()

  1. Finally, add a statement to display the values contained in the global variable.

print (‘Coerced Global:’, inner_var)

  1. Save the file in the working directory, open a command line and run the program – you will see the results of the user-defined function that displays the values of variables.

3.4. Using a callback

Python has the ability to create unnamed (anonymous) functions using the lambda keyword. An anonymous function can contain only one expression, which must always return a value.

Unlike a regular function created with the def keyword, a lambda function returns an object that you can assign to a variable. Subsequently, it can be used to call the function (callback) anywhere in the program and execute the block of expressions that the function contains.

Thus, the lambda construct allows programmers to use an alternative syntax to create a function. For example:

defsquare (x):

return x ** 2

can be written in a more concise form like this:

square = lambdax: x ** 2

3.4. Using a callback

In both cases, the call to square (5) will return 25, passing the integer 5 as an argument to the function. Note that the argument after the lambda keyword is without parentheses and the expression in this function does not require the return keyword, since the lambda function returns a value anyway.

Because the lambda keyword offers an alternative way to create a function, it is often used to inline a function anywhere in your code. For example, callbacks are very often programmed as one-line lambda expressions embedded directly into the argument list instead of the usual def and call by name:

def function_1: executable-expressions

deffunction_2: executable-expressions

callbacks = [function_1, function_2]

This record can be expressed more succinctly: callbacks = [lambda: expression, lambda: expression]

3.4. Using a callback

  1. Start a new Python program by defining functions that return the passed argument raised to various powers.

def function_1 (x): return x ** 2

def function_2 (x): return x ** 3

def function_3 (x): return x ** 4

  1. Add a statement with a list of callbacks for each of the functions, referring to their names.

callbacks = [function_1, function_2, function_3]

  1. Now print the title and the result of passing values to each of the three named functions.

print (‘\ nNamed Functions:’)

for function in callbacks: print (‘Result:’, function (3))

  1. Next, add a statement to create a list of anonymous function calls that return the first

argument passed,  raised to various powers.

callbacks = \ [lambda x: x ** 2, lambda x: x ** 3, lambda x: x ** 4]

  1. Finally, display the title, and the result of passing the value of each of the three anonymous functions.

print (‘\ nAnonymous Functions:’)

for function in callbacks: print (‘Result:’, function (3))

  1. Save the file in your working directory, open a command prompt and run the program – you will see results that return regular and anonymous functions.

3.5. Generators in Python

Python has a special generator function that returns an object, not a value. At the same time, it retains the state of its last call and continues to work from the same point on the next call. Generator functions are defined in the same way as regular functions, but they additionally contain a “generator” instruction. It starts with the yield keyword and defines a generator object that is returned to the caller of the function.

When the generator instruction is executed, the state of the generator object is frozen and saved. An object returned by a generator instruction can be assigned to a variable. Using the built-in next () function, you can, by passing it the name of this variable, continue the execution of the function from the same freeze point.

Calling the generator again using the next () function continues execution of the function until an exception is thrown. It can be avoided by placing the generator instruction inside an infinite loop. For example, to generate values incrementally on each new call, write:

defincrementer ():                      i = 1                   while True:                     yield I                     i + = 1

inc = incrementer ()                  print (next (inc))               print (next (inc))                   print (next (inc))

These successive calls to the function will output the integer values 1, 2, and 3.

The most efficient way is to place the generator object in a loop that iterates through the values sequentially.

Generators

  1. Start a new Python program by defining a function that starts by initializing two variables with one integer.

deffibonacci_generator ():

a = b = 1

  1. Now add an infinite loop to the function body (not forgetting the indentation) to generate the sum of the two previous values.

while True:

yield a

a, b = b, a + b

  1. Assign the returned generator object to the variable.

fib = fibonacci_generator ()

  1. Finally, add a loop to sequentially call the generator function and output its value at each iteration.

for i in fib:

if i> 100:

break

else:

print (‘Generated:’, i)

  1. Save the file in the working directory, open a command prompt and run your program – you will see the incremental values generated in the loop.

3.6. Debugging with the assert statement

To find errors in your code while debugging a program, it is useful to use such a technique as commenting, when a # is added to the beginning of a line, and thus one or more lines become comments. As a result, the Python interpreter skips the execution of those commented lines, localizing the problem in the program. For example, when you suspect that there is some kind of error in the assignment of a value to a variable, then it can be excluded as follows:

# elem = elem / 2

If the program then runs without error, then it is obvious that the problem was in the commented out line. Another useful tool for debugging is the use of the assert statement. It tests the specified test expression against True or False and throws an AssertionError if the test fails. It can also include a descriptive message, using the following syntax:

assert test-expression, descriptive-message

3.6. Debugging with the assert statement

When the expression is not validated, the interpreter reports an AssertionError and aborts the program. If the check is successful, the assert statement does nothing and the program continues.

Using the assert mechanism is very useful for documenting your programs.

Assert or exception

At first glance, the operation of an assert statement might look similar to exception handling, but it is important to remember the differences.

  • Exceptions offer a way to handle errors that can occur at runtime.
  • The AssertionErrors tool provides programmers with the means to find errors while working on a program.

Assert statements are typically removed from final versions of a program after debugging is complete, while except statements remain in the program and handle runtime errors.

3.6. Debugging with the assert statement

  1. Start a new Python program by initializing a list of several string variables.

chars = [‘Alpha’, ‘Beta’, ‘Gamma’, ‘Delta’, ‘Epsilon’]

  1. Next, define a function that takes a single argument.

defdisplay (elem):

  1. Now add statements to the body of the function to test the passed argument value for an integer and display the list item with the appropriate ordinal. (Don’t forget the indentation of the phone function.)

assert type (elem) is int, ‘Argument Must Be Integer!’

print (‘List Element’, elem, ‘=’, chars [elem])

  1. Then initialize the variable with an integer value and call the function, passing the

value of this variable as an argument.

elem = 4

display (elem)

  1. Now change the value of the variable and call the function again, passing this

new value as an argument.

elem = elem / 2

display (elem)

  1. Save the file in your working directory, open a command prompt and run the program – you will see your message along with the AssertionError error.

SYNOPSIS

Python is a high-level (“human readable”) programming language that uses an interpreter to display results. Python contains an extensive standard library of tested code modules that can be easily incorporated into your own programs.

Developed by GuidovanRossum in the late 1980s and early 1990s at the National Research Institute of Mathematics and Computer Science in the Netherlands, Python is derived from many other languages, including C, C ++ and the Unix shell. Today Python is supported by the core team at the institute, although Guido vanRossum still plays an important role in determining the direction of the language. Code readability, making Python especially suitable for newbies to programming.

Because Python is focused on code readability, it often uses English keywords where other programming languages tend to use punctuation marks. A special difference is that Python uses indentation rather than keywords or punctuation marks to group statements in a block of code.

List of references

  • Eric Matthes, Python Crash Course. (No Starch Press, 2016)
  • Al Sweigart, Invent Your Own Computer Games with Python, 4th edition. (No Starch, 2017)
  • Dan Bader, Python Tricks: A Buffet of Awesome Python Features. (dbader.org, 2017)

Further reading

  • John Zelle, “Python Programming: An Introduction to Computer Science Paperback”. Franklin, Beedle&Associates Inc. www.fbeedle.com 3/09/10
  • Paul Barry, “Head First Python 2e: A Brain-Friendly Guide Paperback”. www.oreilly.com 16/12/16