Python
Python
And while you may know the python as a large snake, the name of the Python programming
language comes from an old BBC television comedy sketch series called Monty Python's Flying
Circus.
Guido van Rossum used the "C" programming language to implement the very first version
of his language and this decision is still in force. All Pythons coming from the PSF are written
in the "C" language.
Cython
Another Python family member is Cython.
Cython is one of a possible number of solutions to the most painful of Python's trait - the lack of
efficiency. Large and complex mathematical calculations may be easily coded in Python
Jython
Another version of Python is called Jython.
It's a logo of the PyPy - a Python within a Python. In other words, it represents a Python
environment written in Python-like language named RPython (Restricted Python). It is actually a
subset of Python.
an editor which will support you in writing the code (it should have some special features,
not available in simple tools); this dedicated editor will give you more than the standard OS
equipment;
a console in which you can launch your newly written code and stop it forcibly when it gets
out of control;
a tool named a debugger, able to launch your code step by step and allowing you to inspect
it at each moment of execution.
Navigate through your OS menus, find IDLE somewhere under Python 3.x and launch it. This is
what you should see:
How to write and run your very first program
It is now time to write and run your first Python 3 program. It will be very simple, for now.
The first step is to create a new source file and fill it with code. Click File in the IDLE’s menu and
choose New file.
print("Hello!")
A new window appears – it says that the interpreter has encountered an EOF (end-of-file) although
(in its opinion) the code should contain some more text.
print("Hello!"
print("Hello!")
Remove one letter from the word print. Run the code by pressing F5. As you can see, Python is
not able to recognize the error.
rint("Hello")
Run this program
print("Hello!")
The print() function
Look at the line of code below:
print("Hello, World!")
As you can see, the string is delimited with quotes - in fact, the quotes make the string - they cut
out a part of the code and assign a different meaning to it.
Example
Console
Example
print()
Console
The empty print() invocation is not as empty as you may have expected - it does output an
empty line
Example
print()
Console
\n
Example
Console
The itsy bitsy spider climbed up the waterspout.
Example
print("My name is", "Python.")
print("Monty Python.")
Console
My name is Python.
Monty Python.
Example
The print() function has two keyword arguments that you can use for your purposes. The first of
them is named end.
Console
My-name-is-Monty-Python.
Console
My_name_is*Monty*Python.*
Exercise
print("Programming","Essentials","in")
print("Python")
Console
Programming Essentials in
Python
Expected output
Programming***Essentials***in...Python
Solution
Print(“programming”,Essentials”, “in”,
sep=”***”,end=”… ”)
Print(“Python”)
Example
print(" *")
print(" * *")
print(" * *")
print(" * *")
print("*** ***")
print(" * *")
print(" * *")
print(" *****")
Console
*
* *
* *
* *
*** ***
* *
* *
*****
Key takeaways
2. Built-in functions, contrary to user-defined functions, are always available and don't have to be
imported. Python 3.7.1 comes with 69 built-in functions. You can find their full list provided in
alphabetical order in the Python Standard Library.
3. To call a function (function invocation), you need to use the function name followed by
parentheses. You can pass arguments into a function by placing them inside the parentheses. You
must separate arguments with a comma, e.g., print("Hello,", "world!") . An
"empty" print() function outputs an empty line to the screen.
4. Python strings are delimited with quotes, e.g., "I am a string" , or 'I am a string, too' .
6. In Python strings the backslash ( \ ) is a special character which announces that the next
character has a different meaning, e.g., \n (the newline character) starts a new output line.
7. Positional arguments are the ones whose meaning is dictated by their position, e.g., the second
argument is outputted after the first, the third is outputted after the second, etc.
8. Keyword arguments are the ones whose meaning is not dictated by their location, but by a
special word (keyword) used to identify them.
9. The end and sep parameters can be used for formatting the output of the print() function.
The sep parameter specifies the separator between the outputted arguments (e.g., print("H",
"E", "L", "L", "O", sep="-") , whereas the end parameter specifies what to print at the end
of the print statement.
Python Literals
Console
2
2
The print() function presents them in exactly the same way - this example is obvious, as
their human-readable representation is also the same. Internally, in the computer's memory,
these two values are stored in completely different ways - the string exists as just a string - a
series of letters.
The number is converted into machine representation (a set of bits). The print() function
is able to show them both in a form readable to humans.
Integers
we can write this number either like this: 11111111, or like that: 11_111_111.
*Python 3.6 has introduced underscores in numeric literals, allowing for placing single underscores
between digits and after base specifiers for improved readability.
And how do we code negative numbers in Python? As usual - by adding a minus. You can write: -
11111111 , or -11_111_111 .
Positive numbers do not need to be preceded by the plus sign, but it's permissible, if you wish to do
it. The following lines describe the same number: +11111111 and 11_11_11_11 .
print(0o123)
0x123 is a hexadecimal number with a (decimal) value equal to 291. The print() function can
manage these values too. Try this:
print(0x123)
Floats
Whenever we use a term like two and a half or minus zero point four, we think of numbers which the
computer considers floating-point numbers:
2.5
If you want to use just a value of two and a half, you should write it as shown above. Note once
again - there is a point between 2 and 5 - not a comma.-0.4
0.4
.4
4.0
4
4.0
You may think that they are exactly the same, but Python sees them in a completely different way.
Take, for example, the speed of light, expressed in meters per second. Written directly it would look
like this: 300000000.
To avoid writing out so many zeros, physics textbooks use an abbreviated form, which you have
probably already seen: 3 x 108.
In Python, the same effect is achieved in a slightly different way - take a look:
3E8
The letter E (you can also use the lower-case letter e - it comes from the word exponent) is a
concise record of the phrase times ten to the power of.
Note:
Coding floats
A physical constant called Planck's constant (and denoted as h), according to the textbooks, has the
value of: 6.62607 x 10-34.
If you would like to use it in a program, you should write it this way:
6.62607E-34
For example, let's say you've decided to use the following float literal:
0.0000000000000000000001
print(0.0000000000000000000001)
1e-22
Exercise
''
""
Code
print("''")
print('""')
Boolean values
A programmer writes a program, and the program asks questions. Python executes the program,
and provides the answers. The program must be able to react according to the received answers.
Fortunately, computers know only two kinds of answers:
True
False
You cannot change anything - you have to take these symbols as they are, including case-
sensitivity.
Expected output
"I'm"
""learning""
"""Python"""
print('”I\'m happy.”')
print(‘””learning””’)
print(‘”””Python”””’)
Key takeaways
1. Literals are notations for representing some fixed values in code. Python has various types of
literals - for example, a literal can be a number (numeric literals, e.g., 123), or a string (string literals,
e.g., "I am a literal.").
2. The binary system is a system of numbers that employs 2 as the base. Therefore, a binary
number is made up of 0s and 1s only, e.g., 1010 is 10 in decimal.
Octal and hexadecimal numeration systems, similarly, employ 8 and 16 as their bases respectively.
The hexadecimal system uses the decimal numbers and six extra letters.
3. Integers (or simply ints) are one of the numerical types supported by Python. They are numbers
written without a fractional component, e.g., 256, or -1 (negative integers).
4. Floating-point numbers (or simply floats) are another one of the numerical types supported by
Python. They are numbers that contain (or are able to contain) a fractional component, e.g., 1.27.
5. To encode an apostrophe or a quote inside a string you can either use the escape character,
e.g., 'I\'m happy.', or open and close the string using an opposite set of symbols to the ones you
wish to encode, e.g., "I'm happy." to encode an apostrophe, and 'He said "Python", not
"typhoon"' to encode a (double) quote.
6. Boolean values are the two constant objects True and False used to represent truth values (in
numeric contexts 1 is True, while 0 is False.
Exercise 1
Exercise 2
The first is a string, the second is a numerical literal (a float), the third is a numerical literal (an
integer), and the fourth is a boolean literal.
Python as a calculator
print(2+2)
Basic operators
An operator is a symbol of the programming language, which is able to operate on the values.
We'll begin with the operators which are associated with the most widely recognizable arithmetic
operations:
+, -, *, /, //, %, **
Arithmetic operators: exponentiation
A ** (double asterisk) sign is an exponentiation (power) operator. Its left argument is the base, its
right, the exponent.
Classical mathematics prefers notation with superscripts, just like this: 23. Pure text editors don't
accept that, so Python uses ** instead, e.g., 2 ** 3 .
print(2 ** 3)
print(2 ** 3.)
print(2. ** 3)
print(2. ** 3.)
Console
8
8.0
8.0
8.0
when both ** arguments are integers, the result is an integer, too;
when at least one ** argument is a float, the result is a float, too.
Console
6
6.0
6.0
6.0
print(6 / 3)
print(6 / 3.)
print(6. / 3)
print(6. / 3.)
Console
2.0
2.0
2.0
2.0
its result lacks the fractional part - it's absent (for integers), or is always equal to zero (for
floats); this means that the results are always rounded;
it conforms to the integer vs. float rule.
Example
print(6 // 3)
print(6 // 3.)
print(6. // 3)
print(6. // 3.)
Console
2
2.0
2.0
2.0
As you can see, integer by integer division gives an integer result. All other cases produce floats.
Example
print(6 // 4)
print(6. // 4)
Console
1.0
The result of integer division is always rounded to the nearest integer value
that is less than the real (not rounded) result.
Example
print(-6 // 4)
print(6. // -4)
Console
-2
-2.0
The result is two negative twos. The real (not rounded) result is -1.5 in both cases. However, the
results are the subjects of rounding. The rounding goes toward the lesser integer value, and the
lesser integer value is -2, hence: -2 and -2.0.
Example
print(14 % 4)
Console
2
14 // 4 gives 3 → this is the integer quotient;
3 * 4 gives 12 → as a result of quotient and divisor multiplication;
14 - 12 gives 2 → this is the remainder.
Example
print(12 % 4.5)
Console
3.0
Operators: addition
The addition operator is the + (plus) sign, which is fully in line with mathematical standards.
Example
print(-4 + 4)
print(-4. + 8)
Console
0
4.0
Example
print(-4 - 4)
print(4. - 8)
print(-1.1)
Console
-8
-4.0
-1.1
You surely remember that you should first multiply 3 by 5 and, keeping the 15 in your memory, then
add it to 2, thus getting the result of 17.
Most of Python's operators have left-sided binding, which means that the calculation of the
expression is conducted from left to right.
This simple example will show you how it works. Take a look:
print(9 % 6 % 2)
There are two possible ways of evaluating this expression:
The result should be 1. This operator has left-sided binding. But there's one interesting exception.
print(2 ** 2 ** 3)
2 ** 2 → 4; 4 ** 3 → 64
2 ** 3 → 8; 2 ** 8 → 256
256
The result clearly shows that the exponentiation operator uses right-sided binding.
List of priorities
Priority Operator
1 +, - unary
2 **
3 *, /, %
4 +, - binary
Example
print(2 * 3 % 5)
console
1
Operators and parentheses
Of course, you're always allowed to use parentheses, which can change the natural order of a
calculation.
Example
print((5 * ((25 % 13) + 100) / (2 * 13)) // 2)
Console
10
Key takeaways
1. An expression is a combination of values (or variables, operators, calls to functions - you will
learn about them soon) which evaluates to a value, e.g., 1 + 2.
2. Operators are special symbols or keywords which are able to operate on the values and perform
(mathematical) operations, e.g., the * operator multiplies two values: x * y.
Exercise 1
Exercise 2
-0.5 0.5 0 -1
Exercise 3
-2 2 512
You already know that you can do some arithmetic operations with these numbers: add, subtract, etc
It offers special "boxes" (containers) for that purpose, and these boxes are called variables
a name;
a value (the content of the container)
If you want to give a name to a variable, you must follow some strict rules:
the name of the variable must be composed of upper-case or lower-case letters, digits, and
the character _ (underscore)
the name of the variable must begin with a letter;
the underscore character is a letter;
upper- and lower-case letters are treated as different (a little differently than in the real world
- Alice and ALICE are the same first names, but in Python they are two different variable
names, and consequently, two different variables);
the name of the variable must not be any of Python's reserved words (the keywords - we'll
explain more about this soon).
Keywords
Take a look at the list of words that play a very special role in every Python program.
They are called keywords or (more precisely) reserved keywords. They are reserved because you
mustn't use them as names: neither for your variables, nor functions, nor any other named entities
you want to create.
The meaning of the reserved word is predefined, and mustn't be changed in any way.
Creating variables
What can you put inside a variable?
Anything.
var = 1
print(var)
It consists of two simple instructions:
The first of them creates a variable named var, and assigns a literal with an integer value
equal to 1.
The second prints the value of the newly created variable to the console.
Using variables
You're allowed to use as many variable declarations as you need to achieve your goal, like this:
var = 1
account_balance = 1000.0
client_name = 'John Doe'
print(var, account_balance, client_name)
print(var)
var = 1
print(Var)
Example
var = "3.7.1"
print("Python version: " + var)
Console
Example
var = 1
print(var)
var = var + 1
print(var)
console:
1
2
Example
var = 100
var = 200 + 300
print(var)
Console
500
500 - why? Well, first, the var variable is created and assigned a value of 100. Then, the same
variable is assigned a new value: the result of adding 200 to 300, which is 500.
The square of the hypotenuse is equal to the sum of the squares of the other two sides.
The following code evaluates the length of the hypotenuse (i.e., the longest side of a right-angled
triangle, the one opposite of the right angle) using the Pythagorean theorem:
a = 3.0
b = 4.0
c = (a ** 2 + b ** 2) ** 0.5
print("c =", c)
Console
C = 5.0
Note: we need to make use of the ** operator to evaluate the square root as:
√ (x) = x(½)
and
c = √ a2 + b2
Exercise
Objectives
becoming familiar with the concept of storing and working with different data types in Python;
experimenting with Python code.
Scenario
Here is a short story:
Once upon a time in Appleland, John had three apples, Mary had five apples, and Adam had six
apples. They were all very happy and lived for a long time. End of story.
mary = 5
adam = 6
print("John Apples = " ,john , "\n" "Mary Apples = " , mary,"\n" "Adam = ",adam)
Console
John Apples = 3
Mary Apples = 5
Adam = 6
Total Apples = 14
Shortcut operators
It's time for the next set of operators that make a developer's life easier.
Very often, we want to use one and the same variable both to the right and left sides of
the = operator.
x = x * 2
x *= 2
sheep = sheep + 1
sheep += 1
If op is a two-argument operator (this is a very important condition) and the operator is used in the
following context:
Take a look at the examples below. Make sure you understand them all.
i = i + 2 * j ⇒ i += 2 * j
x = x ** 2 ⇒ x **= 2
Objectives
becoming familiar with the concept of, and working with, variables;
performing basic computations and conversions;
experimenting with Python code.
Scenario
Miles and kilometers are units of length or distance.
Bearing in mind that 1 mile is equal to approximately 1.61 kilometers, complete the program in the
editor so that it converts:
miles to kilometers;
kilometers to miles.
Do not change anything in the existing code. Write your code in the places indicated by ### . Test
your program with the data we've provided in the source code.
round() function. Its job is to round the outputted result to the number of decimal places specified
in the parentheses, and return a float
Exercise
kilometers = 12.25
miles = 7.38
miles_to_kilometers = ###
kilometers_to_miles = ###
print(miles, "miles is",
round(miles_to_kilometers, 2), "kilometers")
print(kilometers, "kilometers is",
round(kilometers_to_miles, 2), "miles")
Solution
kilometers = 12.25
miles = 7.38
Console
7.38 miles is 11.88 kilometers
12.25 kilometers is 7.61 miles
Exercise
Objectives
becoming familiar with the concept of numbers, operators, and arithmetic operations in
Python;
performing basic calculations.
Scenario
Take a look at the code in the editor: it reads a float value, puts it into a variable named x , and
prints the value of a variable named y . Your task is to complete the code in order to evaluate the
following expression:
3x3 - 2x2 + 3x - 1
The result should be assigned to y .
Remember that classical algebraic notation likes to omit the multiplication operator - you need to use
it explicitly. Note how we change data type to make sure that x is of type float .
Keep your code clean and readable, and test it using the data we've provided, each time assigning it
to the x variable (by hardcoding it). Don't be discouraged by any initial failures. Be persistent and
inquisitive.
Test Data
Sample input
x = 0
x = 1
x = -1
Expected Output
y = -1.0
y = 3.0
y = -9.0
Problem
x = # hardcode your test data here
x = float(x)
# write your code here
print("y =", y)
Solution
x= 0
x = float(x)
y = (3 * (x ** 3) - 2 * ( x** 2 ) + (3 * x) -1)
print("y =", y)
console
y = -1.0
y = 3.0
y = -9.0
Key takeaways
1. A variable is a named location reserved to store values in the memory. A variable is created or
initialized automatically when you assign a value to it for the first time. (2.1.4.1)
2. Each variable must have a unique name - an identifier. A legal identifier name must be a non-
empty sequence of characters, must begin with the underscore( _), or a letter, and it cannot be a
Python keyword. The first character may be followed by underscores, letters, and digits. Identifiers in
Python are case-sensitive. (2.1.4.1)
5. You can assign new values to already existing variables using the assignment operator or one of
the compound operators, e.g.: (2.1.4.5)
var = 2
print(var)
var = 3
print(var)
var += 1
print(var)
6. You can combine text and variables using the + operator, and use the print() function to output
strings and variables, e.g.: (2.1.4.4)
var = "007"
Exercise 1
var = 2
var = 3
print(var)
Console
3
Exercise 2
my_var
m
101
averylongvariablename
m101
m 101
Del
Del
Console
my_var
m
101 # incorrect (starts with a digit)
averylongvariablename
m101
m 101 # incorrect (contains a space)
Del
del # incorrect (is a keyword)
Exercise 3
a = '1'
b = "1"
print(a + b)
Console
11
Exercise 4
a = 6
b = 3
a /= 2 * b
print(a)
Console
1.0
2*b=6
a = 6 → 6 / 6 = 1.0
A remark inserted into the program, which is omitted at runtime, is called a comment.
In Python, a comment is a piece of text that begins with a # (hash) sign and extends to the end of
the line.
If you want a comment that spans several lines, you have to put a hash in front of them all.
Objectives
becoming familiar with the concept of comments in Python;
using and not using comments;
replacing comments with code;
experimenting with Python code.
#this program computes the number of seconds in a given number of hours
a = 2 # number of hours
#here we should also print "Goodbye", but a programmer didn't have time to
write any code
#this is the end of the program that computes the number of seconds in 3 hour
Key takeaways
1. Comments can be used to leave additional information in code. They are omitted at
runtime.
2. . If you want to place a comment that spans several lines, you need to place # in
front of them al
Exercise 1
# print("String #1")
print("String #2")
Console
String #2
Exercise 2
# This is
a multiline
comment. #
print("Hello!")
Console
The input() function is able to read data entered by the user and to return the same data to the
running program.
The program can manipulate the data, making the code truly interactive.
Example
print("Tell me anything...")
anything = input()
the input() function is invoked without arguments; the function will switch the console to input
mode;
Modified example
anything = input("Tell me anything...")
print("Hmm...", anything, "...Really?")
Example
Console
Enter a number: 66
Traceback (most recent call last):
File "main.py", line 2, in <module>
something = anything ** 2.0
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'float'
Type casting
Python offers two simple functions to specify a type of data and solve this
problem - here they are: int() and float().
Example
Console
Enter a number: 6
6.0 to the power of 2 is 36.0
Example
leg_a = float(input("Input first leg length: "))
leg_b = float(input("Input second leg length: "))
hypo = (leg_a**2 + leg_b**2) ** .5
print("Hypotenuse length is", hypo)
Console
Input first leg length: 5
Input second leg length: 10
Hypotenuse length is 11.180339887498949
Example
fnam = input("May I have your first name, please? ")
lnam = input("May I have your last name, please? ")
print("Thank you.")
print("\nYour name is " + fnam + " " + lnam + ".")
Console
May I have your first name, please? Amit
May I have your last name, please? kumar
Thank you.
Replication
The * (asterisk) sign, when applied to a string and number (or a number and string, as it remains
commutative in this position) becomes a replication
operator:
string * number
number * string
It replicates the string the same number of times specified by the number.
For example:
"James" * 3 gives "JamesJamesJames"
3 * "an" gives "ananan"
5 * "2" (or "2" * 5) gives "22222" (not 10!)
print (“abc” * 0)
This simple program "draws" a rectangle, making use of an old operator ( +) in a new role:
print("+" + "-" * 10 + "+")
print(("|" + " " * 10 + "|\n") * 5, end="")
print("+"+ "-" * 10 + "+")
Console
Type conversion: str()
You already know how to use the int() and float() functions to convert a string into a number.
Console
Example
# input a float value for variable a here
# input a float value for variable b here
Scenario
Your task is to prepare a simple code able to evaluate the end time of a period of time, given as a
number of minutes (it could be arbitrarily large). The start time is given as a pair of hours (0..23) and
minutes (0..59). The result has to be printed to the console.
For example, if an event starts at 12:17 and lasts 59 minutes, it will end at 13:16.
Don't worry about any imperfections in your code - it's okay if it accepts an invalid time - the most
important thing is that the code produce valid results for valid input data.
Test your code carefully. Hint: using the % operator may be the key to success.
Test Data
Sample input
:12
17
59
Sample input
:23
58
642
Sample input:
2939
Example
# total hours
print(hr,":",rmin)
# put your code here
Key takeaways
3. When the input() function is called, the program's flow is stopped, the prompt symbol keeps
blinking (it prompts the user to take action when the console is switched to input mode) until the user
has entered an input and/or pressed the Enter key.
Example
name = input("Enter your name: ")
print("Hello, " + name + ". Nice to meet you!")
print("THE END.")
Example
Example
multiply (* - replication) strings, e.g.:
print(x * "5")
Console
55
Exercise 2
print(type(x))
Console
<class 'str'>
In this module
Boolean values;
if-elif-else instructions;
the while and for loops;
flow control;
logical and bitwise operations;
lists and arrays.
Example
2 == 2
Example
2 == 2.
This question is not as easy as the first one. Luckily, Python is able to convert the integer value into
its real equivalent, and consequently, the answer is True .
Example
1 == 2
This should be easy. The answer will be (or rather, always is) False.
Example
Console
True
print(var == 0)
Console
False
Example
Console
False
Example
var = 1 # assigning 1 to var
print(var != 0)
Console
True
You can also ask a comparison question using the > (greater than) operator.
black_sheep > white_sheep # greater than
If we want to find out whether or not we have to wear a warm hat, we ask the following question:
As you've probably already guessed, the operators used in this case are:
the < (less than) operator and its non-strict sibling: <= (less than or equal
to).
What can you do with the answer (i.e., the result of a comparison operation) you get from the
computer?
Priority Operator
1 +, - unary
2 **
3 *, /, //, %
4 +, - binary
5 <, <=, >, >=
6 ==, !=
Scenario
Using one of the comparison operators in Python, write a simple two-line program that takes the
parameter n as input, which is an integer, and prints False if n is less than 100 , and True if n is
greater than or equal to 100 .
Example
ans = n>=100
print(ans)
Console
type nummber+123
True
if true_or_not:
do_this_if_true
This conditional statement consists of the following, strictly necessary, elements in this and this
order only:
the if keyword;
one or more white spaces;
an expression (a question or an answer) whose value will be interpreted solely in terms
of True (when its value is non-zero) and False (when it is equal to zero);
a colon followed by a newline;
an indented instruction or set of instructions (at least one instruction is absolutely required);
the indentation may be achieved in two ways - by inserting a particular number of spaces
(the recommendation is to use four spaces of indentation), or by using the tab character;
note: if there is more than one instruction in the indented part, the indentation should be the
same in all lines; even though it may look the same if you use tabs mixed with spaces, it's
important to make all indentations exactly the same - Python 3 does not allow mixing
spaces and tabs for indentation.
As you can see, having lunch is not a conditional activity and doesn't depend on the
weather.
Knowing what conditions influence our behavior, and assuming that we have the
parameterless functions go_for_a_walk() and have_lunch(), we can write the following
snippet:
if the_weather_is_good:
go_for_a_walk()
have_lunch()
We've said that conditionally executed statements have to be indented. This creates a very
legible structure, clearly demonstrating all possible execution paths in the code.
As you can see, making a bed, taking a shower and falling asleep and dreaming are all executed
conditionally - when sheep_counter reaches the desired limit.
Example
k = int(input ("type a number :"))
if k >= 120:
print("greater than 120")
print("number is " , k)
print("last statement on true condition")
print("out side the indent wether condition is true of false2")
Console
type a number :150
greater than 120
number is 150
last statement on true condition
out side the indent whether condition is true of
false2
We can say, for example: If the weather is good, we will go for a walk, otherwise we will go to a
theater.
Now we know what we'll do if the conditions are met, and we know what we'll do if not everything
goes our way. In other words, we have a "Plan B".
if true_or_false_condition:
perform_if_condition_true
else:
perform_if_condition_false
Thus, there is a new word: else - this is a keyword.
if the_weather_is_good:
go_for_a_walk()
else:
go_to_a_theater()
have_lunch()
If the weather is good, we'll go for a walk. Otherwise, we'll go to a theatre. No matter if the weather is
good or bad, we'll have lunch afterwards (after the walk or after going to the theatre).
Everything we've said about indentation works in the same manner inside the else branch:
if the_weather_is_good:
go_for_a_walk()
have_fun()
else:
go_to_a_theater()
enjoy_the_movie()
have_lunch()
Nested if-else statements
Now let's discuss two special cases of the conditional statement.
First, consider the case where the instruction placed after the if is another if .
Example
if the_weather_is_good:
if nice_restaurant_is_found:
have_lunch()
else:
eat_a_sandwich()
else:
if tickets_are_available:
go_to_the_theater()
else:
go_shopping()
Example
weather = input("is weather good : <y/n>")
if weather == "y":
resturent = input("is resturent found : <y/n>")
if resturent == "y":
print("Have a lunch !")
else:
print("Eat sandwich !")
else:
ticket = input("are the tickets availabe : <y/n>")
if ticket == "y":
print("go to theater :")
else:
print("go for shopping :")
Console
is weather good : <y/n>n
are the tickets availabe : <y/n>n
go for shopping :
Here are two important points:
this use of the if statement is known as nesting; remember that
every else refers to the if which lies at the same indentation level; you need
to know this to determine how the ifs and elses pair up;
consider how the indentation improves readability, and makes the code easier
to understand and trace.
The elif statement
The second special case introduces another new Python keyword: elif. As you probably suspect, it's
a shorter form of else if.
elif is used to check more than just one condition, and to stop when the first statement which is
true is found.
if the_weather_is_good
go_for_a_walk()
elif tickets_are_available:
go_to_the_theater()
elif table_is_available:
go_for_lunch()
else:
play_chess_at_home()
Notice again how the indentation improves the readability of the code.
Console
enter number1 :10
enter number2 :20
large number is : 20
Example
# read two numbers
number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
number1 = int(input("enter number1 :"))
number2 = int(input("enter number2 :"))
number3 = int(input("enter number3 :"))
if number1 > number2:
if number1 > number3:
large_number = number1
print("large number :",number1)
else:
print("large number :",number3)
else:
if number2 > number3:
large_number = number2
print("large number :", number2 )
else:
large_number = number3
print("large number :",number3)
print("Large number is :" , large_number)
Console
enter number1 :80
enter number2 :110
enter number3 :6
large number : 110
Large number is : 110
Example
a = int(input("Enter value of a :"))
b = int(input("Enter value of b :"))
c = int(input("Enter value of c :"))
big = a
if b > big :
big = b
if c > big:
big = c
print("bigger number is ", big)
Console
Enter value of a :5
Enter value of b :30
Enter value of c :6
bigger number is 30
largest_number = number1
Example
Sample input: spathiphyllum
Sample input: pelargonium
Sample input: Spathiphyllum
Solution
Example
The most important tax, called the Personal Income Tax (PIT for short) had
to be paid once a year, and was evaluated using the following rule:
if the citizen's income was not higher than 85,528 thalers, the tax was
equal to 18% of the income minus 556 thalers and 2 cents (this was
the so-called tax relief)
if the income was higher than this amount, the tax was equal to
14,839 thalers and 2 cents, plus 32% of the surplus over 85,528
thalers.
Solution
Test Data
Sample input: 10000
Sample input: 100000
Sample input: 1000
Sample input: -100
Key takeaways
1. The comparison (or the so-called relational) operators are used to
compare values. The table below illustrates how the comparison operators
work, assuming that x = 0, y = 1, and z = 0:
2. When you want to execute some code only if a certain condition is met, you can use
a conditional statement:
Exercise 1
x = 5
y = 10
z = 8
print(x > y)
print(y > z)
Exercise 2
x, y, z = 5, 10, 8
print(x > z)
print((y - 5) == x)
Exercise 3
x, y, z = 5, 10, 8
x, y, z = z, y, x
print(x > z)
print((y - 5) == x)
Exercise 4
x = 10
if x == 10:
print(x == 10)
if x > 5:
print(x > 5)
if x < 10:
print(x < 10)
else:
print("else")
Exercise 5
x = "1"
if x == 1:
print("one")
elif x == "1":
if int(x) > 1:
print("two")
elif int(x) < 1:
print("three")
else:
print("four")
if int(x) == 1:
print("five")
else:
print("six")
Exercise 6
x = 1
y = 1.0
z = "1"
if x == y:
print("one")
if y == int(z):
print("two")
elif x == y:
print("three")
else:
print("four")
do it
Note that this record also declares that if there is nothing to do, nothing at all will happen.
instruction
The semantic difference is more important: when the condition is met, if performs its
statements only once; while repeats the execution as long as the condition evaluates to True .
Note: all the rules regarding indentation are applicable here, too. We'll show you this soon.
while conditional_expression:
instruction_one
instruction_two
instruction_three
:
:
instruction_n
An infinite loop
An infinite loop, also called an endless loop, is a sequence of instructions in a program which
repeat indefinitely (loop endlessly.)
while True:
This loop will infinitely print "I'm stuck inside a loop." on the screen.
Example
With comments
largest_number = -999999999
largest_number = number
ln = -99999999
while n != -1:
if n > ln :
ln = n
largest number is 54
Example
# A program that reads a sequence of numbers
# and counts how many numbers are even and how many are odd.
# The program terminates when zero is entered.
odd_numbers = 0
even_numbers = 0
# 0 terminates execution
while number != 0:
# check if the number is odd
if number % 2 == 1:
# increase the odd_numbers counter
odd_numbers += 1
else:
# increase the even_numbers counter
even_numbers += 1
# read the next number
number = int(input("Enter a number or type 0 to stop: "))
# print results
print("Odd numbers count:", odd_numbers)
Example
on = 0 #odd number
en = 0 #even number
if n%2 == 1 :
else:
Console
enter number or 0 :0
Try to recall how Python interprets the truth of a condition, and note that
these two forms are equivalent:
counter = 5
while counter != 0:
print("Inside the loop.", counter)
counter -= 1
print("Outside the loop.", counter)
Problem
Objectives
Scenario
A junior magician has picked a secret number. He has hidden it in a variable
named secret_number. He wants everyone who run his program to play the Guess
the secret number game, and guess what number he has picked for them. Those who
don't guess the number will be stuck in an endless loop forever! Unfortunately, he does
not know how to complete the code.
Your task is to help the magician complete the code in the editor in such a way so that
the code:
Solution
secret_number = 777
no = int(input ("\n Guess the secret number game :"))
while secret_number != no:
print("\n HA HA ! You're Stuck in my loop !")
no = int(input ("\n Guess the secret number game :"))
print("Well done, muggle! You are free now.")
print(
"""
+================================+
| Welcome to my game, muggle! |
| Enter an integer number |
| and guess what number I've |
| picked for you. |
| So, what is the secret number? |
+================================+
""")
-------------------------------------------------------------------------------------------------
-----------------------------------------
while loop
i = 0
while i < 100:
# do_something()
i += 1
for loop
for i in range(100):
# do_something()
Pass
There are some new elements. Let us tell you about them:
the for keyword opens the for loop; note - there's no condition after it; you don't have to
think about conditions, as they're checked internally, without any intervention;
any variable after the for keyword is the control variable of the loop; it counts the loop's
turns, and does it automatically;
the in keyword introduces a syntax element describing the range of possible values being
assigned to the control variable;
the range() function (this is a very special function) is responsible for generating all the
desired values of the control variable; in our example, the function will create (we can even
say that it will feed the loop with) subsequent values from the following set: 0, 1, 2 .. 97, 98,
99; note: in this case, the range() function starts its job from 0 and finishes it one step (one
integer number) before the value of its argument;
note the pass keyword inside the loop body - it does nothing at all; it's an empty
instruction - we put it here because the for loop's syntax demands at least one instruction
inside the body (by the way - if, elif, else and while express the same thing)
Example
for i in range(10):
print("The value of i is currently", i)
The range() function invocation may be equipped with two arguments, not just one:
In this case, the first argument determines the initial (first) value of the control variable.
The last argument shows the first value the control variable will not be assigned.
The third argument is an increment - it's a value added to control the variable at every loop turn (as
you may suspect, the default value of the increment is 1).
Example
Console
The value of i is currently 2
The value of i is currently 5
2 (starting number) → 5 ( 2 increment by 3 equals 5 - the number is within the range from 2 to 8)
→ 8 ( 5 increment by 3 equals 8 - the number is not within the range from 2 to 8, because the stop
parameter is not included in the sequence of numbers generated by the function.)
Example
This means that the range()'s second argument must be greater than the first.
short program whose task is to write some of the first powers of two:
Example
pow = 1
for exp in range(8):
print("2 to the power of", exp, "is", pow)
pow *= 2
Console
expor power is 1
expor power is 2
expor power is 4
expor power is 8
expor power is 16
expor power is 32
expor power is 64
expor power is 128
The exp variable is used as a control variable for the loop, and indicates the current value of
the exponent. The exponentiation itself is replaced by multiplying by two. Since 2 0 is equal to
1, then 2 × 1 is equal to 21, 2 × 21 is equal to 22, and so on. What is the greatest exponent for
which our program still prints the result?
Example
for i in range(9):
if i > 3:
break
print(i)
import time
for i in range(5):
print("Mississippi")
time.sleep(1)
# Write a for loop that counts to five.
# Body of the loop - print the loop iteration number and the word "Mississippi".
# Body of the loop - use: time.sleep(1)
Console
Mississippi
Mississippi
Mississippi
Mississippi
Mississippi
The break and continue statements
Example
# break - example
# continue - example
Console
The break instruction:
Inside the loop. 1
Inside the loop. 2
Outside the loop.
(cnt = 0
while cnt != 10:
if cnt == 3 :
cnt += 1
continue
print("cnt", cnt)
cnt += 1 )
Example continue
largestNumber = -99999999
counter = 0
if counter:
print("The largest number is", largestNumber)
else:
print("You haven't entered any number.")
Console
cnt = 0
cnt = 1
cnt = 2
Killed
-----------------------------------------------------------------------
for i in range(5):
if i == 3:
continue
print("i =",i)
print("out side the loop")
Console
i=0
i=1
i=2
i=4
out side the loop
----------------------------------------------------------------------
i=0
while i <= 5:
if i == 3:
i=i+1
continue
print("i = ",i)
i=i+1
print("outside the while loop")
Console
i= 0
i= 1
i= 2
i= 4
i= 5
Problem
The break statement is used to exit/terminate a loop.
Design a program that uses a while loop and continuously asks the user to enter a word unless the
user enters "chupacabra" as the secret exit word, in which case the message "You've
successfully left the loop." should be printed to the screen, and the loop should terminate.
---------------------------------------------------------------------------------
Problem
Objectives
Familiarize the student with:
Your task here is very special: you must design a vowel eater! Write a program that uses:
a for loop;
the concept of conditional execution (if-elif-else)
the continue statement.
Test your program with the data we've provided for you.
Solution
# Prompt the user to enter a word
# and assign it to the userWord variable.
userWord = input("Enter Name :")
userWord = userWord.upper()
for letter in userWord:
if letter == "A":
continue
elif letter == "E":
continue
elif letter == "I":
continue
elif letter == "O":
continue
elif letter == "U":
continue
print(letter)
# Complete the body of the for loop.
Console
Enter Name: Gregory
G
R
G
R
Y
Same Problem
Test data
Sample input: Gregory
Expected output:
GRGRY
wordWithoutVovels = ""
Example
i = 5
while i < 5:
print(i)
i += 1
else:
print("else:", i)
Console
1
2
3
4
5
else:5
Console
else: 10
Run and test the program, and check whether the else branch has been
executed or not.
for i in range(5):
print(i)
else:
print("else:", i)
Console
0
1
2
3
4
else 4
Example
for i in range(3,14,2):
print(i)
Console
3
5
7
9
11
13
Example
i = 111
for i in range(2, 1):
print(i)
else:
print("else:", i)
Console
else: 111
Example
Scenario
Listen to this story: a boy and his father, a computer programmer, are playing with wooden blocks.
They are building a pyramid.
Their pyramid is a bit weird, as it is actually a pyramid-shaped wall - it's flat. The pyramid is stacked
according to one simple principle: each lower layer contains one block more than the layer above.
Your task is to write a program which reads the number of blocks the builders have, and outputs the
height of the pyramid that can be built using these blocks.
Note: the height is measured by the number of fully completed layers - if the builders don't have a
sufficient number of blocks and cannot complete the next layer, they finish their work immediately.
Test Data
Sample input: 6
Sample input: 20
Sample input: 2
3.1.2.15 Surbhi ?
Example 1
while True:
print("Stuch in indefinate loop")
Example 2
counter = 5
while counter > 1:
print(counter)
counter -= 1
the for loop executes a set of statements many times; it's used to iterate over a sequence
(e.g., a list, a dictionary, a tuple, or a set - you will learn about them soon) or other objects
that are iterable (e.g., strings). You can use the for loop to iterate over a sequence of
numbers using the built-in range function. Look at the examples below:
Example 1
word = "Phython"
for letter in word:
print(letter,end="*")
Console
P*h*y*t*h*o*n*
Example 2
for i in range(1,10):
if i %2 == 0:
print("even",i)
else:
print("odd",i)
Console
odd 1
even 2
odd 3
even 4
odd 5
even 6
odd 7
even 8
odd 9
You can use the break and continue statements to change the flow of a loop:
Example
text = "OpenEDG Python Institute"
for letter in text:
if letter == "P":
break
print(letter, end=" ")
console
O p e n E D G
Example
text = "pyxpyxpyx"
for letter in text:
if letter == "x":
continue
print(letter, end=" ")
Console
p y p y p y
while n != 3:
print(n)
n += 1
else:
print(n, "else")
print()
Example
for i in range(3):
print(i, end=" ") # outputs: 0 1 2
Create a for loop that counts from 0 to 10, and prints odd numbers to the screen. Use the
skeleton below:
Solution 1
Exercise 2
Create a while loop that counts from 0 to 10, and prints odd numbers to the screen. Use the
skeleton below:
x = 1
while x < 11:
# line of code
# line of code
# line of code
x=1
while x < 11:
if x % 2 != 0:
print(x)
x += 1
Exercise 3
Create a program with a for loop and a break statement. The program should iterate over
characters in an email address, exit the loop when it reaches the @ symbol, and print the part
before @ on one line. Use the skeleton below:
for ch in "john.smith@pythoninstitute.org":
if ch == "@":
# line of code
# line of code
for ch in "john.smith@pythoninstitute.org":
if ch == "@":
break
print(ch, end="")
Console
john.smith
Exercise 4
Create a program with a for loop and a continue statement. The program should iterate over
a string of digits, replace each 0 with x , and print the modified string to the screen. Use the
skeleton below:
Console
x165x318x651x
Exercise 5
while n > 0:
print(n + 1)
n -= 1
else:
print(n)
Console
4
3
2
0
Exercise 6
n = range(4)
for num in n:
print(num - 1)
else:
print(num)
Console
-1
0
1
2
3
Exercise 7
Console
0
3
If you are in the mall or I am in the mall, one of us will buy a gift for Mom.
It's clear that Python must have operators to build conjunctions and
disjunctions. Without them, the expressive power of the language would be
substantially weakened. They're called logical operators.
and
One logical conjunction operator in Python is the word and. It's a binary
operator with a priority that is lower than the one expressed by the
comparison operators. It allows us to code complex conditions without the
use of parentheses like this one:
If we consider the conjunction of A and B, the set of possible values of arguments and
corresponding values of the conjunction looks as follows:
A disjunction operator is the word or . It's a binary operator with a lower priority
than and (just like + compared to * ). Its truth table is as follows:
Argument A Argument B A or B
False False False
False True True
True False True
True True True
not
In addition, there's another operator that can be applied for constructing
conditions. It's a unary operator performing a logical negation. Its operation
is simple: it turns truth into falsehood and falsehood into truth.
This operator is written as the word not, and its priority is very high: the
same as the unary + and -. Its truth table is simple:
Argument Not Argument
True False
False True
Logical expressions
Let's create a variable named var and assign 1 to it. The following
conditions are pairwise equivalent:
print(var > 0)
print(not (var <= 0))
print(var != 0)
print(not (var == 0))
Logical operators take their arguments as a whole regardless of how many bits they contain.
The operators are aware only of the value: zero (when all the bits are reset) means False ; not
zero (when at least one bit is set) means True .
The result of their operations is one of these values: False or True . This means that this
snippet will assign the value True to the j variable if i is not zero; otherwise, it will be False .
ex
i=1
j = not i
Console
False
i=1
j = not not i
Console
True
EX
i=0
if i :
print("true")
else:
print("false")
Console
False
Ex
i=0
if not i :
print("true")
else:
print("false")
Console
True
Ex
i=0
if not not i :
print("true")
else:
print("false")
Console
False
Bitwise operators
However, there are four operators that allow you to manipulate
single bits of data. They are called bitwise operators.
Let's create a variable called numbers; it's assigned with not just
one number, but is filled with a list consisting of five values (note:
the list starts with an open square bracket and ends with a closed
square bracket; the space between the brackets is filled with five
numbers separated by commas).
numbers = [10, 5, 7, 2, 1]
The elements inside a list may have different types. Some of them
may be integers, others floats, and yet others may be lists.
You'll soon get used to it, and it'll become second nature.
Let's assign a new value of 111 to the first element in the list. We
do it this way:
Example
numbers = [10, 5, 7, 2, 1]
print("Original list content:", numbers) # printing original list
content
numbers[0] = 111
print("New list content: ", numbers) # current list content
And now we want the value of the fifth element to be copied to the
second element - can you guess how to do it?
Example
numbers = [10, 5, 7, 2, 1]
print("Original list content:", numbers) # printing original list
content
numbers[0] = 111
print("\nPrevious list content:", numbers) # printing previous list
content
The value inside the brackets which selects one element of the
list is called an index, while the operation of selecting an element
from the list is known as indexing.
The len() function
The length of a list may vary during execution. New elements may be added to the list, while
others may be removed from it. This means that the list is a very dynamic entity.
If you want to check the list's current length, you can use a function named len() (its name
comes from length).
The function takes the list's name as an argument, and returns the number of elements
currently stored inside the list (in other words - the list's length).
Example
numbers = [10, 5, 7, 2, 1]
print(len(number))
Example
numbers = [10, 5, 7, 2, 1]
print("Original list content:", numbers) # printing original list
content
numbers[0] = 111
print("\nPrevious list content:", numbers) # printing previous list
content
Example
del numbers[1]
print(len(numbers))
print(numbers)
Example
numbers = [10, 5, 7, 2, 1]
print("Original list content:", numbers) # printing original list
content
numbers[0] = 111
print("\nPrevious list content:", numbers) # printing previous list
content
###
Example
print(numbers[-1])
print(numbers[-2])
Example
numbers = [111, 7, 2, 1]
print(numbers[-1])
print(numbers[-2])
print(numbers[-3])
Console
1
2
7
Objectives
Example
Console
[1, 2, 3, 4, 5]
Enter number: 776
[1, 2, 776, 4, 5]
list after del [1, 2, 776, 4]
length 4
list [1, 2, 776, 4]
This also means that invoking a method requires some specification of the data from
which the method is invoked.
It may sound puzzling here, but we'll deal with it in depth when we delve into object-
oriented programming.
In general, a typical function invocation may look like this:
result = function(arg)
The function takes an argument, does something, and returns a result.
result = data.method(arg)
Note: the name of the method is preceded by the name of the data which owns the method.
Next, you add a dot, followed by the method name, and a pair of parenthesis enclosing the
arguments.
The method will behave like a function, but can do something more - it can change the
internal state of the data from which it has been invoked.
You may ask: why are we talking about methods, not about lists?
This is an essential issue right now, as we're going to show you how to add new elements to an
existing list. This can be done with methods owned by all the lists, not by functions.
list.append(value)
list.insert(location, value)
It takes two arguments:
Example
numbers = [111, 7, 2, 1]
print(len(numbers))
print(numbers)
###
numbers.append(4)
print(len(numbers))
print(numbers)
###
numbers.insert(0, 222)
print(len(numbers))
print(numbers)
#
Console
4
[111, 7, 2, 1]
5
[111, 7, 2, 1, 4]
6
[222, 111, 7, 2, 1, 4]
Adding elements to a list: continued
You can start a list's life by making it empty (this is done with an empty pair of square
brackets) and then adding new elements to it as needed.
Example
for i in range(5):
myList.append(i + 1)
print(myList)
Console
[1, 2, 3, 4, 5]
Example
for i in range(5):
myList.insert(0, i + 1)
print(myList)
Console
[5, 4, 3, 2, 1]
You should get the same sequence, but in reverse order (this is the merit of using
the insert() method).
Let's assume that you want to calculate the sum of all the values stored in the myList list.
Example
myList = [10, 1, 8, 3, 5]
total = 0
for i in range(len(myList)):
total += myList[i]
print(total)
Console
27
But the for loop can do much more. It can hide all the actions connected to the list's indexing,
and deliver all the list's elements in a handy way.
myList = [10, 1, 8, 3, 5]
total = 0
for i in myList:
total += i
print(total)
Console
27
Lists in action
Example
variable1 = 1
variable2 = 2
auxiliary = variable1
variable1 = variable2
variable2 = auxiliary
a=5
b = 10
print("a",a)
print("b",b)
a , b = b, a
print("a",a)
print("b",b)
Example
myList = [10, 1, 8, 3, 5]
console
[5, 3, 8, 1, 10]
Example
Using for loop
list = [ 10, 1, 8, 3, 5]
print(list)
length = len(list)
for i in range(length // 2):
list[i],list[length - i - 1] = list[length - i - 1 ], list[i]
print(list)
Console
[10, 1, 8, 3, 5]
[5, 3, 8, 1, 10]
Note:
we've assigned the length variable with the current list's length (this makes our code a
bit clearer and shorter)
we've launched the for loop to run through its body length // 2 times (this works well
for lists with both even and odd lengths, because when the list contains an odd number
of elements, the middle one remains untouched)
we've swapped the ith element (from the beginning of the list) with the one with an index
equal to (length - i - 1) (from the end of the list); in our example, for i equal
to 0 the (l - i - 1) gives 4; for i equal to 1, it gives 3 - this is exactly what we needed.
Exercise
Write a program that reflects these changes and lets you practice with the concept of lists. Your
task is to:
# step 2
print("Step 2:", beatles)
# step 3
print("Step 3:", beatles)
# step 4
print("Step 4:", beatles)
# step 5
print("Step 5:", beatles)
beatles = []
print("Step 2:", beatles)
beatles.append("John Lennon")
beatles.append("Paul McCartney")
beatles.append("George")
beatles.append("Harrison")
del beatles[length - 1]
del beatles[length - 2]
print("deleting last two names " ,beatles)
beatles.insert(0,"Ringo Starr")
print("inserting names " ,beatles)
print("Step 5:", beatles)
Key takeaways
1. The list is a type of data in Python used to store multiple objects. It is an ordered and
mutable collection of comma-separated items between square brackets, e.g.:
Example
myList[1] = '?'
print(myList)
# outputs: [1, '?', True, 'I am a string', 256, 0]
myList.insert(0, "first")
myList.append("last")
print(myList)
# outputs: ['first', 1, '?', True, 'I am a string',
256, 0, 'last']
myList = [1, 2, 3, 4]
del myList[2]
print(myList) # outputs: [1, 2, 4]
Example
list = []
for i in range(6):
list.append(input("enter color name :"))
for i in list:
print(i)
else:
print(list)
del myList[2]
print(len(myList)) # outputs 4
Exercise 1
lst = [1, 2, 3, 4, 5]
lst.insert(1, 6)
del lst[0]
lst.append(1)
print(lst)
Exercise 2
lst = [1, 2, 3, 4, 5]
lst2 = []
add = 0
print(lst2)
Exercise 3
lst = []
del lst
print(lst)
Exercise 4
10
4
2
6
8
Look - 10 is at the top. We could say that it floated up from the bottom to the surface, just like
the bubble in a glass of champagne. The sorting method derives its name from the same
observation - it's called a bubble sort.
Now we start with the second pass through the list. We look at the first and second elements - a
swap is necessary:
6 8 2 4 10
Time for the second and third elements: we have to swap them too:
6 2 8 4 10
Now the third and fourth elements, and the second pass is finished, as 8 is already in place:
6 2 4 8 10
We start the next pass immediately. Watch the first and the second elements carefully - another
swap is needed:
2 6 4 8 10
Now 6 needs to go into place. We swap the second and the third elements:
2 4 6 8 10
The list is already sorted. We have nothing more to do. This is exactly what we want.
As you can see, the essence of this algorithm is simple: we compare the adjacent elements,
and by swapping some of them, we achieve our goal.
Sorting a list
Example
myList = [8, 10, 6, 2, 4]
j=0
for j in range(len(myList) - 1):
for i in range(len(myList) - 1):
if myList[i] > myList[i + 1]:
myList[i], myList[i + 1] = myList[i + 1], myList[i]
else:
print(myList)
Example
myList = [8, 10, 6, 2, 4]
swapped = True
while swapped:
swapped = False # no swaps so far
for i in range(len(myList) - 1):
if myList[i] > myList[i + 1]:
swapped = True # swap occured!
myList[i], myList[i + 1] = myList[i + 1], myList[i]
print(myList)
print("final",myList)
Console
[8, 6, 10, 2, 4]
[8, 6, 2, 10, 4]
[8, 6, 2, 4, 10]
[6, 8, 2, 4, 10]
[6, 2, 8, 4, 10]
[6, 2, 4, 8, 10]
[2, 6, 4, 8, 10]
[2, 4, 6, 8, 10]
final [2, 4, 6, 8, 10]
print("final",mylist)
Key takeaways