Python 10M Q&A
Python 10M Q&A
Python 10M Q&A
def cube(num1):
print(num1, "^","3" , "=",pow(num1,3))
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
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)
roundoff(number_1)
e_x(number_1)
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
#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
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
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')
distance = x2 − x1 2 + y2 − y1 2
>>> distance(1, 2, 4, 6)
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:
vorpal:
An adjective used to describe something that is vorpal.
0! = 1
n! = n n − 1 !
def factorial(n):
def factorial(n):
PYTHON 10M Q&A
if n == 0:
return 1
def factorial(n):
if n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
return result
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
e = math.exp(1.0)
height = radius * math.sin(radians)
def area(radius):
a = math.pi * radius**2
return a
def area(radius):
PYTHON 10M Q&A
def absolute_value(x):
if x < 0:
return -x
else:
return x
def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x
>>> absolute_value(0)
None
OUTPUT:
fibonacci series:
0
1
1
2
3
5
8
13
21
34
PYTHON 10M Q&A
OUTPUT:
enter a number: 5
The factorial of 5 is 120
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 == 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
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
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
as
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 :
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
>>> 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
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
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 ExampleClass:
def function1(parameters):
…
def function2(parameters):
…
def function_name(parameters):
…
>>> 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 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
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
try:
Try-block
except exception1:
Exception1-block
except exception2:
Exception2-block
else:
Else-block
finally:
Finally-block
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
from, import
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
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
>>> a = [1, 2, 3, 4, 5]
>>> 5 in a
True
>>> 10 in a
False
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.
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).
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
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
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
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
def function(args):
def function(args):
pass
class example:
pass
return
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
i = 5
while(i):
print(i)
i = i – 1
Output
5
4
3
2
1
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.
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,
>>> 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
# 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);
# Driver code
n = 4;
r = 7;
print(findMin(n, r));
OUTPUT:
18