Python Que n Ans
Python Que n Ans
Python Que n Ans
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
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
# 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
Output:
Before swapping:
Value of x : 5 and y : 10
After swapping:
Value of x : 10 and y : 5
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.
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]
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.