0% found this document useful (0 votes)
29 views

Python Ut Answers

Uploaded by

Sanjana ML
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Python Ut Answers

Uploaded by

Sanjana ML
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Forwarded

1. *Syntax and ControlFlow


Diagrams of break and
continue statements*:

- break statement: It is used


to exit a loop prematurely.
When encountered withina
loop, the break statement
immediately terminates the
loop it is in, and control is
passed to the statement
immediately following the loop.
This is particularly useful when
youwant to stop the loop
execution based on a certain
condition.

python
for i in range(5):
if i==3:
break
print(i)

Here,the loop will print


numbers from O to 2, and
when i becomes 3, the break
statement is executed, and the
loop terminates.

Control Flow Diagram:

Start -> 0->1-> 2->3


(break) -> End

continue statement:It is
used to skip the rest of the
code inside a loop for the
current iteration, and the
loop continues with the next
iteration. This statement is
helpful when you want to skip
certain iterations of a loop
based on a condition without
terminating the loop entirely.

python
for i in range(5):
if i==3:
Continue
print(i)

Here, the loop will print


numbers from 0 to 4, but it will
skip printing 3 because of the
continue statement.

Control Flow Diagram:

Start ->0->1-> 2->3


(continue) -> 4 -> End
2. *Ways of Importing
Modules in Python*:

- Using import statement:


This method imports the entire
module andmakes allof its
functionality available under
the module's namespace.

python
import math
print(math.pi)

Here,the math module is


imported, and we access the
value of piusing math.pi.
- Using from ..import
statement: This method
allows youto import specific
attributes or functions from a
module directly into the curren
namespace.

python
from math import pi
print(pi)

Here, only the value of pi


is imported from the math
module, and we can directly
access it without using the
module name. 9:24 F
hmher

sitan n jastcn)
anht'etun, n im nCn'). ht C, ))
nz ma Cuint,
tn<:
emtc

int C bimomil co t e nCa e! n a

o n, in
bino mial co
uen the corsole
Jha diret bêneci A u )
n nt Gunhut('em
seendnunJ
") uhlicn.

ifcuhe
cutumi mtscemd num
irt end )
i t mn Decondum
seendum Cuuum i'+)
J24 PV

Forwarded

5. *Looping Control
Statements in Python*:

Looping controlstatements
are used to alter the flow of
loops in Python. There are
two primary looping control
statements:

- for loop: It iterates over a


sequence (such as a list, tuple,
string, etc.)or any iterable
object. The loop continues until
the sequence is exhausted
ora break statement is
encountered.
python
for item in iterable:
# code block

Example:
python
for iin range(5):
print(i)

This loop iterates Over the


numbers Oto 4 and prints each
number.

- while loop: It repeatedly


executes a block of code as
long as a specified condition
is true. The loop continues
untilthe condition becomes
false or a break statement is
encountered.
python
while condition:
# code block

Example:
python
i=0
while i< 5:
print(i)
i+=1

This loop prints numbers


from 0 to4 as long as the
condition i <5 is true.
6. *Scope Rules ofVariables
in Python*:

Scope refers to the visibility


and accessibility of variables
within a program. In Python,
there are four scope rules:

- *Local scope*: Variables


defined within a function have
local scope and are accessible
only within that function.
- *Enclosing scope
(nonlocal)*: Variables defined
in an enclosing function
(a function within another
function) have enclosing scope
and are accessible within the
inner function.
- *Global scope*: Variables
defined outside of any function
or in the global keywordare
in the global scope andcan
be accessed from anywhere
within the program.
- *Built-in scope*: Python
has several built-in functions
and exceptions that are
automatically available in every
program. These are in the
built-in scope.

Example:
python
X= 10 # Global variable

def outer():
y=20 # Enclosingscope
def inner():
z=30 # Local scope
print(x, y, z)

inner()

outer()

In thisexample, x is in
the globalscope, y isin the
enclosing scope,and z is in
the local scope. 9:24 PM
Forwarded

7. Need for Role ofRules of


Precedence and
Precedence inPython*:

Precedence refers to the


are
order in whichoperators
expression. It
evaluated in an
determines which operations
when an
are performed first
expression contains multiple
operators.

of
- *Need for Role
Precedence*: Precedence
is essential for ensuring
of
the correct evaluation
expressions. It helps in avoiding
ambiguity and ensures that
expressions are evaluated
accordingto the intended order
of operations.

- *Rules of Precedence in
Python*:
- Parentheses (0 have the
highest precedence and can be
of
used to force the evaluation
expressions in aspecific order.
-Exponentiation ** has the
next highest precedence.
Multiplication *,division
1, floor division //, and
modulo % have the same
precedence and are evaluated
from left to right.
-Addition + and
subtraction - also have the
same precedence and are
evaluated from left to right.

Example:
python
result = 10 +2 **3/4 *5

In this expression, the order


of precedence dictates that
exponentiation is performed
first (2 ** 3), then division (8/
4), then multiplication (2*5),
and finally addition (10 +10 ),
resulting in 20.
8.*Local and Global Scope
with Suitable Examples*:

- *Local Scope*: Variables


defined withina function are
said to have local scope. They
are accessible only within that
function.
python
def my function():
X= 10 # Local variable
print()

my_function() # Output: 10
# print(x) # Thiswould raise
a NameError since x is not
defined in the global scope

. *Global Scope*: Variables


defined outside of any function
or with the global keyword
inside a function are said to
have global scope. They can
be accessed from anywhere
within the program.
python
X= 10 # Global variable

def my function():
print(x) # Accessing
global variable

my function() # Output: 10

If we want to modify a global


variable inside a function,we
can use the global keyword.
python
X= 10 # Global variable

def my function):
global x
X=20 # Modifying global
variable

my_function)
print(%) # Output: 20
10. *Functions in Python with
Parameters and Return
Statements*:

Functions are blocks of


reusable code that perform a
specific task. They can take
parameters as input, perform
operations, and optionally
return a value.

- *Syntax of a Function*:
python
def
function_name(parametert,
parameter2, ..):
# Function body
# Perform operations
usingparameters
returnresult # Optional

- *Example of a Function
with Parameters and Return
Statement*:
python
def add_numbers(x, y):
return X + y

result = add_numbers(5, 3)
print(result) # Output: 8

In this example, the


add numbers function takes
two parameters x and y,
adds them together, and
returns the result.

python
def greet(name):
return "Hello, "+ name +

message - greet('Alice")
print(message) # Output:
Hello, Alice!

In this example, the greet


function takes a parameter
name,concatenates it withthe
string "Hello,", and returns the
resulting greeting message.
11. *Exception Handling in
Python*:
Exception handling is a
mechanism to handle errors
that occur duringprogram
execution gracefully, preventing
the program from crashing.
Python provides a robust
exception handling mechanism
with the try, except, else,
and finally blocks.

. *Definition*: Exception
handling is the process of
catching and handling errors
that occur during the execution
of a program.

- *How Exceptions are


Handled in Python*:
- try block: The code that
might raise an exception is
placed within this block.
except block: If an
exception occurs within the
try block, the corresponding
eXcept block is executed to
handle the exception.
- else block (optional):
This block is executed if no
exceptions occur in the try
block.
- finally block (optional):
This block is always executed,
whether an exception occurs
or not. It is typically used for
cleanup tasks.

-*Example of Handling
Divide by Zero Exception*:
python
try:
result = 10/0
except ZeroDivisionError:
print("Error: Division by
zero!")

In this example, the try


block attempts to perform
division by zero, which raises a
ZeroDivisionError exception.
The corresponding except
block catches the exception
and prints an error message.
12. *User-Defined Functions
and Built-inFunctions*:

-*User-Defined Functions*:
These are functions created by
the user to perform a specific
task. They are defined using
the def keyword followed
by the function name and
parameters.
Example:
python
def greet(name):
return "Hello, " + name t

message =greet("Alice")
print(message) # Output:
Hello, Alice!

- *Built-in Functions*: These


are pre-defined functions
provided by Python that are
readily available for use without
the need for explicit definition.

Examples:
print() : Prints the
specified value(s) to the
standard output.
- input) : Reads input from
the user through the standard
input.
len): Returns the length
of an object (e.g., string, list,
tuple).

python
print("Hello, world!") #
Output: Hello, world!

name = input("Enter your


name: ")
print("Hello, " + name + "")

length = len("Python")
print(length) # Output: 6
9:24 PM
Forwarded

13.*Exception Handling in
Python with Example*;

Exception handling allows


programmers to gracefully
handle errors that occur during
program execution, preventing
the program from crashing.
Here's how you can handle
exceptions in Python:

-*Syntax*:
python
try:
# Code that might raise
an exception
except ExceptionName:
# Code to handle the
exception

-*Example*:
python
try:
x= 10/ 0
except ZeroDivisionError:
print("Error: Division by
zero!")

In this example, the try


block attempts to perform
division by zero, which
would normally raise a
ZeroDivisionError exception.
The except block catches this
exception and prints an error
message.

-*Handling Multiple
Exceptions*
You can handle mutiple
exceptions by specifying
multiple except blocks or by
using a single block to handle
multiple exceptions.
python
try:
# Code that might raise
exceptions
except Exceptiont:
# Code to handle
Exceptiont
except Exception2:
# Code to handle
Exception2

python
try:
# Code that might raise
exceptions
except (Exceptiont,
Exception2):
# Code to handle both
Exceptiont and Exception2

Example:
python
try:
result = int(input("Enter a
number: ")/0
except ValueError:
print("Error: Invalid input!")
except ZeroDivisionError:
print("Error: Division by
zero!")

In this example, the


program first attempts to
Convert user input to an
integer ( ValueError ) and then
performs division by zero
(ZeroDivisionError ), handling
each exception separately.
14.*Program to Print Even
Numbers Using range()
with Step Size*:

You can use the range()


function with a step size
to generate a sequence of
numbers with a specified
interval. Here's a Python
program to print even numbers
using range) with a step size
of 2:

python
for num in range(0, 11, 2):
print(num)

This program generates a


sequence of numbers from 0
to 10 with a step size of 2 and
prints each even number in the
sequence.

Output:

2
4
6
8
10

Here,the range(0, 11,2)


generates numbers starting
from Oup to (but not including)
11,with a step size of 2,
resulting inthe sequence of
even numbers. 9:24 PM

You might also like