Q.1. What does the following code output?
>>> def extendList(val, list=[]):
list.append(val)
return list
>>> list1 = extendList(10)
>>> list2 = extendList(123,[])
>>> list3 = extendList('a')
>>> list1,list2,list3
Ans. ([10, ‘a’], [123], [10, ‘a’])
You’d expect the output to be something like this:
([10],[123],[‘a’])
Well, this is because the list argument does not initialize to its default value ([]) every time we make a call to the function. Once we define the function, it creates a new list. Then, whenever we call it again without a list argument, it uses the same list. This is because it calculates the expressions in the default arguments when we define the function, not when we call it.
Q.2. What is a decorator?
Ans. A decorator is a function that adds functionality to another function without modifying it. It wraps another function to add functionality to it. Take an example.
>>> def decor(func):
def wrap():
print("$$$$$$$$$$$$$$$$$")
func()
print("$$$$$$$$$$$$$$$$$")
return wrap
>>> @decor
def sayhi():
print("Hi")
>>> sayhi()
$$$$$$$$$$$$$$$$$
Hi
$$$$$$$$$$$$$$$$$
Decorators are an example of metaprogramming, where one part of the code tries to change another. For more on decorators, read Python
Decorators.
Q.3. Write a regular expression that will accept an email id. Use the re module.
Ans.
>>> import re
>>> e=re.search(r'[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$','ayushiwashere@gmail.com')
>>> e.group()
‘ayushiwashere@gmail.com’
To brush up on regular expressions, check Regular Expressions in Python.
Q.4. How many arguments can the range() function take?
Ans. The range() function in Python can take up to 3 arguments. Let’s see this one by one.
a. One argument
When we pass only one argument, it takes it as the stop value. Here, the start value is 0, and the step value is +1.
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(-5))
[]
>>> list(range(0))
[] b. Two arguments
When we pass two arguments, the first one is the start value, and the second is the stop value.
>>> list(range(2,7))
[2, 3, 4, 5, 6]
>>> list(range(7,2))
[]
>>> list(range(-3,4))
[-3, -2, -1, 0, 1, 2, 3]
c. Three arguments
Here, the first argument is the start value, the second is the stop value, and the third is the step value.
>>> list(range(2,9,2))
[2, 4, 6, 8]
>>> list(range(9,2,-1))
[9, 8, 7, 6, 5, 4, 3]
Q.5. Does Python have a switch-case statement?
Ans. In languages like C++, we have something like this:
switch(name)
{
case ‘Ayushi’:
cout<<”Monday”;
break;
case ‘Megha’:
cout<<”Tuesday”;
break;
default:
cout<<”Hi, user”;
}
But in Python, we do not have a switch-case statement. Here, you may write a switch function to use. Else, you may use a set of if-elif-else statements. To implement a function for this, we may use a dictionary.
>>> def switch(choice):
switcher={
'Ayushi':'Monday',
'Megha':'Tuesday',
print(switcher.get(choice,'Hi, user'))
return
>>> switch('Megha')
Tuesday
>>> switch('Ayushi')
Monday
>>> switch('Ruchi')
No comments:
Post a Comment