Python 10M Q&A

Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

PYTHON 10M Q&A

1. Construct a program to perform different


Mathematical Computations. Try to do all the
operations present in a Scientific Calculator.
Ans-
# Python program for simple calculator
import math
import random
# Function to add two numbers
def add(num1, num2):
print(num1, "+", num2, "=",num1+num2)

# Function to subtract two numbers


def subtract(num1, num2):
print(num1, "-", num2, "=",num1-num2)

# Function to multiply two numbers


def multiply(num1, num2):
print(num1, "*", num2, "=",num1*num2)

# Function to divide two numbers


def divide(num1, num2):
print(num1, "/", num2, "=",num1/num2)

# Function to modulous division two numbers


def modulodiv(num1, num2):
print(num1, "%", num2, "=",num1%num2)

# Function to calculate the powers of 10


def powers_of_10(num1):
print("10", "^", num1, "=",pow(10,num1))

# Function to calculate the square of a number


def square(num1):
print(num1, "^","2" , "=",pow(num1,2))

# Function to calculate the cube of a number


PYTHON 10M Q&A

def cube(num1):
print(num1, "^","3" , "=",pow(num1,3))

# Function to calculate the power of y with x


def power_of_xy(num1,num2):
print(num1, "^",num2 , "=",pow(num1,num2))

# Function to calculate the squareroot of a number


def squareroot(num1):
print("Square Root of ",num1,"=",math.sqrt(num1))

# Function to calculate the Cuberoot of a number


def cuberoot(num1):
print("Cube Root of ",num1,"=",pow(num1,(1/3)))

# Function to calculate the sine (x) in degrees


def sinx(num1):
print("Sine(",num1,"Degrees) =",math.sin(math.radians(num1)))

# Function to calculate the cosine of a number


def cosx(num1):
print("Cosine(",num1,"Degrees) =",math.cos(math.radians(num1)))

# Function to calculate the tan of a number


def tanx(num1):
print("Tan(",num1,"Degrees) =",math.tan(math.radians(num1)))

# Function to calculate the natural logarithm (Ln) of a number


def natural_log(num1):
print("The natural logarithm (Ln) of ",num1,"=",math.log(num1))

# Function to calculate the Logarithm of base 10 of a number


def log(num1):
print("The Logarithm of base 10 of ",num1,"=",math.log10(num1))

# Function to calculate the Factorial of a number


def factorial(num1):
PYTHON 10M Q&A

print("The Factorial of ",num1,"=",math.factorial(num1))

# Function to calculate the Roundoff of a number


def roundoff(num1):
print("The Roundoff of ",num1,"=",round(num1,2))

# Function to calculate the Floor of a number


def floor(num1):
print("The Floor of ",num1,"=",math.floor(num1))

# Function to calculate the Ceil of a number


def ceil(num1):
print("The Ceil of ",num1,"=",math.ceil(num1))

# Function to calculate the Absolute of a number


def absolute(num1):
print("The Absolute of ",num1,"=",abs(num1))

# Function to calculate the value of PI


def PI_value():
print("The value of PI =",math.pi)

# Function to calculate the Inverse of a number


def inverse(num1):
print("The Inverse of ",num1,"=",(1/num1))

# Function to generate a Random number


def random(num1,num2):
import random
randomlist = random.sample(range(num1, num2), 10)
print("The Generated 10 Random numbers between",num1,"and
",num2,"are =",randomlist)

# Function to calculate the e^x of a number


def e_x(num1):
print("The e^x of ",num1,"=",math.exp(num1))
PYTHON 10M Q&A

print("Please select operation -\n" "1. Add\n" "2. Subtract\n" "3.


Multiply\n" "4. Divide\n" "5. Modular Division")
print("6. 10^x\n" "7. x^2\n" "8. x^3\n" "9. x^y\n" "10. Square root of x")
print("11. Cube Root(x)\n" "12. Sin(x)\n" "13. Cos(x)\n" "14. Tan(x)\n"
"15. Natural Logarithm(ln)" )
print("16. Log\n" "17. Factorial(x)\n" "18. Roundoff(x)\n" "19.
Floor(x)\n" "20. Ceil(x)" )
print("21. Abs(x)\n" "22. PI\n" "23. Inverse(x)\n" "24. Random
Number\n" "25. e^x\n" "26. Exit\n")
# Take input from the user

while True:
select = int(input("Select operations from 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18 ,19, 20, 21, 22, 23, 24, 25, 26:"))
if select == 1:
print("Addition of Two Numbers")
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))
add(number_1, number_2)

elif select == 2:
print("Subtraction of Two Numbers")
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))
subtract(number_1, number_2)

elif select == 3:
print("Multiplication of Two Numbers")
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))
multiply(number_1, number_2)

elif select == 4:
print("Division of Two Numbers")
PYTHON 10M Q&A

number_1 = int(input("Enter first number: "))


number_2 = int(input("Enter second number: "))
divide(number_1, number_2)

elif select == 5:
print("Modular Division of Two Numbers")
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))
modulodiv(number_1, number_2)

elif select == 6:
print("Powers of 10 of a Number")
number_1 = int(input("Enter the number: "))
powers_of_10(number_1)

elif select == 7:
print("Square of a Number")
number_1 = int(input("Enter the number: "))
square(number_1)

elif select == 8:
print("Cube of a Number")
number_1 = int(input("Enter the number: "))
cube(number_1)

elif select == 9:
print("Power of X to Y")
number_1 = int(input("Enter the First number: "))
number_2 = int(input("Enter the Second number: "))
power_of_xy(number_1,number_2)

elif select == 10:


print("Square Root of a Number")
number_1 = int(input("Enter the number: "))
squareroot(number_1)

elif select == 11:


PYTHON 10M Q&A

print("Cube Root of a Number")


number_1 = int(input("Enter the number: "))
cuberoot(number_1)

elif select == 12:


print("Sine of a Number")
number_1 = int(input("Enter the number: "))
sinx(number_1)

elif select == 13:


print("Cosine of a Number")
number_1 = int(input("Enter the number: "))
cosx(number_1)

elif select == 14:


print("Tan of a Number")
number_1 = int(input("Enter the number: "))
tanx(number_1)

elif select == 15:


print("Natural Logarithm of a Number")
number_1 = int(input("Enter the number: "))
natural_log(number_1)

elif select == 16:


print("Logarithm of a Number")
number_1 = int(input("Enter the number: "))
log(number_1)

elif select == 17:


print("Factorial of a Number")
number_1 = int(input("Enter the number: "))
factorial(number_1)

elif select == 18:


print("Roundoff of a Number")
number_1 = float(input("Enter the number: "))
PYTHON 10M Q&A

roundoff(number_1)

elif select == 19:


print("Floor of a Number")
number_1 = float(input("Enter the number: "))
floor(number_1)

elif select == 20:


print("Ceil of a Number")
number_1 = float(input("Enter the number: "))
ceil(number_1)

elif select == 21:


print("Absolute value of a Number")
number_1 = float(input("Enter the number: "))
absolute(number_1)

elif select == 22:


print("Value of PI")
PI_value()

elif select == 23:


print("Inverse of a Number")
number_1 = float(input("Enter the number: "))
inverse(number_1)

elif select == 24:


print("Random Numbers ")
number_1 = int(input("Enter ONLY INTEGER Starting Range
Number: "))
number_2 = int(input("Enter ONLY INTEGER Ending Range
Number: "))
random(number_1,number_2)

elif select == 25:


print("e power of a Number")
number_1 = float(input("Enter the number: "))
PYTHON 10M Q&A

e_x(number_1)

elif select == 26:


break
else:
break
OUTPUT:
Please select operation -
1. Add
2. Subtract
3. Multiply
4. Divide
5. Modular Division
6. 10^x
7. x^2
8. x^3
9. x^y
10. Square root of x
11. Cube Root(x)
12. Sin(x)
13. Cos(x)
14. Tan(x)
15. Natural Logarithm(ln)
16. Log
17. Factorial(x)
18. Roundoff(x)
19. Floor(x)
20. Ceil(x)
21. Abs(x)
22. PI
23. Inverse(x)
24. Random Number
25. e^x
26. Exit

Select operations from 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18 ,19, 20, 21, 22, 23, 24, 25, 26:1
PYTHON 10M Q&A

Addition of Two Numbers


Enter first number: 2
Enter second number: 3
2+3=5
Select operations from 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18 ,19, 20, 21, 22, 23, 24, 25, 26:

2. With an example, explain the following: procedure to


add new functions, parameters and arguments, local
variables and local parameters.
Ans-
Adding New Functions:
So far, we have only been using the functions that come
with Python, but it is also possible to add new functions. A
function definition specifies the name of a new function and
the sequence of statements that run when the function is
called.
Here is an example:
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print("I sleep all night and I work all
day.")
Parameters and Arguments:
Some of the functions we have seen require arguments. For
example, when you call math.sin you pass a number as an
argument. Some functions take more than one argument:
math.pow takes two, the base and the exponent.
Inside the function, the arguments are assigned to variables
called parameters. Here is a definition for a function that
takes an argument:
def print_twice(bruce):
print(bruce)
print(bruce)
PYTHON 10M Q&A

Variables and Parameters Are Local


When you create a variable inside a function, it is local,
which means that it only exists inside the function. For
example:
def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)

3. Consider turtle object. Compose functions to draw


triangle, rectangle, polygon, Star and circle.
Ans-
import turtle
t=turtle.Turtle()
t.pu()
t.goto(20,-151)
t.pd()
#Star
for i in range(5):
t.color("red")
t.fd(50)
t.rt(144)
t.pu()
t.goto(0,-180)
t.pd()
#Triangle
for i in range(3):
t.color("black")
t.fd(95)
t.lt(120)
t.goto(-20,-180)
PYTHON 10M Q&A

#Rectangle
for i in range(2):
t.color("red")
t.fd(132)
t.lt(90)
t.fd(83)
t.lt(90)
#Pentagon
for i in range(5):
t.color("blue")
t.fd(132)
t.lt(72)
#Hexagon
for i in range(6):
t.color("green")
t.fd(132)
t.lt(60)
#Septagon
for i in range(7):
t.color("black")
t.fd(132)
t.lt(51.42)
#Octagon
for i in range(8):
t.color("blue")
t.fd(132)
t.lt(45)
PYTHON 10M Q&A

#Nanogon
for i in range(9):
t.color("green")
t.fd(132)
t.lt(40)
#Decagon
for i in range(10):
t.color("red")
t.fd(132)
t.lt(36)
#circle
t.color("blue")
t.goto(45,-180)
t.circle(230,360)

OUTPUT:
PYTHON 10M Q&A

4. With neat example, Explain in detail about


conditional execution, Alternative Execution, Chained
Conditionals, Nested Conditionals.
Ans-
Conditional Execution:
The boolean expression after if is called the condition. If it
is true, the indented statement runs. If not, nothing
happens.
Eg: if x > 0:
print('x is positive')
Alternative Execution:
A second form of the if statement is “alternative
execution”, in which there are two possibilities and the
condition determines which one runs. The syntax looks
like this:
Eg: if x % 2 == 0:
print('x is even')
else:
print('x is odd')
If the condition is false, the second set of statements runs.
Since the condition must be true or false, exactly one of the
alternatives will run. The alternatives are called branches,
because they are branches in the flow of execution.

Chained Conditionals:
Sometimes there are more than two possibilities and we
need more than two branches. One way to express a
computation like that is a chained conditional:
Eg: if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
PYTHON 10M Q&A

print('x and y are equal')

elif is an abbreviation of “else if ”. Again, exactly one


branch will run. There is no limit on the number of elif
statements. If there is an else clause, it has to be at the end,
but there doesn’t have to be one.

Nested Conditionals:
One conditional can also be nested within another. We
could have written the exam‐ ple in the previous section
like this:

Eg: if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')

The outer conditional contains two branches. The first


branch contains a simple statement. The second branch
contains another if statement, which has two branches of
its own. Those two branches are both simple statements,
although they could have been conditional statements as
well.
Although the indentation of the statements makes the
structure apparent, nested conditionals become difficult to
read very quickly. It is a good idea to avoid them when
you can.
Logical operators often provide a way to simplify nested
conditional statements.
PYTHON 10M Q&A

5. Define incremental development. Write a procedure


with an example:
(i) To deal with complex programs.
(ii) To call one function from within another.
Ans-
Incremental Development
As you write larger functions, you might find yourself spending more
time debugging.To deal with increasingly complex programs, you
might want to try a process called incremental development. The
goal of incremental development is to avoid long debugging sessions
by adding and testing only a small amount of code at a time.
(i) As an example, suppose you want to find the distance between
two points, given by the coordinates (x1, y1) and (x2, y2) . By
the Pythagorean theorem, the distance is:

distance = x2 − x1 2 + y2 − y1 2

The first step is to consider what a distance function should


look like in Python. In other words, what are the inputs
(parameters) and what is the output (return value)?
In this case, the inputs are two points, which you can represent
using four numbers. The return value is the distance represented
by a floating-point value.
Immediately you can write an outline of the function:

def distance(x1, y1, x2, y2):


return 0.0
PYTHON 10M Q&A

Obviously, this version doesn’t compute distances; it always


returns zero. But it is syntactically correct, and it runs, which
means that you can test it before you make it more complicated.
To test the new function, call it with sample arguments:

>>> distance(1, 2, 4, 6)
0.0

I chose these values so that the horizontal distance is 3 and the


vertical distance is 4; that way, the result is 5, the hypotenuse
of a 3-4-5 triangle. When testing a function, it is useful to know
the right answer.
At this point we have confirmed that the function is
syntactically correct, and we can start adding code to the body.
A reasonable next step is to find the differences x2 − x1 and y2
− y1. The next version stores those values in temporary
variables and prints them:

def distance(x1, y1, x2, y2):


dx = x2 - x1
dy = y2 - y1
print('dx is', dx)
print('dy is', dy)
return 0.0

If the function is working, it should display dx is 3 and dy is 4.


If so, we know that the function is getting the right arguments
PYTHON 10M Q&A

and performing the first computation correctly. If not, there are


only a few lines to check.
Next we compute the sum of squares of dx and dy:
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
print('dsquared is: ', dsquared)
return 0.0

Again, you would run the program at this stage and check the
output (which should be 25). Finally, you can use math.sqrt to
compute and return the result:

def distance(x1, y1, x2, y2):


dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result
If that works correctly, you are done. Otherwise, you might
want to print the value of result before the return statement.
(ii) More Recursion
A recursive definition is similar to a circular definition, in the
sense that the definition contains a reference to the thing being
defined. A truly circular definition is not very useful:
PYTHON 10M Q&A

vorpal:
An adjective used to describe something that is vorpal.

If you saw that definition in the dictionary, you might be


annoyed. On the other hand, if you looked up the definition of
the factorial function, denoted with the symbol !, you might get
something like this:

0! = 1
n! = n n − 1 !

This definition says that the factorial of 0 is 1, and the factorial


of any other value, n, is n multiplied by the factorial of n-1.
So 3! is 3 times 2!, which is 2 times 1!, which is 1 times 0!.
Putting it all together, 3! equals 3 times 2 times 1 times 1, which
is 6.
If you can write a recursive definition of something, you can
write a Python program to evaluate it. The first step is to decide
what the parameters should be. In this case it should be clear
that factorial takes an integer:

def factorial(n):

If the argument happens to be 0, all we have to do is return 1:

def factorial(n):
PYTHON 10M Q&A

if n == 0:
return 1

Otherwise, and this is the interesting part, we have to make a


recursive call to find the factorial of n-1 and then multiply it by
n:

def factorial(n):
if n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
return result

6. Explain in detail about Variables, Expressions and


Statements in python.
Ans-
Variables, Expressions and Statements
One of the most powerful features of a programming
language is the ability to manipulate variables. A
variable is a name that refers to a value.
Assignment Statements
An assignment statement creates a new variable and
gives it a value:
PYTHON 10M Q&A

>>> message = 'And now for something completely


different'
>>> n = 17
>>> pi = 3.141592653589793
This example makes three assignments. The first assigns
a string to a new variable named message; the second
gives the integer 17 to n; the third assigns the
(approximate) value of π to pi.
A common way to represent variables on paper is to
write the name with an arrow pointing to its value. This
kind of figure is called a state diagram because it shows
what state each of the variables is in (think of it as the
variable’s state of mind).

Variable Names
Variable names can be as long as you like. They can
contain both letters and numbers, but they can’t begin
with a number. It is legal to use uppercase letters, but it
is conventional to use only lowercase for variables
names.
The underscore character, _, can appear in a name. It is
often used in names with multiple words, such as
your_name or airspeed_of_unladen_swallow.
If you give a variable an illegal name, you get a syntax
error:
>>> 76trombones = 'big parade'
SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
PYTHON 10M Q&A

>>> class = 'Advanced Theoretical Zymurgy'


SyntaxError: invalid syntax
76trombones is illegal because it begins with a number.
more@ is illegal because it contains an illegal character,
@. But what’s wrong with class?
It turns out that class is one of Python’s keywords. The
interpreter uses keywords to recognize the structure of
the program, and they cannot be used as variable names.
Python 3 has these keywords:

and del from None try


as elif global nonlocal while
assert else if not with
break except import or yield
class false in pass true
continue finally is raise
def for lambda return

Expressions and Statements


An expression is a combination of values, variables, and
operators. A value all by itself is considered an
expression, and so is a variable, so the following are all
legal expressions:
>>> 42
42
>>> n 17
>>> n + 25 42
When you type an expression at the prompt, the
interpreter evaluates it, which means that it finds the
PYTHON 10M Q&A

value of the expression. In this example, n has the value


17 and n + 25 has the value 42.
A statement is a unit of code that has an effect, like
creating a variable or displaying a value.
>>> n = 17
>>> print(n)
The first line is an assignment statement that gives a
value to n. The second line is a print statement that
displays the value of n.
When you type a statement, the interpreter executes it,
which means that it does whatever the statement says. In
general, statements don’t have values.

7. What is importance of keyboard input method? How


can it take arguments? Explain it with examples.
Ans-
Keyboard Input:
The programs we have written so far accept no input from
the user. They just do the same thing every time.
Python provides a built-in function called input that stops the
program and waits for the user to type something. When the
user presses Return or Enter, the program resumes and input
returns what the user typed as a string. In Python 2, the same
function is called raw_input.
PYTHON 10M Q&A

>>> text = input()


What are you waiting for?
>>> text
What are you waiting for?

Before getting input from the user, it is a good idea to print a


prompt telling the user what to type. input can take a prompt
as an argument:

>>> name = input('What...is your name?\n')


What...is your name?
Arthur, King of the Britons!
>>> name
Arthur, King of the Britons!

The sequence \n at the end of the prompt represents a newline,


which is a special character that causes a line break. That’s
why the user’s input appears below the prompt.
If you expect the user to type an integer, you can try to
convert the return value to int:

>>> prompt = 'What...is the airspeed velocity of an unladen


swallow?\n'
>>> speed = input(prompt)
What...is the airspeed velocity of an unladen swallow? 42
>>> int(speed)
42

But if the user types something other than a string of digits,


you get an error:

>>> speed = input(prompt)


What...is the airspeed velocity of an unladen swallow?
PYTHON 10M Q&A

What do you mean, an African or a European swallow?


>>> int(speed)
ValueError: invalid literal for int() with base 10

8. Explain variations of return statements in python.


Ans-
Return Values:
Calling the function generates a return value, which we usually
assign to a variable or use as part of an expression.

e = math.exp(1.0)
height = radius * math.sin(radians)

The functions we have written so far are void. Speaking


casually, they have no return value; more precisely, their return
value is None.
In this chapter, we are (finally) going to write fruitful functions.
The first example is
area, which returns the area of a circle with the given radius:

def area(radius):
a = math.pi * radius**2
return a

We have seen the return statement before, but in a fruitful


function the return statement includes an expression. This
statement means: “Return immediately from this function and
use the following expression as a return value.” The expression
can be arbitrarily complicated, so we could have written this
function more concisely:

def area(radius):
PYTHON 10M Q&A

return math.pi * radius**2

On the other hand, temporary variables like a can make


debugging easier. Sometimes it is useful to have multiple return
statements, one in each branch of a conditional:

def absolute_value(x):
if x < 0:
return -x
else:
return x

Since these return statements are in an alternative conditional,


only one runs.
As soon as a return statement runs, the function terminates
without executing any subsequent statements. Code that
appears after a return statement, or any other place the flow of
execution can never reach, is called dead code.
In a fruitful function, it is a good idea to ensure that every
possible path through the program hits a return statement. For
example:

def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x

This function is incorrect because if x happens to be 0, neither


condition is true, and the function ends without hitting a return
statement. If the flow of execution gets to the end of a function,
the return value is None, which is not the absolute value of 0:
PYTHON 10M Q&A

>>> absolute_value(0)
None

9. Write a python program to generate Fibonacci series.


Ans-
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10
if nterms<=0:
print("Please Enter a Positive Integer")
else:
print("Fibonacci Series:")
for i in range(nterms):
print(recur_fibo(i))

OUTPUT:
fibonacci series:
0
1
1
2
3
5
8
13
21
34
PYTHON 10M Q&A

10. Write a python program to compute factorial of a


given number using recursion. Give stack
representation for this program.
Ans-
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = int(input("enter a number: "))
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))

OUTPUT:
enter a number: 5
The factorial of 5 is 120

11. List 33 types of keywords in python3. Explain any


8 keywords with an example.
Ans-
List of Keywords in Python:
Keywords are the reserved words in Python. We cannot
use a keyword as a variable name, function name or any
other identifier.
PYTHON 10M Q&A

Here's a list of all keywords in Python Programming:

False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield

True, False

True and False are truth values in Python. They are the results of comparison
operations or logical (Boolean) operations in Python. For example:

>>> 1 == 1
True
>>> 5 > 3
True
>>> True or False
True
>>> 10 <= 1
False
>>> 3 > 7
False
>>> True and False
False

Here we can see that the first three statements are true so the interpreter
returns True and returns False for the remaining three
PYTHON 10M Q&A

statements. True and False in python is same as 1 and 0 . This can be justified
with the following example:

>>> True == 1
True
>>> False == 0
True
>>> True + True
2

None

None is a special constant in Python that represents the absence of a value or a


null value.
It is an object of its own datatype, the NoneType . We cannot create
multiple None objects but can assign it to variables. These variables will be equal
to one another.
We must take special care that None does not imply False , 0 or any empty list,
dictionary, string etc. For example:

>>> None == 0
False
>>> None == []
False
>>> None == False
False
>>> x = None
>>> y = None
>>> x == y
True

Void functions that do not return anything will return a None object
automatically. None is also returned by functions in which the program flow does
not encounter a return statement. For example:

def a_void_function():
a = 1
b = 2
c = a + b
PYTHON 10M Q&A

x = a_void_function()
print(x)

Output

None

This program has a function that does not return a value, although it does some
operations inside. So when we print x , we get None which is returned
automatically (implicitly). Similarly, here is another example:

def improper_return_function(a):
if (a % 2) == 0:
return True

x = improper_return_function(3)
print(x)

Output

None

Although this function has a return statement, it is not reached in every case.
The function will return True only when the input is even.
If we give the function an odd number, None is returned implicitly.
and, or , not

and , or , not are the logical operators in Python. and will result into True only if
both the operands are True . The truth table for and is given below:
Truth table for and

A B A and B

True True True

True False False

False True False


PYTHON 10M Q&A

False False False

or will result into True if any of the operands is True . The truth table for or is
given below:
Truth table for or

A B A or B

True True True

True False True

False True True

False False False

not operator is used to invert the truth value. The truth table for not is given
below:
Truth tabel for not

A not A

True False

False True

some example of their usage are given below

>>> True and False


False
>>> True or False
True
>>> not False
True

as

as is used to create an alias while importing a module. It means giving a


different name (user-defined) to a module while importing it.
PYTHON 10M Q&A

As for example, Python has a standard module called math . Suppose we want to
calculate what cosine pi is using an alias. We can do it as follows using as :

>>> import math as myAlias


>>>myAlias.cos(myAlias.pi)
-1.0

Here we imported the math module by giving it the name myAlias . Now we can
refer to the math module with this name. Using this name we calculated cos(pi)
and got -1.0 as the answer.
assert

assert is used for debugging purposes.


While programming, sometimes we wish to know the internal state or check if
our assumptions are true. assert helps us do this and find bugs more
conveniently. assert is followed by a condition.
If the condition is true, nothing happens. But if the condition is
false, AssertionError is raised. For example:

>>> a = 4
>>> assert a < 5
>>> assert a > 5
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
AssertionError

For our better understanding, we can also provide a message to be printed with
the AssertionError .

>>> a = 4
>>> assert a > 5, "The value of a is too small"
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
AssertionError: The value of a is too small

At this point we can note that,


PYTHON 10M Q&A

assert condition, message

is equivalent to,

if not condition:
raise AssertionError(message)

async, await

The async and await keywords are provided by the asyncio library in Python.
They are used to write concurrent code in Python. For example,

import asyncio

async def main():


print('Hello')
await asyncio.sleep(1)
print('world')

To run the program, we use

asyncio.run(main())

In the above program, the async keyword specifies that the function will be
executed asynchronously.
Here, first Hello is printed. The await keyword makes the program wait for 1
second. And then the world is printed.
break, continue

break and continue are used inside for and while loops to alter their normal
behavior.
break will end the smallest loop it is in and control flows to the statement
immediately below the loop. continue causes to end the current iteration of the
loop, but not the whole loop.
This can be illustrated with the following two examples:

for i in range(1,11):
PYTHON 10M Q&A

if i == 5:
break
print(i)

Output

1
2
3
4

Here, the for loop intends to print numbers from 1 to 10. But the if condition is
met when i is equal to 5 and we break from the loop. Thus, only the range 1 to 4
is printed.

for i in range(1,11):
if i == 5:
continue
print(i)

Output

1
2
3
4
6
7
8
9
10

Here we use continue for the same program. So, when the condition is met, that
iteration is skipped. But we do not exit the loop. Hence, all the values except 5
are printed out.
Learn more about Python break and continue statement.
class

class is used to define a new user-defined class in Python.


PYTHON 10M Q&A

Class is a collection of related attributes and methods that try to represent a


real-world situation. This idea of putting data and functions together in a class is
central to the concept of object-oriented programming (OOP).

Classes can be defined anywhere in a program. But it is a good practice to define


a single class in a module. Following is a sample usage:

class ExampleClass:
def function1(parameters):

def function2(parameters):

Learn more about Python Objects and Class.


def

def is used to define a user-defined function.


Function is a block of related statements, which together does some specific
task. It helps us organize code into manageable chunks and also to do some
repetitive task.

The usage of def is shown below:

def function_name(parameters):

Learn more about Python functions.


del

del is used to delete the reference to an object. Everything is object in Python.


We can delete a variable reference using del

>>> a = b = 5
>>> del a
>>> a
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
NameError: name 'a' is not defined
PYTHON 10M Q&A

>>> b
5

Here we can see that the reference of the variable a was deleted. So, it is no
longer defined. But b still exists.
del is also used to delete items from a list or a dictionary:

>>> a = ['x','y','z']
>>> del a[1]
>>> a
['x', 'z']

if, else, elif

if, else, elif are used for conditional branching or decision making.
When we want to test some condition and execute a block only if the condition
is true, then we use if and elif . elif is short for else if. else is the block which is
executed if the condition is false. This will be clear with the following example:

def if_example(a):
if a == 1:
print('One')
elif a == 2:
print('Two')
else:
print('Something else')

if_example(2)
if_example(4)
if_example(1)

Output

Two
Something else
One

Here, the function checks the input number and prints the result if it is 1 or 2.
Any input other than this will cause the else part of the code to execute.
Learn more about Python if and if...else Statement.
PYTHON 10M Q&A

except, raise, try

except, raise, try are used with exceptions in Python.


Exceptions are basically errors that suggests something went wrong while
executing our
program. IOError , ValueError , ZeroDivisionError , ImportError , NameError , TypeErr
or etc. are few examples of exception in Python. try...except blocks are used to
catch exceptions in Python.
We can raise an exception explicitly with the raise keyword. Following is an
example:

def reciprocal(num):
try:
r = 1/num
except:
print('Exception caught')
return
return r

print(reciprocal(10))
print(reciprocal(0))

Output

0.1
Exception caught
None

Here, the function reciprocal() returns the reciprocal of the input number.
When we enter 10, we get the normal output of 0.1. But when we input 0,
a ZeroDivisionError is raised automatically.
This is caught by our try…except block and we return None . We could have also
raised the ZeroDivisionError explicitly by checking the input and handled it
elsewhere as follows:

if num == 0:
raise ZeroDivisionError('cannot divide')

finally
PYTHON 10M Q&A

finally is used with try…except block to close up resources or file streams.


Using finally ensures that the block of code inside it gets executed even if there
is an unhandled exception. For example:

try:
Try-block
except exception1:
Exception1-block
except exception2:
Exception2-block
else:
Else-block
finally:
Finally-block

Here if there is an exception in the Try-block , it is handled in


the except or else block. But no matter in what order the execution flows, we
can rest assured that the Finally-block is executed even if there is an error. This
is useful in cleaning up the resources.
Learn more about exception handling in Python programming.
for

for is used for looping. Generally we use for when we know the number of times
we want to loop.
In Python we can use it with any type of sequences like a list or a string. Here is
an example in which for is used to traverse through a list of names:

names = ['John','Monica','Steven','Robin']
for i in names:
print('Hello '+i)

Output

Hello John
Hello Monica
Hello Steven
Hello Robin

Learn more about Python for loop.


PYTHON 10M Q&A

from, import

import keyword is used to import modules into the current


namespace. from…import is used to import specific attributes or functions into
the current namespace. For example:

import math

will import the math module. Now we can use the cos() function inside it
as math.cos() . But if we wanted to import just the cos() function, this can done
using from as

from math import cos

now we can use the function simply as cos() , no need to write math.cos() .
Learn more on Python modules and import statement.
global

global is used to declare that a variable inside the function is global (outside the
function).
If we need to read the value of a global variable, it is not necessary to define it
as global . This is understood.
If we need to modify the value of a global variable inside a function, then we
must declare it with global . Otherwise, a local variable with that name is
created.
Following example will help us clarify this.

globvar = 10
def read1():
print(globvar)
def write1():
global globvar
globvar = 5
def write2():
globvar = 15

read1()
write1()
PYTHON 10M Q&A

read1()
write2()
read1()

Output

10
5
5

Here, the read1() function is just reading the value of globvar . So, we do not
need to declare it as global . But the write1() function is modifying the value, so
we need to declare the variable as global .
We can see in our output that the modification did take place (10 is changed to
5). The write2() also tries to modify this value. But we have not declared it
as global .
Hence, a new local variable globvar is created which is not visible outside this
function. Although we modify this local variable to 15, the global variable
remains unchanged. This is clearly visible in our output.
in

in is used to test if a sequence (list, tuple, string etc.) contains a value. It


returns True if the value is present, else it returns False . For example:

>>> a = [1, 2, 3, 4, 5]
>>> 5 in a
True
>>> 10 in a
False

The secondary use of in is to traverse through a sequence in a for loop.

for i in 'hello':
print(i)

Output

h
e
l
PYTHON 10M Q&A

l
o

is

is is used in Python for testing object identity. While the == operator is used to
test if two variables are equal or not, is is used to test if the two variables refer
to the same object.
It returns True if the objects are identical and False if not.

>>> True is True


True
>>> False is False
True
>>> None is None
True

We know that there is only one instance of True , False and None in Python, so
they are identical.

>>> [] == []
True
>>> [] is []
False
>>> {} == {}
True
>>> {} is {}
False

An empty list or dictionary is equal to another empty one. But they are not
identical objects as they are located separately in memory. This is because list
and dictionary are mutable (value can be changed).

>>> '' == ''


True
>>> '' is ''
True
>>> () == ()
True
>>> () is ()
True
PYTHON 10M Q&A

Unlike list and dictionary, string and tuple are immutable (value cannot be
altered once defined). Hence, two equal string or tuple are identical as well.
They refer to the same memory location.

lambda

lambda is used to create an anonymous function (function with no name). It is an


inline function that does not contain a return statement. It consists of an
expression that is evaluated and returned. For example:

a = lambda x: x*2
for i in range(1,6):
print(a(i))

Output

2
4
6
8
10

Here, we have created an inline function that doubles the value, using
the lambda statement. We used this to double the values in a list containing 1 to
5.
Learn more about Python lamda function.
nonlocal

The use of nonlocal keyword is very much similar to


the global keyword. nonlocal is used to declare that a variable inside a nested
function (function inside a function) is not local to it, meaning it lies in the outer
inclosing function. If we need to modify the value of a non-local variable inside a
nested function, then we must declare it with nonlocal . Otherwise a local
variable with that name is created inside the nested function. Following
example will help us clarify this.

def outer_function():
a = 5
PYTHON 10M Q&A

def inner_function():
nonlocal a
a = 10
print("Inner function: ",a)
inner_function()
print("Outer function: ",a)

outer_function()

Output

Inner function: 10
Outer function: 10

Here, the inner_function() is nested within the outer_function .


The variable a is in the outer_function() . So, if we want to modify it in
the inner_function() , we must declare it as nonlocal . Notice that a is not a global
variable.
Hence, we see from the output that the variable was successfully modified
inside the nested inner_function() . The result of not using the nonlocal keyword
is as follows:

def outer_function():
a = 5
def inner_function():
a = 10
print("Inner function: ",a)
inner_function()
print("Outer function: ",a)

outer_function()

Output

Inner function: 10
Outer function: 5

Here, we do not declare that the variable a inside the nested function
is nonlocal . Hence, a new local variable with the same name is created, but the
non-local a is not modified as seen in our output.
PYTHON 10M Q&A

pass

pass is a null statement in Python. Nothing happens when it is executed. It is


used as a placeholder.
Suppose we have a function that is not implemented yet, but we want to
implement it in the future. Simply writing,

def function(args):

in the middle of a program will give us IndentationError . Instead of this, we


construct a blank body with the pass statement.

def function(args):
pass

We can do the same thing in an empty class as well.

class example:
pass

return

return statement is used inside a function to exit it and return a value.


If we do not return a value explicitly, None is returned automatically. This is
verified with the following example.

def func_return():
a = 10
return a

def no_return():
a = 10

print(func_return())
print(no_return())

Output

10
None
PYTHON 10M Q&A

while

while is used for looping in Python.


The statements inside a while loop continue to execute until the condition for
the while loop evaluates to False or a break statement is encountered. Following
program illustrates this.

i = 5
while(i):
print(i)
i = i – 1

Output

5
4
3
2
1

Note that 0 is equal to False .


Learn more about Python while loop.
with

with statement is used to wrap the execution of a block of code within methods
defined by the context manager.
Context manager is a class that implements __enter__ and __exit__ methods.
Use of with statement ensures that the __exit__ method is called at the end of
the nested block. This concept is similar to the use of try…finally block. Here, is
an example.

with open('example.txt', 'w') as my_file:


my_file.write('Hello world!')

This example writes the text Hello world! to the file example.txt . File objects
have __enter__ and __exit__ method defined within them, so they act as their
own context manager.
PYTHON 10M Q&A

First the __enter__ method is called, then the code within with statement is
executed and finally the __exit__ method is called. __exit__ method is called
even if there is an error. It basically closes the file stream.
yield

yield is used inside a function like a return statement. But yield returns a
generator.
Generator is an iterator that generates one item at a time. A large list of values
will take up a lot of memory. Generators are useful in this situation as it
generates only one value at a time instead of storing all the values in memory.
For example,

>>> g = (2**x for x in range(100))

will create a generator g which generates powers of 2 up to the number two


raised to the power 99. We can generate the numbers using the next() function
as shown below.

>>> next(g)
1
>>> next(g)
2
>>> next(g)
4
>>> next(g)
8
>>> next(g)
16

And so on… This type of generator is returned by the yield statement from a
function. Here is an example.

def generator():
for i in range(6):
yield i*i

g = generator()
for i in g:
PYTHON 10M Q&A

print(i)

Output

0
1
4
9
16
25

Here, the function generator() returns a generator that generates square of


numbers from 0 to 5. This is printed in the for loop

12. Given n+r+1 = 2r. n is the input and r is to be


determined. Write a program which computes
minimum value of r that satisfies the above.
Ans-
def gcd(n, r):

# Everything divides 0
if (n == 0 or r == 0):
return 0;

# base case
if (n == r):
return n;

# n is greater
if (n > r):
return gcd(n - r, r);
return gcd(n, r - n);

def findMin( n, r):


PYTHON 10M Q&A

# If GCD is not 1, then


# there is no such value,
# else value is obtained
# using "n*r-n-r+1'
if(gcd(n, r) == 1):
return (n * r - n - r + 1)
else:
return -1

# Driver code
n = 4;
r = 7;
print(findMin(n, r));

OUTPUT:
18

You might also like