Nothing Special   »   [go: up one dir, main page]

Note 3 (Scientific Programming Language) - 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

SCIENTIFIC PROGRAMMING LANGUAGE (Lecture Note 3)

INTRODUCTION TO FUNCTIONS
In Python, a function is a named block of code that performs a specific task i.e.
in the context of programming, a function is a named sequence of statements
that performs a computation.
Functions can be categorized as belonging to
 Modules  Built in Functions  User Defined Functions

MODULES
Modules are Python.py files that consist of Python code. Any Python file can be
referenced as a module. Modules contains define functions, classes, and
variables, that we can refer in our Python.py files or via the Python command
line interpreter. There are a number of modules that are built into the Python
Standard Library. Let us understand how to use modules by some examples.
Example: 29 → Example of import module format.
# File Name:sq_root.py | Source Code by: A.Nasra
import math # math is module, sqrt() is function.
x = eval(input('Enter a number: ')) print('\
u221A(',x,')=',math.sqrt(x))
# Sample run of sq_root.py
Enter a number: 49.49
√( 49.49 )= 7.034912934784623

In the above the coding of file sq_root.py imports the whole module named
math and then with the help of dot notation executes/invokes/accesses/calls the
sqrt() function out of many functions within the math module.
Now, let us witness the new format for using sqrt() function in our file.
Example: 30 → Example of: from module import function format.
# File Name:sq_root.py | Source Code by: A.Nasra
from math import sqrt
x = eval(input('Enter a number: '))
print('\u221A(',x,')=',sqrt(x))
# Sample run of sq_root.py
Enter a number: 49.49
√( 49.49 )= 7.034912934784623

The both format of calling sqrt() function can also be used in Python shell,
as is exemplified below.
Example: 31 → (Python shell) from module import function format
>>> from math import sqrt
>>> sqrt(381)
19.519221295943137
>>> sqrt(sqrt(625))
5.0
>>> import math
>>> math.sqrt(1016)
31.874754901018456

Example: 32 → Calculation of Complex Numbers


>>> import cmath
>>> cmath.sqrt(3 + 7j)
(2.3038850997677716+1.5191729832155236j)
>>> cmath.polar(25 + 36j)
(43.829214001622255, 0.9638086627484886)
>>> cmath.exp(3 + 4j)
(-13.128783081462158-15.200784463067954j)

SOME IMPORTANT FUNCITONS OF MATH MODULE


Function Meaning of Function Examples
Name
ceil( x ) It returns the smallest integer
not less than x, where x is a
numeric expression.

floor( x ) It returns the largest integer not


greater than x, where x is a
numeric expression.

fabs( x ) It returns the absolute value of x,


where x is a numeric value.

exp( x ) It returns exponential of x: ex ,


where x is a numeric expression.

log( x ) It returns natural logarithm of x,


for x > 0, where x is a numeric
expression.
log10( x ) It returns base-10 logarithm of x
for x > 0, where x is a numeric
expression.

pow( x, y ) It returns the value of xy, where


x and y are numeric expressions.

sqrt( x ) It returns the square root of x for


x > 0, where x is a numeric
expression.

cos( x ) It returns the cosine of x in


radians, where x is a numeric
expression
sin( x ) It returns the sine of x, in
radians,
where x must be a numeric
value.
tan( x ) It returns the tangent of x in
radians, where x must be a
numeric value.
degrees(x) It converts angle x from radians
to degrees, where x must be a
numeric value.
radians(x) It converts angle x from degrees
to radians, where x must be a
numeric value.

SOME IMPORTANT FUNCITONS OF RANDOM MODULE


Function Meaning of Function Examples
Name
random( ) It returns a random float x, such
that 0 ≤ x<1
randint (a, b) It returns a int x between a & b
such that a ≤ x ≤ b
uniform (a,b) It returns a floating point
number x, such that
a <= x < b
randrange It returns a random item from
(start, stop, step) the given range
SOME IMPORTANT FUNCITONS RELATED TO TIME
The time package (Package is folder that contains modules) has a number of
functions that relate to time. We will consider two functions: clock() and
sleep(). The clock() function measures the time of parts of a program’s
execution and returns a floating-point value, in seconds. The sleep()
function suspends the program’s execution for a specified number of seconds.
Exact times will vary depending on the speed of the computer.
Note:- In Python 3.3 clock() has been deprecated and will be removed in
Python 3.8. Instead, we can use process_time() function.
Let us understand the use of these functions by following examples.
Example: 33 → CExample of time module.
# File Name: time_passed.py | Source Code by: A.Nasra
from time import process_time
# Notice the sequence of following 2 statements.
start = process_time()
name = input('Enter your name: ')
time_passed = process_time()-start
print(name,',you took',time_passed,'seconds to write
your name.')
# Sample run of time_passed.py
Enter your name: Mr. India
Mr. India ,you took 0.03125 seconds to write your
name.
Example: 34 → CFinding current time.
# File Name: time1.py | Source Code by: A.Nasra
import time;
localtime = time.asctime(time.localtime(time.time()))
print("Local current time :", localtime)
# Sample run of time1.py
Local current time : Fri Aug 17 10:57:52 2018

Example: 35 → Finding the calender of current year and month.


import calendar
cal = calendar.month(2018,8)
print("Here is the calendar:")
print(cal)

Run the above program and see the result/output.


BUILT IN FUNCITONS
The Python interpreter has a number of functions that are always available for
use. These functions are called built-in functions. We don’t have to import any
module (file). Built in functions are used with appropriate object. In Python
3.6.7 there are 68 built in functions. Some important functions are listed below.

SOME IMPORTANT BUILT IN FUNCITONS


Function Meaning of Function Examples
Name
abs (x) It returns absolute value,
where x is a numeric
expression.
max(x, y, z, It returns the largest of its
...) arguments: where x, y and z
are numeric
variable/expression.
min(x, y, z, It returns the smallest of its
...) arguments; where x, y, and z
are numeric variable /
expression.
cmp(x, y) It returns the sign of the [N/A for Python 3.6.5]
difference of two numbers: -1
if x < y, 0 if x == y, or 1 if x
> y, where x and y are
numeric
variable/expression.
divmod(x,y) Returns both quotient and
remainder by division
through a tuple, when x is
divided by y; where x & y
are variable /
expression
len(s) Return the length (the
number of items) of an
object. The argument may be
a sequence (string, tuple
or list) or a mapping
(dictionary).
range(start, This is a versatile function to
stop, step) create lists containing
arithmetic progressions. It is
most often used in for loops.
The arguments must be plain
integers. If the step argument
is omitted, it defaults to 1. If
the start argument is omitted,
it defaults to 0. The full form
returns a list of plain integers
[start, start + step, start + 2 *
step, ...]. If step is positive,
the last element is the largest
start
+ i * step less than stop; if
step
is
negative, the last element is
the smallest start + i * step
greater than stop. Step must
not be zero (or else Value
Error is raised).
round(x, n) It returns float x rounded to n
digits from the decimal point,
where x and n are numeric
expressions. If n is not
provided then x is rounded to
0 decimal digits.
bin(d) Convert an integer number to
a binary string prefixed with
“0b”. The result is a valid
Python expression.

oct(d) Convert an integer number to


an octal string prefixed with
“0o”.

hex(d) Convert an integer number to


a lowercase hexadecimal
string prefixed with “0x”.

USER DEFINED FUNCITONS


A function is a block of code which only runs when it is called. We can pass data,
known as parameters, into a function. A function can return data as a result.
CREATING A FUNCTION
In Python a function is defined using the def keyword.
Example: 36 → Understanding def keyword.
# Creation of a simple function.
def urn(): # urn means your name
name = input('Enter your name: ')
print('Hello',name,'You are a God-fearing
person.')

CALLING A FUNCTION
A sample run of urn.py is given below: when we write urn() in Python shell,
it means, we are calling the function that we had created in Python script.
# Sample run of urn.py
>>> urn()
Enter your name: Alina
Hello Alina .You are a God-fearing person.

PARAMETERS AND ARGUMENTS


Parameters are specified within the pair of parentheses in the function
definition, separated by commas. When we call the function, we supply the
values in the same way. Note the terminology used - the names given in the
function definition are called parameters whereas the values you supply in the
function call are called arguments. Let us inspect the following example.
Example: 37 → Understanding role of parameters and arguments in definition.
# File Name: max_min.py | Source Code: A. Nasra
def tell_max(a,b): # a and b are parameters
if a > b:
print(a,'is maximum.')
elif a == b:
print(a,'is equal to', b)
else:
print(b,'is maximum.')
# Sample run of max_min.py
>>> tell_max(43,56) # Here 56(value of a) and
56 is maximum. # 56(value of b) are arguments

DEFAULT PARAMETERS
While calling, if the user forgets or does not want to provide values for the
parameter, then the default argument values are provided by the program while
coding the parameter that is called default parameter. Note that the default
argument value should be a constant (immutable). How to do it, let us
understand by the following example.
Example: 38 → C (File Name: volume2.py)
# File Name: volume.py | Source code by: A. Nasra
print('Call the function vol(length,breadth,height)')
def vol(l, b, h = 10): # Here h is default parameter
print('Volume =',l*b*h)

See, the sample run, third argument is not provided, hence it is taken as 10.
# Sample run of volume.py
Call the function vol(length, breadth, height)
>>> vol(23,40)
Volume = 9200
#When height is not given it is taken as 10, the value
of default parameter

RETURN STATEMENT
Return statement returns a value from the function. Return statement may
contain a constant/literal, variable, expression or function, if return is used
without anything, it will return None. Let us understand the following coding.
Example: 39 → Program to find the Fibonacci Series.
#Fibonacci series
#File Name: fib1.py | Code by: A. Nasra
print('Call the function fib(n) for the Fibonacci
series up to n terms.')
n=0
def fib(n):
a, b = 0, 1
for n in range(1,n,1):
print(a, end=' ')
a, b = b, a+b
return a
fib(n) #calling the function
# Sample run of fib1.py
Call the function fib(n) for the Fibonacci series for
n terms.
>>> fib(9)
0 1 1 2 3 5 8 13 21

Example: 40 → Default parameter.


# File Name: volume1.py | Source Code by: A. Nasra
print('call the function vol(length,breadth,height)')
def vol(l, b, h = 2):
v = l*b*h
print('Volume = ',end='')
return v
# Sample run of volume1.py
call the function vol(length,breadth,height)
>>> vol(15,7)
Volume = 210
>>> vol(1.1,2.2,3.3)
Volume = 7.986000000000001
>>> vol(1 + 2j, 3 + 4j)
Volume = (-10+20j)

SCOPE OF VARIABLES
Scope of variable refers to the part of the program, up to which the variable is
accessible. We will study two types of scopes – Global and Local scopes.
When a variable is created outside all functions/blocks, it is called global
variable.
Example: 23 → Example of global variable.
# File Name: global.py | Code by: A. Nasra
x = eval(input('Enter a global value: '))
print('Now call the function gal()')
def gal(): # gal stands for global
print('Global value is',x)
# Sample run to global.py
Enter a global value: 78
Now call the function gal()
>>> gal()
Global value is 78

Example: 42 → Example of local variable.


# File Name: global.py | Code by: A. Nasra
print('Call the function lal()')
def lal(): # lal stands for local
y = eval(input('Enter a local value: '))
print('Local value is',y)
# File Name: local.py
Call the function lal()
>>> lal()
Enter a local value: 86
Local value is 86
Example: 43 → Recognising global and local values.
# File Name: global_local.py | Coded by: A. Nasra
x = eval(input('Enter a global value: '))
print('Now, call gl()')
def gl(): # gl stand for global local
y = eval(input('Enter a local value: '))
print('Global value is',x)
print('Local value is',y)
# Sample run of global_local.py
Enter a global value: 47
Now, call gl()
>>> gl()
Enter a local value: 45
Global value is 47
Local value is 45

DOCSTRING
The multiline string in the block of a function definition (or the first line in a
module) is known as a documentation string, or docstring for short.
Docstring provides information about
• The purpose of the function.
• The role of each parameter.
• The nature of the return value.
Example: 44 → Calculation of distance between two points.
# File Name: distance.py | Coded by: A. Nasra
from math import sqrt
print('Call the function dist(x1,y1,x2,y2)')
def dist(x1,y1,x2,y2):
'''The function dist(x1,y1,x2,y2) returns the
distance between two coordinates (x1,y1) and
(x2,y2)'''
d = sqrt((x2-x1)**2 + (y2-y1)**2)
print('Distance =',end=' ')
return d
# Sample run of file distance.py
Call the the function dist(x1,y1,x2,y2)
>>> dist(1,2,3,4)
Distance = 2.8284271247461903

KEYWORD ARGUMENT
We know that a print function accepts an additional argument that allows the
cursor to remain on the same line as the printed text:
print('Please enter an integer value:', end='')
The expression end=’’ is known as a keyword argument. The term keyword
here means something different from the term keyword used to mean a reserved
word.
Another keyword argument named sep specifies the string to use insert
between items. The default value of sep is the string ’’, a string containing a
single space. The name sep stands for separator.
Example: 45 → Use of separator.
# File Name: separator.py | Coded by: A. Nasra
d, m, y = 19, 8, 2018
print('TODAY\'S DATE is given below:')
print(d, m, y)
print(d, m, y, sep= ':')
print(d, m, y, sep= '/')
print(d, m, y, sep= '|')
# Sample run of printsep.py
TODAY'S DATE is given below:
19 8 2018
19:8:2018
19/8/2018
19|8|2018
STATEMENTS AND ITS TYPE IN PYTHON
Statements are the instruction to the computer to do some work and produce the
result. There are three types of statements in Python:
1. Empty Statement
2. Simple Statement (Single statement)
3. Compound Statement
EMPTY STATEMENT
The statement that does nothing is called empty statement. In Python empty
statement is pass statement. In Python programming, pass is a null statement.
Example: 46 → Illustration of pass statement.
#Ex of pass statement | File Name: ex_pass.py
#Code by: A. Nasra
for letter in 'abba':
if letter == 'b':
pass
print('Letter b is pass.')
else:
print('Current Letter :', letter)
# Sample run of ex_pass.py
Current Letter : a
Letter b is pass.
Letter b is pass.
Current Letter : a

SIMPLE STATEMENT
A single line logical statement that is executable is called simple statement in
Python. Several simple statements may occur on a single line separated by
comma. One of the example of simple statement is assignment statement.
Simple statements may be of following types:
1. expression_stmt 2. assert_stmt
3. assignment_stmt 4. augmented_assignment_stmt
5. annotated_assignment stmt 6. pass_stmt
7. del_stmt 8. return_stmt
9. yield_stmt 10. raise_stmt
11. break_stmt 12. continue_stmt
13. import_stmt 14. global_stmt
15. nonlocal_stmt
COMPUND STATEMENT
A group of statements, headed by a line is called compound statement. All of
the following comes under the compound statement,
1. if_stmt 2. while_stmt 3. for_stmt
4. try_stmt 5. with_stmt 6. funcdef
7. classdef 8. async_with_stmt 9. async_for_stmt
10. async_funcdef
PROGRAM LOGIC DEVELOPMENT TOOLS
These are the tools that facilitate the writing of the actual program one of such
tools is algorithm. The well-defined step by step instructions (or procedures) is
called algorithm. Algorithm is made with the help of following tools
1. Flowchart/Flow-diagram
2. Pseudocode
3. Decision Trees
FLOWCHART
A flowchart is a graphical representation of an algorithm to solve a given
problem. It consist of following symbols for different steps of the algorithm.

PROCESS SUBPROC DOCUMENT

START/EN INPUT/OUT
DECISION D PUT

PSEUDOCODE
Pseudocode is an easy going natural language that helps programmers develop
algorithm without using any programming language. Pseudocode is a ‘text
based’ detail design tool
DECISION TREES (DT)
Decision tree is a type of hierarchical and sequential algorithm that is mostly
used in classification problem. The basic idea of DT is to split the data
continually according to one (or multiple) attributes (rules), so that we end up
with sub-sets that have single outcomes.
EXAMPLES OF FLOWCHART, PSEDUCODE, DT WITH PYTHON CODE
Example: 47 → Write a program to accept three integers and print the largest of
the three. Make use of only if statement.
Algorithm:

Start Input x, Max = x If y > Max?

Yes
Max = y

Print Yes
Stop Max = z If z > Max?
largest is

Pseudocode:
Input three numbers x, y, z
Max = x (Note x is the first number)
If second number y is more than max then
Max = y
If third number z is more than max then
Max = z
Display max number as largest number

Code In Python:
x = y = z = 0
x = eval(input("Enter first number: "))
y = eval(input("Enter second number: "))
z = eval(input(Enter third number: "))
max = x
if y > max:
max = y
if z > max:
max = z
print("Largest number is ", max)

Example: 48 → Write a program that takes a number and checks whether the
given number is odd or even.
Algorithm:
Input Is num/2 No Display
Start has num is
Ye
Display
num is Stop
Decision Tree:
Remainder
when num/2
= =
Num is Num is
even odd

Pseudocode:
Input num
If num divide by 2 is equal to 0, then
Display num is even
Else display num is odd.

Code In Python
num = eval(input("Enter a number: "))
if num%2 ==0:
print(num, " is even number.")
else:
print(num, " is odd number.")

CONDITIONAL STATEMENTS
Conditional statements are such constructs that allow program statements to be
optionally executed, depending on the condition/situation of the program’s
execution. Important conational statements are: simple if, nested if, if…
else, if…elif…else.
THE SIMPLE IF
The simple if statement tests a particular condition/Boolean expression; if the
condition evaluates to be true the block of statement(s) i.e., body of if is
executed otherwise (condition evaluates to be false) execution is ignored.
The general form of if statement along with flow control diagram is worth seeing.

if condition:
block
 Reserved word if begins the if statement.
 Condition is Boolean expression followed
by colon(:)
 The block is set of statements to be
Example: 49 → Illustration of if statement.
# File Name: passgrade.py | Coded by: A. Nasra
marks = eval(input('Enter your marks:'))
if marks >= 65:
print('You obtained passing grade.')
# Sample run of the file passgrade.py
Enter your marks:74.8
You obtained passing grade.

IF … ELSE STATEMENT
When if statement has an optional else clause that is executed only if the
Boolean condition is false, the statement is known as if … else statement.
The else block, like the if block, consists of one or more statements indented to
the same level.

 The reserved word if


begins if … else statement.
 The condition is a Boolean
expression that determines
whether or not if block or else
block will be executed. A
colon (:) must follow the
condition.

Example: 50 → Program to find the division of two numbers.


# File Name: division.py | Coded by: A. Nasra
a , b = eval(input('Enter two numbers: '))
if b != 0:
print(a,'/',b,'=',a/b)
else:
print('Division by zero is not allowed')
# Sample run of the file division.py
# Sample run - 1
Enter two numbers: 456, 17
456 / 17 = 26.823529411764707
# Sample run - 2
Enter two numbers: 17, 0
Division by zero is not allowed

NESTED IF
When under if or else or both some if statement is used, it is known as nested if.
This concept be understood by the following examples.
Example: 51 → Illustration of nested if.
# File Name: in_range.py | Coded by: A. Nasra
value = int(input('Enter an integer value in the
range of 0 to 10: '))
if value >= 0:
if value <= 10:
print("Value entered is in range.")
else:
print("Value entered isn\'t in range.")
print("Done!")
# Sample run of in_range.py..
# Sample run – 1
Enter an integer value in the range of 0 to 10: 7
Value entered is in range.
Done!
# Sample run – 2
Enter an integer value in the range of 0 to 10: 11
Value entered isn't in range.
Done!
Enter an integer value in the range of 0 to 10: -3
Done!
Now, see the improved version of the same program in following program.
Example: 52 → Illustration of nested if.
# File Name: in_range1.py | Coded by: A. Nasra
value = int(input('Enter an integer value in the
range of 0 to 10: '))
if value >= 0:
if value <= 10:
print(value,"is in range.")
else:
print(value,"is too large (greater than 10)")
else:
print(value,"is too small (less than 0)")
print('Done!')
# Sample run of file in_range1.py
# Sample run – 1
Enter an integer value in the range of 0 to 10: 7
7 is in range.
Done!
# Sample run – 2
Enter an integer value in the range of 0 to 10: 17
17 is too large (greater than 10)
Done!
# Sample run - 3
Enter an integer value in the range of 0 to 10: -7
-7 is too small (less than 0)
Done!

Example: 53 → Write a program to print roots of a quadratic equation:


ax2 + bx + c = 0 (a != 0)
#File Name: root.py | Script by: A. Nasra
#Prog. to calculate and print roots of quadratic
equation:
ax2 + bx + c = 0 (a not equal to 0)
from math import sqrt
import cmath #for complex roots
print("Enter the co-efficient of Quadratic Eq
ax**2+bx+c ")
a = eval(input(" a = "))
b = eval(input(" b = "))
c = eval(input(" c = "))
if a = 0:
print("Value of a must not be 0")
else:
delta = b*b-4*a*c
if delta > 0:
x1 = (-b+sqrt(delta))/2*a
x2 = (-b-sqrt(delta))/2*a
print("Roots are REAL & UNEQUAL")
print("Root1 =",x1," Root2 =",x2)
elif delta == 0:
x1 = x2 = -b/2*a
print("Roots are REAL & EQUAL")
print("Root1 =",x1," ; ","Root2 =",x2)
else:
x1 = -b/2*a + cmath.sqrt(delta)
x2 = -b/2*a – cmath.sqrt(delta)
print("Roots are IMAGINARY & COMPLEX")
print("Root1 =",x1," Root2 =",x2)
#Sample run-1
Enter the co-efficient of Quadratic Eq ax**2+bx+c
a = 6
b = 10
c = 4
Roots are REAL & UNEQUAL
Root1 = -24.0 ; Root2 = -36.0
#Sample run-2
Enter the co-efficient of Quadratic Eq ax**2+bx+c
a = 4
b = 8
c = 4
Roots are REAL & EQUAL
Root1 = -16.0 ; Root2 = -16.0
# Sample run-3
Enter the co-efficient of Quadratic Eq ax**2+bx+c
a = 1
b = 2
c = 3
Roots are IMAGINARY & COMPLEX
Root1 = (-1+1.4142135623730951j) Root2 = (-1-
1.4142135623730951j)

IF … ELIF … ELSE
The if…elif…else statement is valuable for selecting accurately one block
of code to execute from several different options. The if part of an if…
elif…else statement is mandatory. The else part is optional. After the
if part and before else part (if present) we may use as many elif blocks
as necessary.
Example: 54 → Illustration of if … elif … else statement.
# File name: number2day.py
day = int(input('Enter the day as number (0 to 6): '))
if day == 0:
print('Sunday')
elif day == 1:
print('Monday')
elif day == 2:
print('Tuesday')
elif day == 3:
print('Wednesday')
elif day == 4:
print('Thrusday')
elif day == 5:
print('Friday')
elif day == 6:
print('Saturday’)
else:
print('Enter the correct day as number.')
# Sample run of the file number2day.py\
# Samplr run - 1
Enter the day as number (0 to 6): 5
Friday
# Sampler run - 2
Enter the day as number (0 to 6): 10
Enter the correct day as number.

Example: 55 → Write a program that reads two numbers and a arithmetic


operator and calculates the computed result.
# File: calculator.py | Script by: A. Nasra
n1 = eval(input("Enter first number: "))
op = input("Enter an [+ - * / %]: ")
n2 = eval(input("Enter second number: "))
result = 0
if op == '+':
result = n1 + n2
elif op == '-':
result = n1 – n2
elif op == '*':
result = n1 * n2
elif op == '/':
result = n1 / n2
elif op == '%':
result = n1 % n2
else:
print("Invalid operator!")
print(n1, op, n2, ' = ',result)
# Sample run of calculator.py
Enter first number: 15
Enter an operator [+ - * / %]: /
Enter second number: 6
15 / 6 = 2.5

Example: 56 → Write a program to print whether a given character is an


uppercase or a lovercase character or a dight or a special character.
# File Name: char1.py | Script by: A. Nasra
ch = input("Enter a single character ")
if ch >= 'A'and ch<= 'Z':
print("You have entered an Upper character.")
elif ch >= 'a'and ch<= 'z':
print("You have entered a Lower character.")
elif ch >= '0'and ch<= '9':
print("You have entered a Digit.")
else:
print("You have entered a Special character.")
# Sample run of char1.py
Enter a single character %
You have entered a Special character.
Example: 57 →Write a program that reads three numbers inputted by the user
and print them in ascending order.
#File Name: 3num_asc.py | Script by: A. Nasra
#Three numbers in ascending order
x = eval(input("Enter first number: "))
y = eval(input("Enter second number: "))
z = eval(input("Enter third number: "))
if x<y and x<z:
if y<z:
big, bigger, biggest = x, y, z
else:
big, bigger, biggest = x, z, y
elif y<x and y<z:
if y<z:
big, bigger, biggest = y, x, z
else:
big, bigger, biggest = y, z, x
else:
big, bigger, biggest = z, y, x
print("Numbers in ascending order:",big,bigger,
biggest)
#Sample run of 3num_asc.py
Enter first number: 9
Enter second number: 6
Enter third number: 11
Numbers in ascending order: 6 9 11

ITERATION
Iteration repeats/loops the execution of a sequence of code. Iteration is useful
for solving many programming problems. Important iterations are: while
statement, for statements,
THE WHILE LOOP
The while loop is the most general looping statement in Python. it consists of
the word while, followed by an expression that is interpreted as a true or false
result, followed by a nested block of code that is repeated while the test at the
top is true.
The general form of while loop is as given below.

You might also like