Introduction to Python Programming
Introduction to Python Programming
PROGRAMMING- MODULE1
1|Page
[Link]
1.1 Python Basics
1.1.1 Introduction: Python is a general-purpose interpreted, interactive, object-
oriented, and high-level programming language. It was created by Guido van
Rossum during 1985- 1990. Python is named after a TV Show called ‘Monty Python’s
Flying Circus’ and not after Python-the snake. Some of the Features that Makes
Python more popular are:
• Python is Simple and Easy to learn and code.
• Python is Free and Open Source. It is freely available at the
[Link] Python source code is also available to the public,
one can download it, use it, and share it.
• Python is High Level Language and supports both Procedure oriented and
Object-Oriented Language concepts along with dynamic memory
management.
• Python is portable. Python code can be run on any platforms like Linux, Unix,
Mac and Windows.
• Python is extensible and integrated. Python code can be extended and
integrated with among other languages like C, C++, Java, etc.
• Python is an interpreted language. Python code is executed line by line at a
time and there is no need to compile, which makes debugging easier. The
• Python has rich set of libraries for data analytics, machine learning, artificial
intelligence, deep learning, mathematical computation, web app
development, mobile app development, testing, etc.
• Python is a dynamically typed language. Here the data type for variable is
decided at run time. As a result, there is no need to specify the type of
variable.
Python Programming is a fun, creative and rewarding activity. Python is one of the
most widely used programming language across the world for developing software
applications. It is named as one of top picked programming languages of most of
the universities and industries. Python developer is one of the “10 Most in Demand
Tech Jobs of 2019”[ Source : [Link] ] As of February 23,
2|Page
[Link]
2019, the average salary for a Python developer is $123,201 per year in the
United States, making it one of the most popular and lucrative careers today
[source: [Link]
Python can be used on the following:
1. Multiple Programming Paradigms
2. Web Testing
3. Data Extraction
4. Artificial Intelligence
5. Machine Learning
6. Data Science
7. Web Application and Internet Development
8. Cybersecurity
Entering expressions into the Python interactive shell allows you to evaluate and
execute code in real-time. You can use the shell as a convenient way to test and
experiment with Python code. Here are some examples of entering expressions into
the Python interactive shell:
Arithmetic Operations:
You can perform basic arithmetic operations, such as addition, subtraction,
multiplication, and division, directly in the shell. For example:
>>> 2 + 3
5
>>> 4 * 5
20
>>> 10 / 3
3.3333333333333335
3|Page
[Link]
Variable Assignment:
You can assign values to variables and use those variables in expressions. For
example:
>>> x = 5
>>> y = 2
>>> x + y
7
>>> x * y
10
Function Calls:
You can call built-in functions or user-defined functions within the shell. For
example:
>>> abs(-10)
10
>>> len("Hello, World!")
13
>>> def add(a, b):
... return a + b
...
>>> add(3, 4)
7
Boolean Expressions:
You can use boolean operators like and, or, and not to evaluate logical expressions.
For example:
>>> True and False
False
>>> True or False
True
>>> not True
False
Conditional Statements:
You can use conditional statements like if, elif, and else to perform different actions
based on conditions. For example:
>>> x = 10
4|Page
[Link]
>>> if x > 0:
... print("Positive")
... elif x < 0:
... print("Negative")
... else:
... print("Zero")
...
Positive
Examples :
x = 10 # integer
y = 3.14 # floating-point number
z = 2 + 3j # complex number
name = "John" # string
message = 'Hello, World!' # string
is_true = True # Boolean Value
is_false = False
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
coordinates = (10, 20)
person = ("John", 30, "USA")
student = {"name": "John", "age": 20, "grade": "A"}
5|Page
[Link]
type() function :
In Python, the type() function is used to determine the type of a given object or
value. It returns the data type of the object as a result. The type() function is
particularly useful when you need to programmatically determine the type of a
variable or check if a value belongs to a specific data type. Here's an example:
Example: 1,2 and “Hello, World!”. Types are the data types to which the Values
belong.
type(arg) function returns the data type of the argument as illustrated below :
x=5
y = 3.14
name = "John"
is_true = True
fruits = ["apple", "banana", "orange"]
student = {"name": "John", "age": 20}
6|Page
[Link]
Data types
In Python, data types represent the classification or categorization of values. Each
data type defines the operations that can be performed on the values, the storage
format, and the behavior of the values. Python supports several built-in data types.
Here are the commonly used data types supported in Python, along with examples:
str: Strings represent sequences of characters enclosed in single quotes (' ') or
double quotes (" ").
Example: name = "John"
list: Lists are ordered collections of items enclosed in square brackets ([]). They can
contain values of any type and are mutable.
Example: fruits = ["apple", "banana", "orange"]
tuple: Tuples are similar to lists but are enclosed in parentheses (()). They are
immutable, meaning their values cannot be changed once defined.
Example: coordinates = (10, 20)
7|Page
[Link]
Mapping Data Type:
None Type:
None: The None type represents the absence of a value or a null value. It is often
used to indicate the absence of a meaningful result.
Example: result = None
String Concatenation:
8|Page
[Link]
In this example, the + operator is used to concatenate the strings greeting, a space
(" "), and name, resulting in the string "Hello John". The concatenated string is then
stored in the message variable and printed.
String Replication:
String replication allows you to repeat a string multiple times. In Python, you can
replicate a string by using the * operator. Here's an example:
fruit = "apple"
repeated_fruit = fruit * 3
print(repeated_fruit) # Output: appleappleapple
In this example, the * operator is used to replicate the string "apple" three times,
resulting in the string "appleappleapple". The replicated string is stored in the
repeated fruit variable and printed.
word = "Hi"
punctuation = "!"
greeting = word * 3 + punctuation
print(greeting) # Output: HiHiHi!
9|Page
[Link]
Variables:
A variable is a name that refers to a value. In Python, a variable is a named storage
location that holds a value. It allows you to assign values to identifiers and refer to
those values by using the identifiers later in the program. An assignment statement
creates new variables as illustrated in the example below:
x = 10
In this example, the value 10 is assigned to the variable x. Now, x holds the value
10, and you can refer to it later in the program.
Examples:
To know the type of the variable one can use type () function. Ex: type(p)
To display the value of a variable, you can use a print statement:
Ex: print (Si) ; print(pi)
10 | P a g e
[Link]
Table: Valid Variable Names and Invalid Variable Names
Valid Variable Names Invalid Variable Names
python12 current- account(hyphens are not allowed)
Simple savings account (spaces are not allowed)
interest_year 4freinds (can’t begin with a number)
_rate_of_interest 1975 (can’t begin with a number)
_spam 10April_$ (cannot begin with a number and special
characters like $ are not allowed)
HAM Principle#@( special characters like # and @ are not
allowed)
account1234 ‘bear’ ( special characters like ‘ is not allowed)
Note:
Variable names are case-sensitive, meaning that velocity, VELOCITY, Velocity, and
velocity are four different variables. It is a Python convention to start your variables
with a lowercase letter.
Example 1:
x = 40
In this example, the value 10 is assigned to the variable x. The variable x now holds
the value 10, and you can use x to refer to that value throughout the program.
Example 2:
a, b, c = 1, 2, 3
In this example, the values 1, 2, and 3 are assigned to variables a, b, and c respectively.
Each value is assigned to its corresponding variable based on the order of appearance.
11 | P a g e
[Link]
Example 3:
x=5
y=3
result = x + y
In this example, the variables x and y hold the values 5 and 3 respectively. The
expression x + y is evaluated, and the result 8 is assigned to the variable result.
Example 4:
x = 10
x = x + 5 # x is updated to 15
In this example, the variable x initially holds the value 10. The expression x + 5
evaluates to 15, and that value is assigned back to the variable x.
12 | P a g e
[Link]
My First Program :
The program starts with a comment explaining the purpose of the program.
The print() function is used to display the welcome message.
The input() function is used to prompt the user to enter a word or phrase. The value
entered by the user is stored in the text variable.
13 | P a g e
[Link]
The len() function is used to determine the length of the text string, and the result is
stored in the length variable.
The program displays a message with the length of the entered text using the print()
function.
The input() function is used again to get the user's name and age. The values entered
by the user are stored in the name and age variables, respectively.
The int() function is used to convert the age value from a string to an integer.
The program calculates the user's age in 10 years by adding 10 to the age variable,
and the result is stored in the age_in_future variable.
The program displays a message with the user's name, age, and the calculated age in
10 years using the print() function.
The str() function is used to convert the age integer back to a string so that it can be
concatenated with other strings in the message variable.
The final message is displayed using the print() function.
The program demonstrates the usage of these functions: print() for displaying
messages, len() for determining the length of a string, input() for obtaining user
input, int() for converting a string to an integer, and str() for converting an integer to
a string.
Comments:
14 | P a g e
[Link]
Example:
# Printing a message
print(“ Enter your Name “)
myName = input (“ Enter Your Name”) # Read your name to myName
Example:
# It is a
# multiline
# comment
2. Using String Literals ''' at the beginning and end of multiple lines
Example:
'''
I am a
Multiline comment!
'''
The print() Function :
The print function is used to display the string value written within pair of double
quotes inside the parentheses on the screen .
The line print('The length of your name is:') means “Print out the text in the string ‘'The
length of your name is:’ . When Python executes the print statement, python interpreter
calls the print()function and the string value is being passed to the function. The value
within print() is called argument . Quotes within parentheses marks where the string
begins and ends ; they are not part of the string value.
15 | P a g e
[Link]
The input() function
This function is used to take the input from the user . Whatever the user enter as input,
input() function convert it into a string . if you enter an integer value still input()
function convert it into a string . The programmer is needed to convert it into an integer
in your code using typecasting.
Myname = input(“Enter your name”)
Programmer often want as user to enter multiple values in one line . In Python user
can take multiple values or inputs in one line by using split() method . It breaks the
given input by the specified separator. If separator is not provided then any white
space is a separator. Generally, user use a split() method to split a Python string but
one can used it in taking multiple input.
Example:
>>> x, y,z = input ("Enter three values").split()
Enter three values 2 3 4
>>> x
'2'
>>> y
'3'
>>> z
'4'
16 | P a g e
[Link]
The str() , int() and float Functions :
The str(), int(), and float() functions in Python are used to convert values between
different data types. Here's an explanation of each function with examples:
str() Function:
The str() function is used to convert a value to a string data type. It takes any valid
Python object as an argument and returns a string representation of that object. Here's
an example:
number = 10
number_str = str(number)
print(number_str) # Output: "10"
str() function can be used convert integer or floating numbers into string data type.
int() Function:
The int() function is used to convert a value to an integer data type. It can convert a
string or a float to an integer by truncating any decimal places. Here are some
examples:
number_str = "20"
number_int = int(number_str)
print(number_int) # Output: 20
float_num = 3.14
float_int = int(float_num)
print(float_int) # Output: 3
In the first example, the int() function converts the string "20" to an integer value 20.
In the second example, the int() function converts the float value 3.14 to an integer by
truncating the decimal places, resulting in the value 3.
float() Function:
The float() function is used to convert a value to a floating-point data type. It can
convert a string or an integer to a float. Here's an example:
number_str = "3.14"
number_float = float(number_str)
print(number_float) # Output: 3.14
17 | P a g e
[Link]
integer_num = 10
integer_float = float(integer_num)
print(integer_float) # Output: 10.0
In the first example, the float() function converts the string "3.14" to a floating-point
value 3.14. In the second example, the float() function converts the integer value 10 to
a float value 10.0.
These functions are useful when you need to convert values between different data
types in Python. They allow you to perform operations and manipulate values in the
desired format.
18 | P a g e
[Link]
Order of operations
• When more than one operator appears in an expression, the order of
evaluation depends on the rules of precedence.
PEMDAS order of operation is followed in Python:
• Parentheses have the highest precedence and can be used to force an
expression to evaluate in the order you want.
• Exponentiation has the next highest precedence,
• Multiplication and Division have the same precedence, which is higher than
• Addition and Subtraction, which also have the same precedence.
• Operators with the same precedence are evaluated from left to right.
19 | P a g e
[Link]
Python interpreter evaluates parts of the expression as per the PEMDAS rule until
it becomes a single value as illustrated below:
(5-2)*((8+4)/(5-2))
3 * ((8+4)/(5-2))
3*(12/(5-2))
3*(12/3)
3*4.0
12.0
Note: If you type invalid expressions, python interpreter will not be able to
understand it and will display a SyntaxError message as illustrated below:
20 | P a g e
[Link]
Python Tokens:
A token (lexical unit) is the smallest element of Python script that is meaningful to
the interpreter. Python has following categories of tokens: Identifiers, Keywords,
Literals , operators and delimiters.
Identifiers: Identifiers are names that you give to a variable, class or Function.
There are certain rules for naming identifiers similar to the variable declaration
rules, such as : No Special character except_ , Keywords are not used as identifiers
, the first character of an identifier should be _ underscore or a character , but a
number is not valid for identifiers and identifiers are case sensitive .
21 | P a g e
[Link]
Literals: A fixed numeric or non-numeric value is called a literal. Literals may be
string, numbers (int, long, float and complex), Boolean (True or False), NONE and
Operators.
1. Numeric literals: Numeric literals represent numeric values such as
integers, floating-point numbers, and complex numbers.
Examples: x = 10, y = 3.14, z = 2 + 3j
2. String literals: String literals represent sequences of characters enclosed
in either single quotes (') or double quotes (").
Examples: name = 'John', sage = "Hello, world!“
3. Boolean literals: Boolean literals represent the truth values True and False.
Examples: is_valid = True
4. None literal: The None literal represents the absence of a value or a null
value. It is often used to indicate the absence of a meaningful result or as an
initial value for variables.
Example: result = None
4. Operator Literals : Operator literals include arithmetic operators,
comparison operators, assignment operators, logical operators, and more.
Examples: +,-,/,//,%,*,**, <,>,!=,==,and,or,not,etc.
22 | P a g e
[Link]
Delimiters: Delimiters are the symbols which can be used as separators of values or
to enclose some values.
Examples : Comma (,),Colon (:),Parentheses (( and )),Square brackets ([ and
]),Curly braces ({ and }),Quotation marks (' and ") and Backslash (\)
Note : Comments and # symbol used to insert a comment is not a token.
Keywords: The reserved words of Python which have a special fixed meaning for
the interpreter are called keywords. No keyword can be used as an identifier or
variable names. There are 35 keywords in python as listed below:
Keyword Description
and Logical and operator
as Alias
assert Used for debugging
async Used to make a function asynchronous by adding the async keyword before the
function’s regular definition
await Used in asynchronous functions to specify a point in the function where control is
given back to the event loop for other functions to run. You can use it by placing
the await keyword in front of a call to any async function
break To break out of a loop
class To define a class
continue For skipping the statements and conitinuing the next iteration
def For defining user defined functions
del To delete an object
elif Conditional statement, same as else if
else Conditional statement
except Used in exception handling
False Boolean Value
finally Used in exception handling , to execute a block of code no matter whether
exception is there or not
for Used to create for loop – iterative statement
from Used to import specific parts of a module
global Used to declare global variable
if Conditional /decision making statement
import Used to import a module or library
in Used to check if a value if present in list, tuple, dictionaries , sets ,etc.
is To check if two variables are equal
lambda Used for defining an anonymous function
None Used to represent a null value
nonlocal To declare a non-local variable
23 | P a g e
[Link]
not A logical operator
or A logical operator
pass A null statement , a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean Value
try Used in exception handling
while For creating a while iterative loop
with Used to simplify exception handling
yield To end a function , returns a generator
Following code segment can be used to obtain the list of python keywords :
import keyword
# Get the list of keywords
print([Link])
print("\n Total Number of Keywords: ",len([Link]))
# Output :
['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Total Number of Keywords: 36
24 | P a g e
[Link]
Simple Python Programs
1. To perform basic calculations
# Sample numbers
num1 = int(input("Enter first number"))
num2 = int(input("Enter second number"))
# output
Enter first number 3
Enter second number 2
Sum: 5
Product: 6
25 | P a g e
[Link]
Difference: 1
Division: 1.5
Integer Division: 1
Modulo Division: 1
# output
Enter the radius of the circle: 2.5
The area of the circle is: 19.634954084936208
3. To find the simple interest
# Take input for principal amount, rate, and time
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the interest rate: "))
time = float(input("Enter the time period (in years): "))
# Output
Enter the principal amount: 10000
Enter the interest rate: 2.5
Enter the time period (in years): 3
The simple interest is: 750.0
26 | P a g e
[Link]
Questions for Practice:
27 | P a g e
[Link]
[Link] the working and usage of input() function with examples.
[Link] example to read multiple values using input().
[Link] operands and operators. Discuss PEMDAS rules with examples.
[Link] are keywords? How many keywords are there in current version of
Python?
[Link] a program to display all keywords in the current version of Python.
[Link] are Python comments? Explain their importance with programming
examples.
[Link] print () , input() and split() functions with example.
[Link] a program for the following:
1. To read and print a single value in a single line
2. To read and print multiple values in a single line
32. Explain the following different types of errors: Syntax errors, Semantic errors
and Logic Errors.
[Link] the following functions with example: len() , str() , int() , float()
[Link] the out put and justify your answer: (i) -11%9 (ii) 7.7//7 (iii) (200 –
70)*10/5 (iv) not “False” (v) 5*|**2
[Link] the rules to describe a variable in Python. Demonstrate at least three
different types of variables uses with an example program.
[Link] the following :
1. Skills necessary for a programmer
2. Interactive Mode
3. Short circuit evaluation of expression
4. Modulus operator.
[Link] three types of errors encountered in python program.
[Link] the following with example : Values and Types , Variables , Expressions ,
Keywords , Statements , Operators and Operands, Order of Operations ,
Modulus Operators , String operations and Comments.
[Link] three functions can be used to get the integer, floating-point number, or
string version of a value?
28 | P a g e
[Link]
Programs for Practice:
Write and execute python programs for the following :
1. To prompt a user for their name and then welcomes them.
2. To prompt a user for days and rate per day to compute gross salary.
3. To read the following input and display :
a. Name :
b. USN:
c. Roll No:
d. Mobile No:
e. E-Mail Id:
f. Percentage of Marks:
4. To find the simple interest for a given value of P, T and R. Program should
take input from the user.
5. To find the compound interest.
6. To read two integers and find the sum, diff, mult and div.
7. To Convert given Celsius to Fahrenheit temperature.
8. To print ascii value of a character.
9. To display all the keywords.
[Link] print the following string in a specific format :”"Twinkle, twinkle, little
star, How I wonder what you are! Up above the world so high, Like a
diamond in the sky. Twinkle, twinkle, little star, How I wonder what you
are" .
Output :
Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are
30 | P a g e
[Link]
1.2 Flow Control
Syllabus: Boolean Values, Comparison Operators, Boolean Operators, Mixing Boolean and
Comparison Operators, Elements of Flow Control, Program Execution, Flow Control Statements,
Importing Modules, Ending a Program Early with [Link]().
Boolean Values: A Boolean value is either true or false. It is named after the British
mathematician, George Boole, who first formulated Boolean algebra. In Python the
two Boolean Values are True and False and the Python type is bool. Enter the
following into the Python shell and observe the output.
type(True) # output : bool
type(False) # output : bool
type(true) # output: Name Error : name “ true” is not defined
type(false) # output: Name Error : name “ false” is not defined
context = True
print(context) #output : True
5 == 6 # output: False
In the first statement the two operands evaluate to equal values, so the expression
evaluates to True; in the second statement, 5 is not equal to 6 we get False.
P = “hel”
P + “lo” == “hello” # output: True
In the above example since the concatenated value P + “lo” is “hello” the
expression evaluates to True .
31 | P a g e
[Link]
Comparison Operators
Comparison operators compare two values and evaluate down to a single Boolean
value. The == operator is one of six common comparison operators which all
produce a bool result. Table lists all the comparison operators:
Operator Meaning
== Equal to
!= Not Equal to
< Less than
> Greater than
<= Les than or equal to
>= Greater than or equal to
Boolean Operators:
Boolean operators evaluate the expression to Boolean Values True/False. Python
supports three Boolean operators and, or & not. Based on the number of operands
required they can be classified into Binary Boolean operators and Unary Boolean
Operators.
Binary Boolean operators : and & or
Since both and & or operators takes two operands, they are considered as binary
operators. The and operator returns true value if both operands are true and return
false otherwise. While or operator returns false when both operands are false and
returns true otherwise.
True and True # output : True
True and False # output : False
False and True # output : False
False and False # output :False
33 | P a g e
[Link]
Following truth tables illustrates all possible logical combinations and values for OR
and AND Boolean binary operators.
Not operator: It is a unary operator and evaluates the expression to opposite value
true or false as illustrated below :
not True # output : False
not False # output : True
not not not not True # output : True
Examples for Mixing Boolean and Comparison Operators: Boolean operators and
comparison operators can be used in combination as illustrated below :
x = 10
y = 20
x<y and x>y # output : False
(x<y) and (x!=y) or (x*2) and (x<20 or y<20) # output : True
2+2 == 4 and not 2+2 == 5 and 2*2 == 2+2 #output : True
5*7 +8 == 7 or not 5+7 ==10 and 5*4 ==20 #output : True
34 | P a g e
[Link]
Elements of Flow Control:
Flow control statements often starts with condition followed by a block of code
called clause. The two elements of Flow Control are discussed below:
a) Conditions:
Conditions are Boolean expressions with the boolean values True or False. Flow
control statements decides what to do based on the condition whether it is true or
false.
Example 1:
x = int(input(“Enter a number: “)) # Block
if x>=10: # Condition
x = x + 25 # Block belonging to if
y=x
print(x,y)
print(“Next statement”) # Next Block
35 | P a g e
[Link]
Flow Control statements
Flow control statements in Python are used to control the order of execution and
make decisions based on certain conditions. The main flow control statements in
Python include:
Conditional Control Statements:
• if statement: Executes a block of code if a specified condition is true.
• elif statement: Allows you to check additional conditions if the previous if or
elif conditions are false.
• else statement: Executes a block of code if none of the previous conditions
are true.
Looping Statements:
• for loop: Iterates over a sequence (such as a list, tuple, string, or range) and
executes a block of code for each item in the sequence.
• while loop: Repeats a block of code as long as a specified condition is true.
36 | P a g e
[Link]
Types of Condition Control Statements
1. if statement:
It is basically a two-way decision statement and it is used in conjunction
with an expression. It is used to execute a set of statements if the condition
is true. If the condition is false it skips executing those set of statements.
The syntax and flow chart of if statement is as illustrated below:
Entry
False
Is Condition?
True
S1
S2
S3
---
Sn
Sn+1
37 | P a g e
[Link]
Example1: Python program to find the largest number using if statement.
2. If else statement:
38 | P a g e
[Link]
True False
Is
Condition?
Statement x
Example: Program to check whether a given number is even or odd using if else.
3. Nested if else:
When a series of decisions are involved, we may have to use more than one if else
statement in nested form. The nested if else statements are multi decision statements
which consist of if else control statement within another if or else section. The syntax
and flow diagram for nested if else is as shown below:
39 | P a g e
[Link]
False
True
Cond1
True False
False True
Cond3 Cond2
S3 S4 S2 S1
Statement x
Fig : Syntax and flow diagram for nested if else statement
Example:
40 | P a g e
[Link]
4. if – elif ladder:
Cascaded if elif else is a multipath decision statements which consist of chain of
if elseif where in the nesting take place only in else block. As soon as one of the
conditions controlling the ‘if’ is true , then statement /statements associated with
that ‘if’ are executed and the rest of the ladder is bypassed. If condition is false
then it checks the first elif condition , if it is found true then first elif is executed.
However, if none of the elif ladder is correct then the final else statement will be
executed and control flows from top to down.
The syntax and flow diagram for cascaded if else is as shown in figure.
Syntax
T F
if C1: C1
S1 F
elif C2: T C2
S2 S1
elif C3: S2
T F
S3 C3
elif C4:
S3
S4
T
------- Cn
elif Cn:
F
Sn
else: Sn
default
default stmnt statement
Statement x;
Statement x
41 | P a g e
[Link]
Example:
3. Iteration or looping:
The statement which are used to repeat a set of statements repeatedly for a given
number of times or until a given condition is satisfied is called as looping
constructs or looping statements. The set or block of statements used for looping
is called loop.
Types of Looping statements:
Depending on the position of the control statement in the loop the looping
statements are classified into the following two types:
1. Entry controlled Loop
2. Exit Controlled Loop
42 | P a g e
[Link]
1. Entry Controlled Loop: In the entry-controlled loop the control conditions
are tested before the start of the loop execution. If the conditions are not satisfied,
then the body of the loop will not be executed. It is also known as pretest loop or
top test loop. The flow chart for the entry controlled loop is as illustrated in fig .
FALSE
Is
Condition?
TRUE
Body of the
Loop
[Link] Controlled Loop: In the exit controlled loop the test is performed at the
end of the body of the loop and therefore the body is executed unconditionally
for the first time. It is also known as posttest loop. Here the body of the loop will
get executed at least once before [Link] flow chart for the exit controlled
loop is as illustrated in fig .
43 | P a g e
[Link]
Body of the
Loop
TRUE
Is
Condition?
FALSE
44 | P a g e
[Link]
The while statement: It is an entry controlled loop statement. In case of while
loop the initialization, testing the condition and incrementation or updation is
done in separate statements. First initialization of the loop counter is
[Link] the condition is checked. If the condition evaluates to be true
then the control enters the body of the loop and executes the statements in the
body.
initialization
45 | P a g e
[Link]
While statement in Python executes a block of code repeatedly as long as the
test/control condition of the loop is true. The control condition of the while loop is
executed before any statement in the body of the loop is executed . If the condition
is true, the body of the loop is executed. Again, the control condition of the loop is
tested, and the loo continue as long as the condition remains true. When the test
outcome of this condition remains true. When the test outcome of this condition
becomes false, the loop is not entered again and the control is transferred to the
statement immediately following the body of the loop as shown in the flow
diagram.
Example: Program to find the sum of n natural numbers using while loop.
For loop:
The for loop is another entry-controlled loop. It is used to execute the set of
statements repeatedly over a range of values or a sequence. With every iteration of
the loop, the control variable checks whether each of the values in the range has been
traversed or not. When all the items in the range are traversed the control is then
transferred to the statement immediately following for loop.
46 | P a g e
[Link]
Syntax of for loop :
Flow Chart:
47 | P a g e
[Link]
range ( ) function: The range() function returns a sequence of numbers, starting
from 0 to a specified number ,incrementing each time by 1.
Syntax :
range(start,step,stop)
Example:
48 | P a g e
[Link]
The argument of range() function must be integers. The step parameter can be any
positive or negative integer other than zero.
Infinite Loop: A loop becomes infinite loop if a condition never becomes FALSE.
You must use caution when using while loops because of the possibility that this
condition never resolves to a FALSE value. This results in a loop that never ends.
Such a loop is called an infinite loop.
An infinite loop might be useful in client/server programming where the server
needs to run continuously so that client programs can communicate with it as and
when required.
Nested Loops:
Python programming language allows to use one loop inside another loop.
49 | P a g e
[Link]
Example:
50 | P a g e
[Link]
Jump statements:
You might face a situation in which you need to exit a loop completely when an
external condition is triggered or there may also be a situation when you want to
skip a part of the loop and start next execution.
Python provides break and continue statements to handle such situations and to
have good control on your loop.
The break statement in Python terminates the current loop and resumes
execution at the next statement, just like the traditional break found in C.
The most common use for break is when some external condition is triggered
requiring a hasty exit from a loop. The break statement can be used in
both while and for loops.
The continue statement in Python returns the control to the beginning of the while
loop. The continue statement rejects all the remaining statements in the current
iteration of the loop and moves the control back to the top of the loop.
51 | P a g e
[Link]
The continue statement can be used in both while and for loops.
Example:
52 | P a g e
[Link]
Example :
The following example illustrates the combination of an else statement with a for
statement that searches for prime numbers from 10 through 20.
Similar way you can use else statement with while loop.
53 | P a g e
[Link]
54 | P a g e
[Link]
Importing Modules
Python function definition can, usefully, be stored in one or more separate files for
easier maintenance and to allow them to beused in several programs without
copying the definitions into each one. Each file storing function definitions is called
a “module” and the module name is the file name with “.py” extension.
Example:
Functions stored in the module are made available to a program using the Python
import keyword followed by the module name. Although not essential, it is
customary to put any import statements at the beginning of the program.
Imported functions can be called using their name dot -suffixed after the module
name. For example, a “f1()” function from an imported module named
“userdefined” can be called with userdefined.f1() .
Design a new Python module called userdefined by defining all functions as
illustrated below. Save the file as [Link] and run the file.
[Link]
Start a new script with name [Link] (/ipynb). Next call each function
with and without arguments as per the requirements. Run the program and get the
output as illustrated below:
55 | P a g e
[Link]
Importing Modules:
Python includes “sys” and “keyword” modules that are useful for interrogating the
Python system itself. The keyword module contains a list of all Python keywords in
its kwlist attribute and provides as iskeyword () method if you want to rest a word.
56 | P a g e
[Link]
57 | P a g e
[Link]
Performing Mathematics
Random
58 | P a g e
[Link]
Ending a Program Early with [Link] ()
59 | P a g e
[Link]
Questions for Practice:
[Link] is Flow Chart ? Give the meaning of different flow chart
symbols.
[Link] a Flow chart and Python program for the following:
a. To find the average of two numbers.
b. To find the simple interest given the value of P,T and R
c. To find the maximum of two numbers
d. To find the sum of first 50 natural numbers
e. To find the factorial of a given number N.
[Link] == and = operator.
[Link] are operators? Explain the following Operators with
example:
a. Binary Boolean Operators: and, or & not
[Link] is Flow Control? Explain the different Elements of Flow
Control?
[Link] Block and explain what nested blocks with example are.
[Link] condition control statement. Explain the different types of
Condition Control Statement.
[Link] with flow chart and programming example , the following
condition control statements :
a. if
b. if – else
c. nested if else
d. if – elif ladder
[Link] is iteration or looping ? Describe the different types of
looping statements.
[Link] with syntax , flow chart and programming example the
following looping operations.
a. While loop
b. For loop
60 | P a g e
[Link]
[Link] the working of range() function with programming
example.
[Link] the output of the following :
a. range(10)
b. range(1,11)
c. range(0,30,5)
d. range(0,-9,-1)
[Link] is infinite loop ? Explain with example.
[Link] are nested Loops ? Explain with examples.
[Link] the following with examples :
a. break
b. continue
c. else statement with loop
d. pass
[Link] are Python Modules ? Explain with examples how to import
Python Modules .
[Link] is the difference between break and continue statements.
[Link] is the purpose of else in loop?
[Link] logical expressions for the following :
a. Either A is greater than B or A is less than C
b. Name is Snehith and age is between 18 and 35.
c. Place is either Mysore or Bengaluru but not “Dharwad”.
[Link] the following while loop into for loop :
x =10
while (x<20):
print(x+10)
x+=2
[Link] while and for loop . Write a program to generate
Fibonacci series upto the given limit by defining FIBONACCI(n)
function.
61 | P a g e
[Link]
[Link] the advantage of continue statement. Write a program
to compute only even numbers sum within the given natural
number using continue statement.
[Link] the use of break and continue keywords in looping
structures using a snippet code.
[Link] syntax explain the finite and infinite looping constructs in
python. What is the break and continue statements .[ VTU June
/July 2019]
62 | P a g e
[Link]
[Link] a program to find the best of two test average marks out of
three tests marks accepted from the user.
[Link] a program to find the largest of three numbers . [ VTU June
/July 2019]
[Link] a program to check whether the given year is leap or not. [
VTU June /July 2019]
[Link] a program to generate and print prime number between 2
to 50.
[Link] a program to find those numbers which are divisible by 7
and multiple of 5 , between 1000 and 3000.
[Link] a program to guess a number between 1 to 10.
[Link] a program that accepts a word from the user and reverse it.
[Link] a program to count the number of even and odd numbers
from a series of numbers.
[Link] a program that prints all the numbers from 0 to 10 except
3, 7 and 10.
[Link] a program to generate Fibonacci series between 0 and 50.
[Link] a program which iterates the integers from 1 to 50. For
multiple of three print “Fizz” instead of the numbers and fro the
multiples of five print “Buzz” . For numbers which are multiples of
both three and five print “FizzBuzz”.
[Link] a program that accepts a string and calculate the number
of digits and letters.
[Link] a program to check the validity of password input by users.
[Link] a program to find the numbers between 100 and 400
where each digit of a number is an even number . The numbers
obtained should be printed in a comma-separated sequence.
[Link] a program to print alphabet patterns ‘A’ ,D, ‘E’, ‘G’,’L’, ‘T’
and ‘S’ with * symbol.
63 | P a g e
[Link]
[Link] a python program to create the multiplication table (from 1
to 20) of a number.
[Link] a program to print the following patterns :
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
1
22
333
4444
55555
666666
7777777
88888888
999999999
*
* *
* * *
* * * *
* * * * *
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
64 | P a g e
[Link]
A
B B
C CC
D DDD
E EEEE
* * * * *
* * * *
* * *
* *
*
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
65 | P a g e
[Link]
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1
2 3
4 5 6
7 8 9 10
66 | P a g e
[Link]
1.3 Functions
1.3.1 Introduction
A function is a group (or block ) of statements that perform a specific task .
Functions run only when it is called. One can pass data into the function in the form
of parameters. Function can also return data as a result. Instead of writing a large
program as one long sequence of instructions , it can be written as several small
function , each performing a specific part of the task . They constitute line of code(s)
that are executed sequentially from top to bottom by Python interpreter. A python
function is written once and is used / called as many time as required . Functions
are the most important building blocks for any application in Python and work on
the divide and conquer approach. Functions can be conquered into the following
three types :
(i) User Defined
(ii) Built in
(iii) Modules
67 | P a g e
[Link]
Statements below def begin with four spaces. This is called indentation. It is a
requirement of Python that the code following a colon must be indented. A
function definition consists of the following components;
1. Keyword def marks the start of function header
2. A function name to uniquely identify it. Function naming follows the same
rules as rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function . They
are optional.
4. A colon (: ) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function
does.
6. One or more valid Python statements that make up the function body.
Statements must have same indentation level (usually) 4 spaces)
7. An optional return statement to return a value from the function .
Example :
def cube(n):
ncube = n**3
return ncube
fun_name(parameter list)
Example: cube(3)
68 | P a g e
[Link]
Parameters and arguments
Parameters are temporary variable names within functions. The argument can be
thought of as the value that is assigned to that temporary variable.
• 'n' here is the parameter for the function 'cube'. This means that
anywhere we see 'n' within the function will act as a placeholder until
number is passed an argument.
• Here 3 is the argument.
• Parameters are used in function definition and arguments are used in
function call.
Working of function
69 | P a g e
[Link]
Example 2 : Function with parameters but without returning values.
70 | P a g e
[Link]
Example 4: Function which return multiple values
The None-Value
In Python there is a value called None, which represents the absence of a value. None is the only
value of the None Type data type. (Other programming languages might call this value null, nil,
or undefined.) Just like the Boolean True and False values, None must be typed with a capital N.
71 | P a g e
[Link]
Keyword Arguments and print()
Keyword arguments are identified by the keyword put before them in the function
call. Keyword arguments are often used for optional parameters. For example, the
print( ) function has the optional parameters end and sep to specify what should be
printed at the end of its arguments and between its arguments (separating them),
respectively. Following examples illustrates the behavior of print with end , without
end and with sep.
72 | P a g e
[Link]
1.3.6 Local and Global Scope
Parameters and variables that are assigned in a called function are said to exist in
that function’s local scope. Variables that are assigned outside all functions are said
to exist in the global scope. A variable that exists in a local scope is called a local
variable, while a variable that exists in the global scope is called a global variable. A
variable must be one or the other; it cannot be both local and global. Following
example illustrates the difference between local and global variable .
If you run this program the output will look like this
73 | P a g e
[Link]
The error happens because the x variable exists only in the local scope created
when fun1() is called. Once the program execution returns from fun1(), that local
scope is destroyed, and there is no longer a variable named x. So when your
program tries to run print(x), Python gives you an error saying that x is not defined.
This makes sense if you think about it; when the program execution is in the global
scope, no local scopes exist, so there can’t be any local variables. This is why only
global variables can be used in the global scope.
Local Scopes Cannot Use Variables in Other Local Scopes
A new local scope is created whenever a function is called, including when a
function is called from another function. Consider this program:
When the program starts the func1() is called and a local scope is created . The local
variable x is set to 10. Then fun2() is called and a second local scope is created .
Multiple local scopes can exist at the same time . In this new local scope , the local
variable y is set to 21 and a local variable x which is different from the one in fun1()’s
local scope is also created and set to 0. When fun2() returns the local scope for the
call to fun1() still exists here the x variable is set to 10. This is what the programs
prints.
The local variables in one function are completely separate the local variable in
another function.
74 | P a g e
[Link]
Since there is no parameter named x or any code that assigns x a value in the fun1()
function , when x is used in fun1(), Python considers it a reference to the global
variable x. This is why 42 is printed when the previous program is run.
75 | P a g e
[Link]
There are actually three different variables in this program, but confusingly they are
all named x.
A variable named x that exists in a local scope when fun1() is called.
A variable named x that exists in a local scope when fun2() is called
A variable named x that exists in the global scope
Since these three separate variables all have the same name, it can be confusing
to keep of which one is being used at any given time . This is why you should
avoid using the same variable name in different scopes.
Global Statement
If you need to modify a global variable from within a function , used the global
statement . If you have a line such as global x at the top of a function , it tells
Python, In this function, x refers to the global variable, so don’t create a local
variable with this name.” For example, type the following code and run
When you run this program the final print() call will output this :
Because x is declared global at the top of spam() , when x is set to 'spam' , this
assignment is done to the globally scoped x. No local x variable is created.
There are four rules to tell whether a variable is in a local scope or global scope:
1. If a variable is being used in the global scope (that is, outside of all functions),
then it is always a global variable.
2. If there is a global statement for that variable in a function, it is a global
variable.
76 | P a g e
[Link]
3. Otherwise, if the variable is used in an assignment statement in the function, it
is a local variable.
4. But if the variable is not used in an assignment statement, it is a global variable.
Exceptional Handling
Right now, getting an error, or exception, in your Python program means the entire
program will crash. You don’t want this to happen in real-world programs. Instead,
you want the program to detect errors, handle them, and then continue to run. For
example, consider the following program, which has a “divide-byzero” error. Open
a new file editor window and enter the following code, saving it as [Link]:
We’ve defined a function called spam, given it a parameter, and then printed the value of that function
with various parameters to see what happens. This is the output you get when you run the previous
code:
A ZeroDivisionError happens whenever you try to divide a number by zero. From the line number given
in the error message, you know that the return statement in spam() is causing an error.
77 | P a g e
[Link]
Errors can be handled with try and except statements. The code that could potentially have an error is
put in a try clause. The program execution moves to the start of a following except clause if an error
happens. You can put the previous divide-by-zero code in a try clause and have an except clause contain
code to handle what happens when this error occurs.
When code in a try clause causes an error, the program execution immediately moves to the code in the
except clause. After running that code, the execution continues as normal. The output of the previous
program is as follows:
Note that any errors that occur in function calls in a try block will also be caught. Consider the following
program, which instead has the spam() calls in the try block:
78 | P a g e
[Link]
When this program is run, the output looks like this:
The reason print(spam(1)) is never executed is because once the execution jumps to the code in the
except clause, it does not return to the try clause. Instead, it just continues moving down as normal.
ascii() Returns a readable version of an object. Replaces none-ascii characters with escape character
delattr() Deletes the specified attribute (property or method) from the specified object
divmod() Returns the quotient and the remainder when argument1 is divided by argument2
79 | P a g e
[Link]
float() Returns a floating point number
map() Returns the specified iterator with the specified function applied to each item
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
80 | P a g e
[Link]
slice() Returns a slice object
iii. Modules :
As the programs become more lengthy and complex, there arises a need for the
tasks to be split into smaller segments called modules.
A module is a file containing functions and variable defined in separate files. A
module is simply a file that contains Python code or a series of instructions . When
we break a program into modules , each module should contain functions that
performs related tasks . There are some commonly used modules in Python that
are used for certain predefined tasks and they are called libraries.
Modules also make it easier to reuse the same code in more than one program. If
we have written a ste of functions that is needed in several different programs , we
can place those functions that is needed in several different programs, we can place
those functions in a module. Then we can import the module in each program that
needs to call one of the functions . Once we import a module we can refer to any
of its functions or variable in our program.
A module in Python is a file that contains a collection of related functions.
81 | P a g e
[Link]
Importing Modules in a python Program
Python language provides two important methods to import modules in a
program which are as follows :
(i) Import statement : To import entire module
(ii) From :To import all functions or selected ones
(iii) Import : To use modeule in a program , we import them using the
import statement.
Syntax : import modulename1 [ modulname2,------]
It is the simplest and the most common way to use modules in our code.\
Example:
import math
On executing
Output
82 | P a g e
[Link]
83 | P a g e
[Link]
Random module (Generating random numbers)
The various functions associated with the module are explained as follows:
randrange () : This method generates an integer between its lower and upper
argument. By default, the lower argument is 0 and upper argument is 1. The
following line of code generates random numbers from 0 to 29. In this instance
it is 15.
84 | P a g e
[Link]
-Example :
Example :
Example:
Example:
85 | P a g e
[Link]
Example:
Example :
Example :
86 | P a g e
[Link]
Example :
Example :
Example :
Example :
87 | P a g e
[Link]
Sample Programs
Example1: A Short Program , Guess the Number
88 | P a g e
[Link]
Simple Project:
89 | P a g e
[Link]
Questions for Practice:
1. What are the advantages of using functions in a program?
2. When the code in the function does executes during definition or calling.
3. Discuss How to create a function with example.
4. Explain the following with example
a. Functions
b. Function Call
c. Built in Function
d. Type Conversion Functions
e. Random Numbers
f. Math Functions
g. Adding new Functions
h. Defining and using the new functions
i. Flow of execution
j. Parameter and Arguments
k. Fruitful and void Functions
l. Advantages of Functions
5. Differentiate between argument and parameter.
6. What is the difference between a function and a function call?
7. How many global scopes and local scopes are there in Python program?
8. What happens to variables in a local scope when the function call returns?
9. What is a return value? Can a return value be part of an expression?
[Link] is the return value of the function which does not have return
statement?
[Link] can you force a variable in a function to refer to the global variable?
[Link] is the data type of None?
[Link] does the import allname statement do?
[Link] you had a function named radio() in a module named car who would you
call it after importing car.
[Link] can you prevent a program from crashing when it gets an error?
[Link] goes in the try clause? What goes in the except clause?
[Link] the flow of execution of a python function with an example
program to convert given Celsius to Fahrenheit temperature.
90 | P a g e
[Link]
[Link] the function arguments in python.
[Link] call by value and call by reference in python
[Link] explain about function prototypes
[Link] the scope and lifetime of a variable in python
[Link] out the uses of default arguments in python
[Link] the uses of python module.
[Link] how a function calls another function. Justify your Apply
answer
[Link] the syntax for function call with and without arguments.
[Link] recursive function
[Link] the syntax for passing arguments.
[Link] are the two parts of function definition give the syntax
[Link] discuss in detail about function prototyping in python. With suitable
example program
[Link] the difference between local and global variables.
[Link] with an example program to circulate the values of n variables
[Link] in detail about lambda functions or anonymous function.
[Link] in detail about the rules to be followed while using Lambda
function.
[Link] with an example program to return the average of its argument
[Link] the various features of functions in python.
[Link] the syntax and rules involved in the return statement in python.
[Link] a program to demonstrate the flow of control after the return
statement in python.
[Link] with an example program to pass the list arguments to a
function.
[Link] a program to perform selection sort from a list of numbers using
python.
[Link] the use of return () statement with a suitable example.
[Link] are the advantages and disadvantages of recursion function? A
[Link] the types of function arguments in python
[Link] recursive function. How do recursive function works? Explain with a
help of a program
[Link] the concept of local and global variables.
91 | P a g e
[Link]
45.A polygon can be represented by a list of (x, y) pairs where each pair is a
tuple: [ (x1, y1), (x2, y2), (x3, y3) , … (xn, yn)]. Write a Recursive function to
compute the area of a polygon. This can be accomplished by “cutting off” a
triangle, using the fact that a triangle with corners (x1, y1), (x2, y2), (x3, y3)
has area (x1y1 + x2y2 + x3y2 – y1x2 –y2x3 – y3x1) / 2.
[Link] is a lambda function?
[Link] Do We Write A Function In Python?
[Link] Is “Call By Value” In Python?
[Link] Is “Call By Reference” In Python?
[Link] It Mandatory For A Python Function To Return A Value? Comment?
[Link] Does The *Args Do In Python?
[Link] Does The **Kwargs Do In Python?
[Link] Python Have A Main() Method?
[Link] Is The Purpose Of “End” In Python?
[Link] Does The Ord() Function Do In Python?
[Link] are split(), sub(), and subn() methods in Python?
[Link] the syntax for the following functions and explain with an
example: a) abs() b) max() c) divmod() d) pow() e) len()
92 | P a g e
[Link]
evenly divided by 1 and 5. The number 6, however, is not prime because it
can be divided by 1, 2, 3, and 6.
8. Write a function named isPrime, which takes an integer as an argument and
returns True if the argument is a prime number, and False otherwise.
Define a function main() and call isPrime() function in main() to display a list
of the prime numbers from 100 to 500.
9. Write a program that lets the user perform arithmetic operations on two
numbers. Your program must be menu driven, allowing the user to select
the operation (+, -, *, or /) and input the numbers. Furthermore, your
program must consist of following functions:
1. Function showChoice: This function shows the options to the user and explains how
to enter data.
2. Function add: This function accepts two number as arguments and returns sum.
3. Function subtract: This function accepts two number as arguments and returns their
difference.
4. Function mulitiply: This function accepts two number as arguments and returns
product.
5. Function divide: This function accepts two number as arguments and returns
quotient.
Define a function main() and call functions in main().
93 | P a g e
[Link]
m. That prints out the first n rows of Pascal's triangle.
n. To check whether a string is a pangram or not.
[Link] a Python program that accepts a hyphen-separated sequence of
words as input and prints the words in a hyphen-separated sequence after
sorting them alphabetically.
[Link] a Python function to create and print a list where the values are
square of numbers between 1 and 30 (both included).
[Link] a Python program to make a chain of function decorators (bold, italic,
underline etc.) in Python.
[Link] a Python program to execute a string containing Python code
[Link] a Python program to access a function inside a function
[Link] a Python program to detect the number of local variables declared in
a function.
17. Write a function calculation() such that it can accept two variables and
calculate the addition and subtraction of it. And also it must return both
addition and subtraction in a single return call
[Link] a function showEmployee() in such a way that it should accept
employee name, and it’s salary and display both, and if the salary is missing
in function call it should show it as 9000
[Link] an inner function to calculate the addition in the following way
a. Create an outer function that will accept two parameters a and b
b. Create an inner function inside an outer function that will calculate
the addition of a and b
c. At last, an outer function will add 5 into addition and return it
[Link] a recursive function to calculate the sum of numbers from 0 to 10
[Link] a function to calculate area and perimeter of a rectangle.
[Link] a function to calculate area and circumference of a circle.
[Link] a function to calculate power of a number raised to other. E.g.- ab.
[Link] a function to tell user if he/she is able to vote or not.( Consider
minimum age of voting to be 18. )
[Link] multiplication table of 12 using recursion.
[Link] a function to calculate power of a number raised to other ( ab ) using
recursion.
[Link] a function “perfect()” that determines if parameter number is a
perfect number. Use this function in a program that determines and prints
all the perfect numbers between 1 and 1000.[An integer number is said to
94 | P a g e
[Link]
be “perfect number” if its factors, including 1(but not the number itself),
sum to the number. E.g., 6 is a perfect number because 6=1+2+3].
[Link] a function to check if a number is even or not.
[Link] a function to check if a number is prime or not.
[Link] a function to find factorial of a number but also store the factorials
calculated in a dictionary as done in the Fibonacci series example.
31. Write a function to calculate area and perimeter of a rectangle.
[Link] is the output of the following Code ?
def foo(u, v, w=3):
return u * v * w
def bar(x):
y = 4
return foo(x, y)
print(foo(4,5,6))
print(bar(10))
def change(t1,t2):
t1 = [100,200,300]
t2[0]= 8
list1 = [10,20,30]
list2 = [1,2,3]
change(list1, list2)
print(list1)
print(list2)
x = [10,20,30]
y = [1,2,3,4]
dot(x,y)
95 | P a g e
[Link]
def buz(arr, n):
for i in range(n-1):
if arr[i]>arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
print(arr)
def bar(arr,n):
for i in range(n-1):
buz(arr,n-i)
t = [19,7,4,1]
bar(t,len(t))
n1 = 150
n2 = 100
change(n1,n2)
change(n2)
change(num2=n1,num1=n2)
96 | P a g e
[Link]