[go: up one dir, main page]

0% found this document useful (0 votes)
7 views12 pages

Python Que n Ans

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 12

1.

Control flow statements in Python are control flow is the order in which the
program’s code executes. The control flow of a Python program is regulated by
conditional statements, loops, and function calls. Python has three types of control
structures:
Sequential - default mode
Selection - used for decisions and branching
Repetition - used for looping, i.e., repeating a piece of code multiple times.
a. Sequential
Sequential statements are a set of statements whose execution process happens in a
sequence. The problem with sequential statements is that if the logic has broken in
any one of the lines, then the complete source code execution will break.
b. Selection/Decision control statements
In Python, the selection statements are also known as Decision control statements or
branching statements. The selection statement allows a program to test several
conditions and execute instructions based on which condition is true.
Some decision control statements are:
if
if-else
nested if
if-elif-else
c. Repetition
A repetition statement is used to repeat a group(block) of programming instructions.
In Python, we generally have two loops/repetitive statements:
while loop
for loop
Repetition Statements
Repetition statements are called loops, and are used to repeat the same code
multiple times in succession. Python has two types of loops: Condition-Controlled
and Count-Controlled

Condition-Controlled loop uses a true/false condition to control the number of times


that it repeats - while. Basic syntax:
while condition:
statement(s) # notice the indent from of this line relative to the while
Count-Controlled loop repeats a specific number of times - for. Basic syntax:
for variable in [value1, value2, etc.]:
statement(s) # notice the indent from of this line relative to the for
“while” loops
while a condition is true, do some task.
while loop is known as a pretest loop, which means it tests its condition before
performing an iteration
The boolean_expression in these formats is sometimes known as the loop
continuation condition
The loop body must be a block, or a single statement (like with the if-statements)
How it works
The boolean expression is a test condition that is evaluated to decide whether the
loop should repeat or not.
true means run the loop body again.
false means quit.
Examples

while true
do statement 01…
do statement 02…
…..
“for” loop
The for loop as a Count-Controlled loop iterates a specific number of times.
Basic syntax:
for variable in [value1, value2, etc.]:
statement(s) # notice the indent from of this line relative to the for

How it works
The first line is called the for clause
In the for clause, variable is the name of a variable.
Inside the brackets is a sequence of values, that is comma separated. (in Python this
is called a list).
Executing is as follows:
The variable is assigned the first value in the list.
The statements in the block are executed.
The variable is assigned the next value in the list, if any repeat step 2 else the loop
terminates.
The variable can be used in the loop.
Examples
if true
do statement 01…
do statement 02…

else
do statement 03…
do statement 04…

2. Recursion
Python also accepts function recursion, which means a defined function can call
itself.
Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through data to
reach a result.

The developer should be very careful with recursion as it can be quite easy to slip
into writing a function which never terminates, or one that uses excess amounts of
memory or processor power. However, when written correctly recursion can be a
very efficient and mathematically-elegant approach to programming.

Examples
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))

3. Python Language: The most common saying, which is also published in various
books, is that Python is an interpreted language, however, the hidden fact is that
Python is both compiled and interpreted. This might seem contradictory at first, but it’s
important to understand how Python’s compilation and interpretation work together.
When you write a Python program, it is initially in source code form. This source code
needs to be transformed into an executable form that can be executed by the
computer.
a. Interpretation: in simple terms means running code line by line. It also means that
the instruction is executed without earlier compiling the whole program into machine
language. Now, let us discuss how Python works as an interpreted language. Consider
a scenario where you are trying to run a python code, but unfortunately, you have
made some mistakes at the bottom of the code. You will find that there is an error
generated for obvious reasons, but along with the error, you will find the output of the
program till the line of the program is correct. This is possible because Python reads
the code line by line and generates output based on the code. Whenever it finds any
error in the line, it stops running and generates an error statement.
b. object-oriented programming: Python is an object-oriented programming
language that is designed in C. By nature, it is a high-level programming language that
allows for the creation of both simple as well as complex operations. Along with this
Python comes inbuilt with a wide array of modules as well as libraries which allows it
to support many different programming languages like Java, C, C++, and JSON.
c. Interactive Python: Python is interactive. When a Python statement is entered,
and is followed by the Return key, if appropriate, the result will be printed on the
screen, immediately, in the next line. This is particularly advantageous in the
debugging process. In interactive mode of operation, Python is used in a similar way
as the Unix command line or the terminal.
Similar to other scripting languages, Python is an interpreted language. At runtime an
interpreter processes the code and executes it. To demonstrate the use of the Python
interpreter, we write print “Hello World” to a file with a .py extension. To interpreter this
new script, we invoke the Python interpreter followed by the name of the newly created
script.
hello.py
print \”Hello World\”
programmer# python hello.py
Hello World

Additionally, Python provides interactive capability. A programmer can invoke the


Python interpreter and interact with the interpreter directly. To start the interpreter, the
programmer executes python with no arguments. Next, the interpreter presents the
programmer with a >>> prompt, indicating it can accept a command. Here, the
programmer again types print “Hello World.” Upon hitting return, the Python interactive
interpreter immediately executes the statement.
programmer# python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
>>>
>>> print “Hello World”
Hello World
Python’s compilation and interpretation work together to provide a flexible and
dynamic programming environment. When Python code is compiled, the resulting
bytecode can be cached and reused for faster execution in the future. This also allows
for some level of static analysis and optimization of the code. When Python code is
interpreted, it allows for rapid development and debugging, and provides a more
interactive programming experience.
4. Swap two Numbers
a. Without temporary variable
Method 1 :- Using simple built-in method
# Python code to swap two numbers
# without using another variable
x=5
y = 10
print ("Before swapping: ")
print("Value of x : ", x, " and y : ", y)
# code to swap 'x' and 'y'
x, y = y, x
print ("After swapping: ")
print("Value of x : ", x, " and y : ", y)
Output:
Before swapping:
Value of x : 5 and y : 10
After swapping:
Value of x : 10 and y : 5
Method 2 :- Using Bitwise XOR operator
# Python code to swap two numbers
# using Bitwise XOR method
x = 5 # x = 0101
y = 10 # y = 1010
print ("Before swapping: ")
print("Value of x : ", x, " and y : ", y)

# Swap code
x ^= y # x = 1111, y = 1010
y ^= x # y = 0101, x = 1111
x ^= y # x = 1010, y = 0101
print ("After swapping: ")
print("Value of x : ", x, " and y : ", y)
Output:
Before swapping:
Value of x : 5 and y : 10
After swapping:
Value of x : 10 and y : 5

Method 3: Using both bitwise operators and arithmetic operators


x = 5;
y = 10;
print ("Before swapping: ") ;
print("Value of x : ", x, " and y : ", y) ;
# same as x = x + y
x = (x & y) + (x|y) ;
#vsame as y = x - y
y = x + (~y) + 1 ;
# same as x = x - y
x = x + (~y) + 1 ;
print ("After swapping: ")
print("Value of x : ", x, " and y : ", y)
Output:
Before swapping:
Value of x : 5 and y : 10
After swapping:
Value of x : 10 and y : 5
b. With temporary variable
# Python code to swap two numbers
# with using temporary variable
x=5
y = 10
print ("Before swapping: ")
print("Value of x : ", x, " and y : ", y)
# code to swap 'x' and 'y'
temp = x
x=y
y = temp
print ("After swapping: ")
print("Value of x : ", x, " and y : ", y)

Output:
Before swapping:
Value of x : 5 and y : 10
After swapping:
Value of x : 10 and y : 5

5. Break and Continue in Python


a.Break Statement
A break statement is used to terminate the loop whenever a particular condition is
satisfied. The statement is there just next after the loop receives control of the
program. The break statement will end the innermost loop if it is contained within a
nested loop that is the loop inside the other loop. It is used to end the loop that it is
enclosed in, such as a do-while, while, switch, and for statement.

Example
The example given below will give a better understanding of the break statement in
Python.
for char in "Deepika":
if char == "p":
break
print(char)
print("Over")

Output
D
e
e
Over
In the above example, we are printing the characters of the string "Deepika" until the
character "p" is not encountered. At the moment when "t" is encountered the "if"
condition will satisfy what is needed for the execution of the break statement. After
execution of the break statement, the control of the program will directly jump to line
number 7 which is just the next statement outside the loop.
b. Continue Statement
The continue statement skips the remaining lines of code, for the current iteration of
the loop. In this case, the loop does not end, it continues with the next iteration.
Example
The example given below will give a better understanding of the break statement in
Python.
for char in "Deepika":
if char == "p":
continue
print(char)
print("Over")

Output
D
e
e
i
k
a
This example is similar to the above example of the break statement, the difference
here is that the break statement is replaced with the continue statement. So here we
are printing the characters of the string " Deepika" but when the character "p" is
encountered then it skips that character and jumps to the next iteration.

6. String Functions in Python


To manipulate strings and character values, python has several in-built functions. It
means you don't need to import or have dependency on any external package to deal
with string data type in Python. It's one of the advantages of using Python over other
data science tools. Dealing with string values is very common in real-world. Suppose
you have customers' full name and you were asked by your manager to extract first
and last name of customer. Or you want to fetch information of all the products that
have code starting with 'QT'.
The 10 Python String Functions which we are going to discuss in this article are as
follows:
Functions Description
capitalize( ) returns a string where the first character
is the upper case
lower( ) returns a string where all the characters
in a given string are lower case
title( ) returns a string where the first character
in every word of the string is an upper
case
casefold( ) returns a string where all the characters
are lower case
upper( ) returns a string where all the characters
in a given string are in the upper case
count( ) finds the number of times a specified
value(given by the user) appears in the
given string
find( ) finds the first occurrence of the specified
value. It returns -1 if the value is not
found in that string
replace( ) replaces a specified phrase with another
specified phrase
swapcase( ) returns a string where all the upper case
letters are lower case and vice versa
join( ) takes all items in an iterable and joins
them into one string

upper( ) function
The upper() function returns a string where all the characters in a given string are in
the upper case. This function doesn’t do anything with Symbols and Numbers i.e,
simply ignored these things.

Syntax: string.upper()
Example: Return the number of times the value “deepika” appears in the string
string = "deepika"
print(string.upper( ))
Output:
DEEPIKA
count( ) function
The count() function finds the number of times a specified value(given by the user)
appears in the given string.
Syntax: string.count(value, start, end)

Example: Return the number of times the value “deepika” appears in the string
string = "deepika"
print(string.count("p"))
Output:
1
find( ) function
The find() function finds the first occurrence of the specified value. It returns -1 if the
value is not found in that string.
The find() function is almost the same as the index() function, but the only difference
is that the index() function raises an exception if the value is not found.
Syntax: string.find(value, start, end)
Example: Where in the text is the first occurrence of the letter “p”?
string = "Deepika"
print(string.find("p"))
Output:
3
7. Python list
Python Lists are similar to dynamically scaled arrays. They are used to hold a series
of different formats of data. Python lists are changeable (mutable), which means they
can have their elements changed after they are created. A Python list can also be
defined as a collection of distinct types of values or items. The elements in the list are
separated by using commas (,) and are surrounded by square brackets []. A single list
can contain Datatypes such as Integers, Strings, and Objects. Lists are changeable,
which means they can be changed even after they are created. Each element in the
list has a different location in the list, allowing for the duplication of components in the
list, each with its own individual place and credibility.
A Python list is generated in Python programming by putting all of the items (elements)
inside square brackets [], separated by commas. It can include an unlimited number
of elements of various data types (integer, float, string, etc.). Python Lists can also be
created using the built-in list() method.
Adding elements in a list
The built-in append() function can be used to add elements to the List. The append()
method can only add one element to the list at a time. We can use the extend() function
to add multiple elements to the list. We can insert one item at a time using the insert()
method, or we can insert numerous things by squeezing them into an empty slice of a
list. Unlike the append() function, which accepts only one argument, insert() function
requires two arguments -> (position, value)
Example
num = [1, 2, 3, 4]
print('Original List:', num)

num.append(5)
print(num)
num.extend([6, 7, 8])
print(num)
Output
Original List: [1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8]
Example
num = [1, 2, 5, 6]
print('Original List:', num)
num.insert(2, 3)
print(num)
num.insert(3, 4)
print(num)
Output
Original List: [1, 2, 5, 6]
[1, 2, 3, 5, 6]
[1, 2, 3, 4, 5, 6]

8. Bubble Sort in Python


The bubble sort algorithm compares adjacent elements and swaps them to sort the
list. The bubble sort uses two for loops to sort the list. The first for loop (outer for loop)
is used to traverse the list n times. The Second for loop (inner for loop) is used to
traverse the list and swap elements if necessary.
Algorithm:
N array elements
Loop i = 1 to N
Compare elements
If (i + 1) > (i) swap elements
Continue Loop until no swap
Program:
def bubble_sort(list1):
for i in range(0,len(list1)-1):
for j in range(len(list1)-1):
if(list1[j]>list1[j+1]):
temp = list1[j]
list1[j] = list1[j+1]
list1[j+1] = temp
return list1
list1 = [5, 3, 8, 6, 7, 2]
print("The unsorted list is: ", list1)
print("The sorted list is: ", bubble_sort(list1))
Output

The unsorted list is: [5, 3, 8, 6, 7, 2]


The sorted list is: [2, 3, 5, 6, 7, 8]
9. File Handling
In Python, file operations are essential for reading and writing data to files, and they
play a crucial role in data manipulation, analysis, and storage. In this article, we’ll
explore the basics of file operations in Python, including how to open, read, write, and
manipulate files, along with some advanced techniques to handle files efficiently. We’ll
also discuss different file modes, file objects, and file handling best practices that will
help you to work with files. File handling is an integral part of programming. File
handling in Python is simplified with built-in methods, which include creating, opening,
and closing files.
file_object = open('file_name', 'mode')
While files are open, Python additionally allows performing various file operations,
such as reading, writing, and appending information. The mode must have exactly one
create(x)/read(r)/write(w)/append(a) method, at most one +. Omitting the mode
defaults to 'rt' for reading text files

Mode Description
'r' Reads from a file and returns an error if
the file does not exist (default).
Writes to a file and creates the file if it
'w' does not exist or overwrites an existing
file.
'x' Exclusive creation that fails if the file
already exists.
Appends to a file and creates the file if it
'a' does not exist or overwrites an existing
file.
'b' Binary mode. Use this mode for non-
textual files, such as images.
't' Text mode. Use only for textual files
(default).
'+' Activates read and write methods.

10. Exception Handling


Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are
problems in a program due to which the program will stop the execution. On the other
hand, exceptions are raised when some internal events occur which change the
normal flow of the program.
Different types of exceptions in python:
In Python, there are several built-in Python exceptions that can be raised when an
error occurs during the execution of a program. Here are some of the most common
types of exceptions in Python
Try and Except Statement – Catching Exceptions
Try and except statements are used to catch and handle exceptions in Python.
Statements that can raise exceptions are kept inside the try clause and the statements
that handle the exception are written inside except clause.
Raising Exceptions
Each time an error is detected in a program, the Python interpreter raises (throws) an
exception. Exception handlers are designed to execute when a specific exception is
raised. Programmers can also forcefully raise exceptions in a program using the raise
and assert statements. Once an exception is raised, no further statement in the current
block of code is executed. So, raising an exception involves interrupting the normal
flow execution of program and jumping to that part of the program (exception handler
code) which is written to handle such exceptional situations.The raise statement can
be used to throw an exception. The syntax of raise statement is:
raise exception-name[(optional argument)]
Finally Clause
The try statement in Python can also have an optional finally clause. The statements
inside the finally block are always executed regardless of whether an exception has
occurred in the try block or not. It is a common practice to use finally clause while
working with files to ensure that the file object is closed. If used, finally should always
be placed at the end of try clause, after all except blocks and the else block.
Example: access element index out of bound and handle the corresponding exception
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")
Output
Second element = 2
An error occurred
Example: Here Use of raise statements
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise

An exception flew by!


Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: HiThere
Example: Here Use of finally clause
print ("Handling exception using try...except...else...finally")
try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ", quotient)
finally:
print ("OVER AND OUT")

You might also like