WEB Programmer - Python

Unit 2

Unit 2: 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 «arithmetic operations», «prioritization», «data type conversion» and «lists».

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

2.1. Error correction

Errors can occur when executing programs written in Python. There are three main types of errors that should be distinguished so that they are easier to correct later.

  • Syntax error – occurs when the interpreter processes code that does not conform to the rules of the Python language, such as missing quotes around a string variable. The interpreter stops and reports an error without further execution of the program.
  • Execution error – occurs during program execution. For example, when a variable cannot be recognized due to a type mismatch. The interpreter starts the program, stops at the error, and reports the nature of the error as an exception.
  • Logical error (semantic) – occurs when the program does not behave as intended. For example, when the order of actions in a calculated expression is not defined. The interpreter runs the program and does not report an error.

With syntax and runtime errors corrected, everything is pretty clear, since the interpreter tells where the error occurred and indicates the nature of its origin. But logical errors require a detailed study of the code.

2.1. Error correction

  1. Start a text editor and add an expression to output the string, omitting the closing quotation marks.

print (‘Python in easy steps)

  1. Save the file in your working directory, open a command line and run the program – you will see that the interpreter reports a syntax error and indicates its position in the code.
  2. Add a quotation mark before the closing parenthesis to end the line, save the
    file, and start the program again. You will see that the error has been fixed.
  3. Add a quotation mark before the closing parenthesis to end the line, save the
    file, and start the program again. You will see that the error has been fixed.

2.1. Error correction

  1. We correct the name of the variable in accordance with its description, save the file, start the program again – and we see that the error has been fixed.
  2. Now start a new program, initialize the variable, then try to output the value of the expression without explicitly specifying the order. You will see unexpected results.

num = 3

print (num * 8 + 4)

          7. Add a parenthesis to make the expression 3 * (8 + 4). Save the file and run the program again. You will see the expected value of 36 as a result of the semantic error correction.

2.2. Arithmetic operations

The operators for addition, subtraction, multiplication and division shouldn’t be too complicated. They work as you probably expected. However, it should be noted that when using multiple operators, it is recommended to group expressions using parentheses – the operations within the parentheses are performed first. For example, the expression

a = b * c – d% e / f may be confusing in terms of the order of computation. But it is allowed to clarify it by writing it in the form:

a = (b * c) – ((d% e) / f)

The% (modulo) operator divides one number by another and returns the remainder of the division. It is very useful for determining whether a number is even or odd.

The // (integer division) operator works the same as normal division, /, but discards the result after the decimal point.

The ** (exponentiation) operator raises the first operand to the power of the second operand.

2.2. Arithmetic operations

  1. Start a new program by initializing two variables with integer values.

a = 8

b = 2

  1. 2. Then print the result of the addition of the variables.

print (‘Addition: \ t’, a, ‘+’, b, ‘=’, a + b)

  1. 3. Now display the result of the subtraction of the variables.

print (‘Subtraction: \ t’, a, ‘-‘, b, ‘=’, a – b)

  1. 4. Then display the result of the multiplication of the variables.

print (‘Multiplication: \ t’, a, ‘x’, b, ‘=’, a * b)

  1. 5. Display the result of dividing both floating point and integer

variables.

print (‘Division: \ t’, a, ‘÷’, b, ‘=’, a / b)

print (‘Floor Division: \ t’, a, ‘÷’, b, ‘=’, a // b)

  1. Then output the remainder after dividing one value by another.

print (‘Modulus: \ t’, a, ‘%’, b, ‘=’, a% b)

  1. 7. Finally, display the result of raising the first operand to the power of the second.

print (‘Exponent: \ t’, a, ‘² =’, a ** b, sep = ”)

  1. 8. Save the file in your working directory, open a command line and run the program

– you will see the result of arithmetic operations.

2.3. Assigning values

The operators used in Python programming to assign values to variables are listed in the table below. All of them, with the exception of the simple assignment, =, are shorthand forms for longer expressions. For clarity, the table shows their equivalents.

In the table above, the variable named

 a is assigned the value that is contained

 in the variable named b, and thus the

new value will be stored in variable a.

The + = operator is useful for adding some

value to the existing one stored in the variable a.

The + = operator first adds to the value contained in the variable b the value contained in the variable a, and then assigns the result to the value of the variable a.

All other operators work on the same principle – first they perform an arithmetic operation between two operands, and then assign the value of this result to the first variable.

When using the% = operator, the first operand a is divided by the second operand b, and then the remainder of that division is assigned to a.

2.3. Assigning values

1. Start a new Python program that initializes two variables by assigning integer values to them, and print those assigned values.

a = 8

b = 4

print (‘Assign Values: \ t \ t’, ‘a =’, a, ‘\ tb =’, b)

2. Now assign a new value to the first variable and display it.

a + = b

print (‘Add & Assign: \ t \ t’, ‘a =’, a, ‘(8 + = 4)’)

3. Do the same as in the previous step, but now using subtraction and multiplication.

a – = b

print (‘Subtract & Assign: \ t’, ‘a =’, a, ‘(12 – 4)’)

a * = b

print (‘Multiply & Assign: \ t’, ‘a =’, a, ‘(8 x 4)’)

4. Finally, using division and assignment, get the new value for the first variable and

 print the result, then use modulo and assignment to print the result.

a / = b

print (‘Divide & Assign: \ t’, ‘a =’, a, ‘(32 ÷ 4)’)

a% = b

print (‘Modulus & Assign: \ t’, ‘a =’, a, ‘(8% 4)’)

5. Save the file in your working directory, then open a command line and run

 

the program – you will see the result of the assignment operation.

2.4. Comparison of quantities

Operators commonly used in Python programming to compare two operands are shown in the table below.

Operator              Checked condition

= =                     Equality

! =                   Inequality

>                            More

<                               Less

> =      Greater than or equal

<=          Less than or equal

The equality operator, ==, compares the two operands and returns True if their values are equal, otherwise it returns False. Moreover, if the operands are numeric values, and they are the same, then they are equal, and if symbols, then their ASCII codes are compared.

2.4. Comparison of quantities

The inequality operator,! =, Conversely, returns True if both operands are not equal, using the same rule as the equality operator, otherwise returning False.

The equality and inequality operators are useful for performing conditional branching in a program by comparing the values of two variables.

The greater than operator,>, compares the two operands and returns True if the first is greater than the second, and vice versa, returns False if the first is equal to or less than the second.

The less than operator, <, does the same thing, but returns True if the first operator is less than. These two operators are often used to check the value of the counter of operations in a loop.

Adding an equal, =, operator after a greater than,>, or less than, <operator causes them to return True if the values of the operands are the same.

2.4. Comparison of quantities

  1. Start a new Python program by initializing five variables that will be used for comparison.

nil = 0

num = 0

max = 1

cap = ‘A’

low = ‘a‘

  1. 2. Now add instructions to display the results of numeric and symbolic comparisons using the equal operator.

print (‘Equality: \ t’, nil, ‘==’, num, nil == num)

print (‘Equality: \ t’, cap, ‘==’, low, cap == low)

  1. 3. Now add a statement to output the comparison result using the inequality operator.

print (‘Inequality: \ t’, nil, ‘! =’, max, nil! = max)

  1. Now let’s add instructions to display the results of the greater than and less than operators.

print (‘Greater: \ t’, nil, ‘>’, max, nil> max)

print (‘Lesser: \ t’, nil, ‘<‘, max, nil <max)

  1. Finally, add an instruction to display the results of the comparison operators,

“more than equal”, “less than equal.”

print (‘More Or Equal: \ t’, nil, ‘> =’, num, nil> = num)

print (‘Less or Equal: \ t’, max, ‘<=’, num, max <= num)

  1. Save the file in your working directory, open a command line and run the

 program – you will see the results of the comparison operators.

2.5. Evaluative logic

Logical operators used in Python programming are shown in the table below.

Operator                   Operation

and              Logical AND

or              Logical “OR”

not              Logical NOT

Logical operators operate on operands that have a Boolean value, that is, True or False, or values that convert to True or False.

The logical AND operator, and, evaluates two operands and returns True only if both operands are themselves True, otherwise it returns False. This operator is usually used in conditional branching, when the direction of the program is determined by checking two conditions – if both are true, the program goes in a certain direction, otherwise – in the other.

Unlike the and operator, which requires both operands to be True, the logical OR operator, or, evaluates two operands and returns True if at least one of them itself returns True. Otherwise, the or operator will return False. This is useful when programming certain actions when one of the two checked conditions is met.

2.5. Evaluative logic

  1. Start a new Python program by initializing two boolean variables for evaluation.

a = True

b = False

  1. Now add instructions to display the results of the logical AND operator.

print (‘AND Logic:’)

print (‘a and a =’, a and a)

print (‘a and b =’, a and b)

print (‘b and b =’, b and b)

  1. Now add statements to display the output of the logical-OR statement.

print (‘\ nOR Logic:’)

print (‘a or a =’, a or a)

print (‘a or b =’, a or b)

print (‘b or b =’, b or b)

  1. Finally, add instructions for displaying the results of “logical NOT”.

print (‘\ nNOT Logic:’)

print (‘a =’, a, ‘\ tnot a =’, not a)

print (‘b =’, b, ‘\ tnot b =’, not b)

  1. Save the file in your working directory, open a command prompt and run the program. You will see the results of the logical operations.

2.6. Prioritization

  1. Start a new Python program by initializing three variables with integer values for subsequent priority comparison.

a = 2

b = 4

c = 8

  1. Now add instructions for displaying the results of calculations with a default order of actions and explicitly specifying the priority of the addition operation.

print (‘\ nDefault Order: \ t’, a, ‘*’, c, ‘+’, b, ‘=’, a * c + b)

print (‘Forced Order: \ t’, a, ‘* (‘, c, ‘+’, b, ‘) =’, a * (c + b))

  1. Then add instructions to display the result of the calculation, with a default order of actions and an explicit indication of the priority of the subtraction operation.

print (‘\ nDefault Order: \ t’, c, ‘//’, b, ‘-‘, a, ‘=’, c // b – a)

print (‘Forced Order: \ t’, c, ‘// (‘, b, ‘-‘, a, ‘) =’, c // (b – a))

  1. Finally, add instructions for displaying the results of the calculations in the default order of

operations, and then adding the priority of the add operation before dividing by the module, and

also before calculating the degree.

print (‘\ nDefault Order: \ t’, c, ‘%’, a, ‘+’, b, ‘=’, c% a + b)

print (‘Forced Order: \ t’, c, ‘% (‘, a, ‘+’, b, ‘) =’, c% (a + b))

print (‘\ nDefault Order: \ t’, c, ‘**’, a, ‘+’, b, ‘=’, c ** a + b)

print (‘Forced Order: \ t’, c, ‘** (‘, a, ‘+’, b, ‘) =’, c ** (a + b))

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

 the results of the statements with the default order and with the changed order of precedence.

2.7. Data type conversion

Python’s built-in data type conversion functions return a new object

representing the converted value. The most commonly used of these

functions are presented below.

Function                           Description

int (x)                     Converts x to an integer

float (x)                      Converts x to float

str (x)           Converts x to string representation

chr (x)              Converts integer x to character

unichr (x)           Converts an integer x to a Unicode character

ord (x)    Converts the character x to its corresponding integer

hex (x)      Converts an integer x to a hexadecimal string

oct (x)         Converts an integer x to an octal string

2.7. Data type conversion

  1. Start a new Python program by initializing two variables with numeric values from user input.

a = input (‘Enter A Number:’)

b = input (‘Now Enter Another Number:’)

  1. Now add instructions for adding the two variables and for printing the result, the corresponding data type, and the result of the string concatenation.

sum = a + b

print (‘\ nData Type sum:’, sum, type (sum))

  1. Then add instructions for adding the two given values and displaying the result,

 as well as the corresponding data type – you will see the integer value of the sum.

sum = int (a) + int (b)

print (‘Data Type sum:’, sum, type (sum))

  1. Add instructions to cast the variable and display the result and its data type.

You will get a floating point output of the total.

sum = float (sum)

print (‘Data Type sum:’, sum, type (sum))

  1. Finally add instructions for casting the integer representation of the value and for printing the result and its data type — you get a character string. sum = chr (int (sum))

print (‘Data Type sum:’, sum, type (sum))

  1. Save the file in the working directory, open a command prompt and run the program. You will see the result of casting different data types.

2.8. Lists

In Python, any variable must be assigned an initial value (it must be initialized), otherwise the interpreter will issue an error message (the variable is not defined).

You can initialize multiple variables with the same initial value in one statement using a sequence of assignment statements. For example, to assign the same value to three variables at the same time, we write:

a = b = c = 10

On the other hand, several variables can be initialized with different initial values in a single assignment statement, using commas as separators. For example, to simultaneously assign different values to three variables, we write:

a, b, c = 1, 2, 3

Unlike regular variables, which contain a single item of data, Python has a so-called list, which can store multiple items of data. The data is stored sequentially in the “items” of the list, which are indexed numerically, starting at zero. That is, the first value is stored in element 0, the second in element 1, and so on. The list is created in the same way as another variable, but initialized by assignment as a comma-separated list of values enclosed in square brackets, for example, creating a list named nums looks like this:

nums = [0, 1, 2, 3, 4, 5]

2.8. Lists

  1. Start a new Python program by initializing a three-element list containing string values.

quarter = [‘January’, ‘February’, ‘March’]

  1. Then add instructions to separately display the values contained in each list item.

print (‘First Month:’, quarter [0])

print (‘Second Month:’, quarter [1])

print (‘Third Month:’, quarter [2])

  1. Now add a statement to create a multidimensional list of two elements, each of which is itself a list of three elements containing integer values.

coords = [[1, 2, 3], [4, 5, 6]]

  1. Then add instructions to display the values contained in two specific elements of the inner list.

print (‘\ nTop Left 0,0:’, coords [0] [0])

print (‘Bottom Right 1,2:’, coords [1] [2])

  1. Finally, add a statement to output only one character of the string variable.

print (‘\ nSecond Month First Letter:’, quarter [1] [0])

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

see the output of the list item values.

2.9. Working with lists

Lists containing multiple items are widely used in Python programming. To work with them, there are many so-called methods that can be accessed through dot notation.

List method                                          Description

list.append (x)                  Adds element x to the end of the list

list.extend (L)           Adds all elements of list L to the end of the list

list.insert (i, x)        Inserts element x at the position before index i in the list

list.remove (x)              Removes the first element x from the list

list.pop (i)                  Removes the element at index i and returns it

list.index (x)               Returns the index of the first element x in the list

list.count (x)             Returns the number of occurrences of x in the list

list.sort ()                             Sorts list items in ascending

list.reverse ()                         Reverse the order of items

2.9. Working with lists

Python has a useful function len (L) that returns the size of a list L, that is, the total number of elements in the list. Like the index () and count () methods, in this case the return value is numeric and cannot be directly concatenated with text to output a text string.

However, using the str (n) function, numeric values can be converted to a string representation so that they can later be used for addition to other strings. Similarly, using the str (L) function, you can return the string representation of the entire list. In both cases, remember that the original versions remain unchanged, and the returned view is only a copy of them.

Individual list items can be removed by specifying their index as a parameter to the del (i) function. You can delete a single element by specifying its position number i, or a set of elements using the i1: i2 notation, which specifies the range of indices of the first and last elements to be deleted. This means that all elements with indices from i1 to i2 will be deleted, excluding the last one

2.9. Working with lists

  1. Start a new Python program by initializing two lists of three elements each containing string values.

basket = [‘Apple’, ‘Bun’, ‘Cola’]

crate = [‘Egg’, ‘Fig’, ‘Grape’]

  1. Now add instructions to display the contents of the first list and its length.

print (‘Basket List:’, basket)

print (‘Basket Elements:’, len (basket))

  1. Write instructions for adding an item to the list, displaying all items, then deleting the last item, and re-displaying all items.

basket.append (‘Damson’)

print (‘Appended:’, basket)

print (‘Last Item Removed:’, basket.pop ())

print (‘Basket List:’, basket)

  1. Finally, add instructions for expanding the first list with items in the second, displaying all

 items in the first list, then deleting the items and displaying items in the first list again.

basket.extend (crate)

print (‘Extended:’, basket)

del basket [1]

print (‘Item Removed:’, basket)

del basket [1: 3]

print (‘Slice Removed:’, basket)

  1. Save the file in your working directory, open a command prompt and run the program. You will see the result of processing the lists.

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