0% found this document useful (0 votes)
22 views10 pages

Module 1 VTU QP VTU Question Paper Questions:: - If Statement

The document contains a series of questions and answers related to Python programming, covering topics such as features of Python, flow control statements, functions, variable scope, exception handling, and basic data types. Each section includes definitions, examples, and explanations of key concepts. It serves as a study guide for students preparing for examinations in Python programming.

Uploaded by

forf7627
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views10 pages

Module 1 VTU QP VTU Question Paper Questions:: - If Statement

The document contains a series of questions and answers related to Python programming, covering topics such as features of Python, flow control statements, functions, variable scope, exception handling, and basic data types. Each section includes definitions, examples, and explanations of key concepts. It serves as a study guide for students preparing for examinations in Python programming.

Uploaded by

forf7627
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Module 1 VTU QP

VTU Question Paper Questions:

1. List the Salient features of python programming language. (Jul/Aug 2022, 6M)
Features of Python
Free and Open Source
Easy to code
Easy to Read
Object-Oriented Language
GUI Programming Support
High-Level Language
Extensible feature
Easy to Debug
Python is a Portable language
Python is an Integrated language
Large Standard Library
Dynamically Typed Language

2. List and explain the syntax of all flow control statements with example. (Jul/Aug 2022, 8M)
Flow Control Statements
• if Statement
• else Statements

 elif Statements
• while Loop Statements
• break Statements
• continue Statements
• for Loops and the range() Function

if Statement
• The most common type of flow control statement is the if statement.
• An if statement’s clause (that is, the block following the if statement) will execute if the statement’s condition is
True.
• The clause is skipped if the condition is False.
In Python, an if statement consists of the following:
• The if 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 if clause)

Example:
if name == 'Alice':
print('Hi, Alice.')
The flowchart for an if statement
else Statements
• An if clause can optionally be followed by an else statement.
• The else clause is executed only when the if statement’s condition is False.
• In plain English, an 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:
• The else keyword
• A colon
• Starting on the next line, an indented block of code (called the else clause)

Example:
if name == 'Alice':
print('Hi, Alice.')
else:
print('Hello, stranger.')

elif Statements
• While only one of the if or else clauses will execute, you may have a case where you want one of many possible
clauses to execute.
• The elif statement is an “else if” statement that always follows an if or another elif statement.

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)

Example 1:
if name == 'Alice':
print('Hi, Alice.') elif age < 12:
print('You are not Alice, kiddo.')
Example 2:
if name == 'Alice':
print('Hi, Alice.') elif age < 12:
print('You are not Alice, kiddo.') elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.') elif age > 100:
print('You are not Alice, grannie.‘)

while Loop Statements


• You 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.

A while statement always consists of the following


• The while 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 while clause)

Example:
spam = 0
while spam < 5:
print('Hello, world.') spam = spam + 1

break Statements
• ‘Break’ in Python is a loop control statement.
• There is a shortcut to getting the program execution to break out of a while loop’s clause early.
• If the execution reaches a break statement, it immediately exits the while loop’s clause.
• break statement is put inside the loop body (generally after if condition).
• In code, a break statement simply contains the break keyword.
Example:

while True:
print('Please type your name.') name = input()
if name == 'your name':
break print('Thank you!')
continue Statements
• The continue statement is used to skip the rest of the code inside a loop for the current iteration only.
• Loop does not terminate but continues on with the next iteration.

When the program execution reaches a continue statement, the program execution immediately jumps back to the
start of the loop and re-evaluates the loop’s condition.

for Loops and the range() Function


What if you want to execute a block of code only a certain number of times??
Solution is do this with a for loop statement and the range() function for always includes the following:
• The for keyword
• A variable name
• The in keyword

A call to the range() method with up to three integers passed to it



• A colon
• Starting on the next line, an indented block of code (called the for clause)
Example:
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
The Starting, Stopping, and Stepping Arguments to range()
for i in range(12, 16): print(i)
Output:
12
13
14
15
Explanation:
The first argument will be where the for loop’s variable starts.
The second argument will be up to, but not including, the number to stop at.
Example 2:
for i in range(0, 10, 2): print(i)
Output:
0
2
4
6
8
Explanation:
• The range() function can also be called with three arguments.
• The first two arguments will be the start and stop values, and the third will be the step argument.
• The step is the amount that the variable is increased by after each iteration.

3. Write a python program to calculate the area of circle, rectangle and triangle. Print the results. (Jul/Aug
2022, 6M) (Feb/Mar 2022, 8M)
In VTU QP programs
4. What is a function? How to define a function in python? Explain with Suitable Example. (Jul/Aug 2022,
6M)

Functions
• Deduplicating code, which means getting rid of duplicated or copy-and pasted code.
• Deduplication makes your programs shorter, easier to read, and easier to update.
• We can write our own functions.
• A function is like a mini- program within a program.
• A major purpose of functions is to group code that gets executed multiple times.
Example1 (def Statements with Parameters ):
• You can also define your own functions that accept arguments.
def hello(name):
print('Hello ' + name)
hello('Alice')
hello('Bob')
Output:
Hello Alice Hello Bob
5. Explain Local and Global scope of variable in python with example. (Jul/Aug 2022, 8M) (Jan/Feb
2021, 8M) (Feb/Mar 2022, 8M)
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
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.

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. You can use the same name for different variables if they are in different scopes.
Local Variables Cannot Be Used in the Global Scope Example:

def spam():
eggs = 31337
spam()
print(eggs)
Output:
Traceback (most recent call last):
File "C:\Users\admin\ee.py", line 4, in <module> print(eggs)
NameError: name 'eggs' is not defined
Why Error?
The error happens because the eggs variable exists only in the local scope created when spam() is called.
Once the program execution returns from spam, that local scope is destroyed, and there is no longer a
variable named eggs.
So when your program tries to run print(eggs), Python gives you an error saying that eggs is not defined.

Local Scopes Cannot Use Variables in Other Local Scopes Example:

def spam():
1* eggs = 99
2* bacon()
3* print(eggs)
def bacon():
ham = 101
4* eggs = 0
5* spam()
Output:
>>> 99
5* When the program starts, the spam() function is called and a local scope is created.
1* The local variable eggs is set to 99.
2* Then the bacon() function is called, and a second local scope is created.
4* In this new local scope, the local variable ham is set to 101, and a local variable eggs— which is different
from the one in spam()’s local scope—is also created and set to 0 3*When bacon() returns, the local scope
for that call is destroyed. The program execution continues in the spam() function to print the value of eggs,
the eggs variable is set to 99. This is what the program print
Global Variables Can Be Read from a Local Scope Example:

def spam():
print(eggs) eggs = 42 spam()
print(eggs)
Output:
42
42
Why 42 is the output?
Since there is no parameter named eggs or any code that assigns eggs a value in the spam() function.
When eggs is used in spam(), Python considers it a reference to the global variable eggs.
This is why 42 is printed when the previous program is run.
Local and Global Variables with the Same Name Example:

def spam():
1* eggs = 'spam local' # prints 'spam local'
print(eggs) def bacon():
2* eggs = 'bacon local'
print(eggs) # prints 'bacon local
spam()
print(eggs) # prints 'bacon local'
3* eggs = 'global' bacon()
print(eggs) # prints 'global'
Output:
bacon local spam local bacon local global
There are actually three different variables in this program, but confusingly they are all named eggs.
The variables are as follows:
1* A variable named eggs that exists in a local scope when spam() is called. 2* A variable named eggs that
exists in a local scope when bacon() is called. 3* A variable named eggs that exists in the global scope.
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 refers
to the global variable, so don’t create a local variable with this name.” Example:

def spam():
1* global eggs
2* eggs = ‘spam’
eggs = ‘global’
spam()
print(eggs)
Output: Spam
Because eggs is declared global at the top of spam() 1*, when eggs is set to 'spam' 2*, this assignment is done to
the globally scoped spam. No local spam variable is created.

6. What is Exception Handling? How Exceptions are handled in python? Write a python program
with exception handling code to solve divide – by – zero error situation. (Jul/Aug 2022, 6M)
Exception handling is a programming mechanism that allows a program to respond to exceptional
conditions, or exceptions, that occur during execution. Exceptions are conditions that disrupt the normal
flow of a program's instructions, such as when an instruction fails, an undefined instruction is
encountered, or an external interrupt is raised.
Exception Handling
Errors can be handled with try and except statements.
The code that could potentially have an error is put in a try clause.

Example 1: Without Exception Handling


def spam(divideBy):
return 42 / divideBy
print(spam(2))
print(spam(0))
Output:
21.0
3.5
Traceback (most recent call last):
File "C:/zeroDivide.py", line 6, in print(spam(0))
File "C:/zeroDivide.py", line 2, in spam return 42 / divideBy
ZeroDivisionError: division by zero
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.
Errors can be handled with try and except statements.

Example 2: With Exception Handling


def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error: Invalid argument.')
print(spam(2))
print(spam(0))
Output:
21.0
Error: Invalid argument.

7. Demonstrate with example print(), input() and string replication. (Jan/Feb 2021, 6M)
8. The print() Function
9. The print() function displays the string value inside the parentheses on the screen.
10. *2 print('Hello world!')
11. print('What is your name?') # ask for their name
12. The line print('Hello world!') means “Print out the text in the string 'Hello world!'.”
13. When Python executes this line, you say that Python is calling the print() function and the string
value is being passed to the function.
 
15. A value that is passed to a function call is an argument
16. Note: Quotes are not printed to the screen. They just mark where the string begins and ends; they are
not part of the string value.
17. The input() Function
18. The input() function waits for the user to type some text on the keyboard and press enter
19.
20. Example:
21. myName = input() # Line *3 in the program above in the section 1.5
22. This function call evaluates to a string equal to the user’s text, and the previous line of code assigns the
myName variable to this string value.

8. Explain elif, for, while, break and continue statements in python with examples for each.
(Jan/Feb 2021, 10M)
Q2 Answer
9. Write a python program to check whether a given number is even or odd. (Jan/Feb 2021, 4M)
In VTU QP programs
10. How can we pass parameters in user defined functions? Explain with suitable example.
(Jan/Feb 2021, 5M)
Q4 answer
11. Demonstrate the concept of exception. Implement a code which prompts the user for Celsius temperature,
convert the temperature to Fahrenheit, and print out the converted temperature by handling the exception.
(Jan/Feb 2021, 7M)

12. Explain with example code snippets, different syntax of range() function in Python.
Q2 Answer
(Feb/Mar 2022, 8M)
13. Demonstrate the use of break and continue keyword using a code snippet. (Feb/Mar 2022, 6M)
Q2 Answer
14. List and define the use of comparison operators in python. Write the output for the following expression in
python. (Feb/Mar 2022, 6M)
i) 2**3
ii) 20%6
iii) 20/6

Comparison Operators
• Comparison operators compare two values and evaluate down to a single Boolean value.
• Table below lists the comparison operators.

lists the comparison operators.


Operator Meaning
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to

Examples:
>>> 42 == 42
True
>>> 42 == 99
False
i) 8
ii) 2
iii) 3.33
15. What is user defined function? Write a function to check if a given number is a prime or not. (Feb/Mar
2022, 8M)
Q4 Answer. In VTU QP program

16. Explain basic data types like int, float, double and string with an example

A Data type is a category for values, and every value belongs to exactly one data type.
The most Common data types in Python are listed in table
Integers (int) -2, -1, 0, 1, 2, 3, 4, 5

Floating-point -1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25


numbers (float)

Strings (str) 'a', 'aa', 'aaa', 'Hello!', '11 cats‘, ‘ ’

Example:

 int (integer): Represents whole numbers, positive or negative, without any decimal point.
>>> s = 5
>>> print(s, "is of type", type(s)) 5 is of type <class
'int'>

 float: Represents numbers with a decimal point or in exponential form.

>>> s = 2.0

>>> print(s, "is of type", type(s))


2.0 is of type <class 'float'>
 double: Python does not have a separate double type. Instead, it uses float to represent double-
precision floating-point numbers, which are similar to double in other programming languages.
large_float = 1.7976931348623157e+308
print(type(large_float)) # Output: <class 'float'>
 str (string): Represents a sequence of characters, enclosed in single or double quotes.
>>> s =”Hello”
>>> print(s,”is of type”,type(s))
Hello is of type < class ‘str’>

You might also like