Introduction to Python Programming (BPLCK105B)
VTU Question Paper Solution
MODULE 1 SOLUTION
1. Explain elif, for, while statements in Python with examples for each.
a) elif
While only one of the if or else clauses will execute, we may have a case where we want
one of many possible clauses to execute.
It provides another condition that is checked only if all of the previous conditions were
False.
In code, an elif statement always consists of the following:
• The elif keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the elif clause)
Meghashree, CSE (ICSB) PA College of Engineering Page 1
Introduction to Python Programming (BPLCK105B)
b) for
If we want to execute a block of code only a certain number of times then we can do this with
a for loop statement and the range() function.
➢ In code, a for statement looks something like for i in range (5):
1. The for keyword
2. A variable name
3. The in keyword
4. A call to the range() method with up to three integers passed to it
5. A colon
6. Starting on the next line, an indented block of code (called the for clause)
Meghashree, CSE (ICSB) PA College of Engineering Page 2
Introduction to Python Programming (BPLCK105B)
c) while loop
We can make a block of code execute over and over again with a while statement
➢ The code in a while clause will be executed as long as the while statement‘s condition is True.
➢ In code, a while statement always consists of the following:
1. The while keyword
2. A condition (that is, an expression that evaluates to True or False.
3. A colon
4. Starting on the next line, an indented block of code (called the while clause)
Ex:
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
Meghashree, CSE (ICSB) PA College of Engineering Page 3
Introduction to Python Programming (BPLCK105B)
2. List and explain math operators used in Python with examples.
The order of operations (precedence) of Python math operators is similar to that of
mathematics. The ** operator is evaluated first; the *, /, //, and % operators are
evaluated next, from left to right; and the + and - operators are evaluated last (also
from left to right).The BODMAS rule follows the order, ie B – Brackets, O –
Order of powers or roots, D – Division, M – Multiplication A – Addition, and S –
Subtraction. Mathematical expressions with multiple operators need to be solved
from left to right in the order of BODMAS.
Ex:
Meghashree, CSE (ICSB) PA College of Engineering Page 4
Introduction to Python Programming (BPLCK105B)
3. Explain a local and Global Scope
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 must be one or the other; it cannot be both local
and global.
When a scope is destroyed, all the values stored in the scope’s variables are
forgotten.
There is only one global scope, and it is created when your program begins.
When your program terminates, the global scope is destroyed, and all its
variables are forgotten.
A local scope is created whenever a function is called. Any variables
assigned in this function exist within the local scope. When the function
returns, the local scope is destroyed, and these variables are forgotten.
Scopes matter for several reasons:
1. Code in the global scope cannot use any local variables.
2. However, a local scope can access global variables.
3. Code in a function’s local scope cannot use variables in any other
local scope.
4. We can use the same name for different variables if they are in
different scopes. That is, there can be a local variable named spam
and a global variable also named spam.
The global Statement If you need to modify a global variable from within a function, use the
global statement. If you have a line such as global eggs at the top of a function, it tells Python,
“In this function, eggs refer to the global variable, so don’t create a local variable with this
name.”
Example
def spam():
global eggs
eggs = 'spam'
Meghashree, CSE (ICSB) PA College of Engineering Page 5
Introduction to Python Programming (BPLCK105B)
spam()
print(eggs) When you run this program, the final print() call will output this: spam
4. With an example explain the following built in function
i. print() ii. input () iii. len()
i.print ()
The print() function displays the string value inside the parentheses on
the screen or any other standard output device.
The line print('Hello world!')` means Print out the text in the string
`'Hello world!'`. When Python executes this line, you say that Python is
calling the `print()` function and the string value is being passed to the
function.
Ex:
print ("Hello, Python!")
print () # This prints a blank line
ii. input()
The input() function allows takes a user input. By default, it returns
the user input in the form of a string.
The input() function waits for the user to type some text on the
keyboard and press ENTER.
Example:
iii. len()
The len()function evaluates to the integer value of the number of characters
in that string.
Example:
print(len("together")) # Output: 7
print(len("Python")) # Output: 6
print(len("Hello world")) # Output: 11 (includes the space)
print(len(" ")) # Output: 1 (just the space)
Meghashree, CSE (ICSB) PA College of Engineering Page 6
Introduction to Python Programming (BPLCK105B)
5. What are Functions? Explain python functions with parameter and return statement
Function is a block of code that only runs when called. It is like a mini-program. The
idea is to use the same block of code repeatedly during programming in terms of
function whenever required.
o The syntax to declare a function is:
def Statements with Parameters:
When we call the print() or len() function, we pass in values, called arguments in
this context, by typing them between the parentheses.
We can also define our own functions that accept arguments.
Return Values and Return Statements
When you call the len () function and pass it an argument such as 'Hello', the function call
evaluates to the integer value 5, which is the length of the string you passed it.
In general, the value that a function call evaluates to is called the return value of the
function. When creating a function using the def statement, you can specify what the
return value should be with a return statement.
A return statement consists of the following:
• The return keyword
• The value or expression that the function should return
Meghashree, CSE (ICSB) PA College of Engineering Page 7
Introduction to Python Programming (BPLCK105B)
Example: Output:
def square(num): 16
return num * num
result = square(4)
print(result)
6. How to handle exception in python with example
Definition: Exception is an event (error) which occurs during the
execution of the program.
If we don’t want to crash the program due to errors instead we want the
program to detect errors, handle them, and then continue to run. A
ZeroDivisionError happens whenever we try to divide a number by zero.
From the line number given in the error message, the return statement in
spam () is causing an error.
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 the following except clause if an
error happens.
We 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
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
Example:
Program
Meghashree, CSE (ICSB) PA College of Engineering Page 8
Introduction to Python Programming (BPLCK105B)
Output
21.0
3.5
Error: Invalid argument.
None
42.0
7. Define a Comparison Operator and List its Types. Give the difference between = = and
= operator
a)
The comparison operators are also called relational operators. Comparison
operators compare two values and evaluate them down to a single
Boolean value. The table below lists the comparison operators
Operator Meaning Example
< Less than A<B
> Greater than A>B
<= Less than or equal to A<=B
>= Greater than or equal to A>=B
== Is equal to A==B
!= Is not equal to A!=B
b)
The = operator is used for assignment, such as when assigning a value
to a variable.
The == operator is the relational operator for checking the equality of two
values. If the values are the same, it will return True and will return False
otherwise
Meghashree, CSE (ICSB) PA College of Engineering Page 9
Introduction to Python Programming (BPLCK105B)
Example 1: Assign Operator Example 2: Equality Operator
>>> num = 15 >>> 3 == 3
>>> num True
15
>>> 5 == 8
>>> num1 = 'EC' False
>>> num1
'EC' >>> 'EC' == 'EC'
True
>>> 'CS' == 'EC'
False
8. Write the step by step execution of the following expression in python
3 / 2 * 4 + 3 + (10 / 4) * * 3 – 2
Expression
3 / 2 * 4 + 3 + (10 / 4) ** 3 - 2
Step 1: Evaluate the parentheses: (10 / 4) = 2.5
Updated expression: 3 / 2 * 4 + 3 + (2.5) * * 3 - 2
Step 2: Evaluate the exponentiation: (2.5) ** 3 = 15.625
Updated expression: 3 / 2 * 4 + 3 + 15.625 - 2
Step 3: Evaluate the division: 3 / 2 = 1.5
Updated expression: 1.5 * 4 + 3 + 15.625 - 2
Step 4: Evaluate the multiplication: 1.5 * 4 = 6.0
Updated expression: 6.0 + 3 + 15.625 - 2
Step 5: Evaluate the first addition: 6.0 + 3 = 9.0
Updated expression: 9.0 + 15.625 - 2
Meghashree, CSE (ICSB) PA College of Engineering Page 10
Introduction to Python Programming (BPLCK105B)
Step 6: Evaluate the second addition: 9.0 + 15.625 = 24.625
Updated expression: 24.625 - 2
Step 7: Evaluate the subtraction: 24.625 - 2 = 22.625
Final Result: 22.65
9. Explain String Concatenation and String Replication operator with an example
String concatenation:
Concatenation is the process of joining two or more strings together and
forming one single string.
Different ways to concatenate strings using the + operator
For example, + is the addition operator when it operates on two integers or
floating-point values.
However, when + is used on two string values, it joins the strings as the
string concatenation operator.
>> ‘Hello’ + ‘World’
HelloWorld
String replication:
Replicating the same string “n” several times is called string replication.
Use the * operator on a string to repeat the string a provided number of
times.
The syntax for the operation is: result = ‘string’ * integer number
>> ‘Alice’ * 3
AliceAliceAlice
10. List and Explain with examples Different types of Comparison and Boolean
Operator
a)
The comparison operators are also called relational operators. Comparison
operators compare two values and evaluate them down to a single
Boolean value. The table below lists the comparison operators
Meghashree, CSE (ICSB) PA College of Engineering Page 11
Introduction to Python Programming (BPLCK105B)
Operator Meaning Example
< Less than A<B
> Greater than A>B
<= Less than or equal to A<=B
>= Greater than or equal to A>=B
== Is equal to A==B
!= Is not equal to A!=B
b) Boolean Operator
Python has three Boolean operators, or logical operators:
and
or
not
These logical operators are used to compare Boolean values, as shown below:
Operator Meaning Example
and True if both the operands are true X and Y
or True if either of the operands is true X or Y
not True if the operand is false not X
and operator: The and operator evaluates an expression to True if both Boolean values are
True; otherwise, it evaluates to False.
Meghashree, CSE (ICSB) PA College of Engineering Page 12
Introduction to Python Programming (BPLCK105B)
or operator: The or operator valuates an expression to True if either of the two Boolean values
is True. If both are False, it evaluates to False
The not operator operates on only one Boolean value (or expression). The not operator simply
evaluates to the opposite Boolean value
11. What are user defined functions? How can we pass the arguments to the functions?
Explain with suitable example
Types of Functions in Python:
1. Built-in library function: These are Standard functions in
Python that are available to use. Example print(), len()etc..
2. User-defined function: We can create our own functions based
on our requirements.
b) def Statements with Parameters
➢ When we call the print() or len() function, we pass in values, called arguments in this
context, by typing them between the parentheses.
The definition of the hello() function in this program has a parameter called name
➢ A parameter is a variable that an argument is stored in when a function is called.
The first time the hello() function is called, it‘s with the argument 'Alice'
Meghashree, CSE (ICSB) PA College of Engineering Page 13
Introduction to Python Programming (BPLCK105B)
➢ The program execution enters the function, and the variable name is automatically set to
'Alice', which is what gets printed by the print() statement
➢ One special thing to note about parameters is that the value stored in a parameter is
forgotten when the function returns
Program Output
12. Explain else ,Continue, break statement in python with an example
a) else
An if clause can optionally be followed by an elsestatement.
The elseclause is executed only when the if statement’s condition is False.
else statement could be read as, “If this condition is true, execute this
code. Or else, execute that code.”
An else statement doesn’t have a condition, and in code, an else statement
always consists of the following:
1. The else keyword
2. A colon
3. Starting on the next line, an indented block of code (called the
else clause)
Meghashree, CSE (ICSB) PA College of Engineering Page 14
Introduction to Python Programming (BPLCK105B)
b) Break
Break in Python is a loop control statement. It is used to control the
sequence of the loop.
The break keyword is used to break out a for loop, or a while loop.
If the execution reaches a break statement, it immediately exits the while
loop’s clause.
n code, a break statement simply contains the break keyword.
Example: for break statement
Meghashree, CSE (ICSB) PA College of Engineering Page 15
Introduction to Python Programming (BPLCK105B)
c) Continue
The continue keyword is used to end the current iteration in a for
loop (or a while loop) and continues to the next iteration. It is used inside
the loop.
When the program execution reaches a continue statement, the program
execution immediately jumps back to the start of the loop and reevaluates
the loop’s condition.
Program
while True:
print('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break
print('Access granted.')
Meghashree, CSE (ICSB) PA College of Engineering Page 16
Introduction to Python Programming (BPLCK105B)
Meghashree, CSE (ICSB) PA College of Engineering Page 17