Which of the following is an invalid variable?
- my_day_2
- 2nd_day
- Day_two
- _2
Answer
2nd_day
Reason — Variable names cannot begin with a number, although they can contain numbers.
Find the invalid identifier from the following:
- name
- break
- section
- mark12
Answer
break
Reason — break is a reserved keyword.
Which of the following is not a keyword?
- eval
- assert
- nonlocal
- pass
Answer
eval
Reason — eval is not a keyword in python.
Which of the following cannot be a variable?
- _init_
- in
- it
- on
Answer
in
Reason — in is a keyword in python.
Which of these is not a core data type?
- Lists
- Dictionary
- Tuples
- Class
Answer
Class
Reason — Class is not a core data type.
How would you write xy in Python as an expression ?
- x^y
- x**y
- x^^y
- none of these
Answer
x**y
Reason — ** is an arithmetic operator used for exponentiation.
What will be the value of the expression?
14 + 13 % 15
- 14
- 27
- 12
- 0
Answer
27
Reason — According to operator precedence remainder (%) operation will be done first and then addition (+) will be done.
14 + 13 % 15
= 14 + 13
= 27
Evaluate the expression given below if A = 16 and B = 15.
A % B // A
- 0.0
- 0
- 1.0
- 1
Answer
0
Reason — According to operator precedence, floor division (//) and remainder (%) both have equal precedence hence the expression will be evaluated from left to right.
A % B // A
= 16 % 15 // 16
= 1 // 16
= 0
What is the value of x?
x = int(13.25 + 4/2)
- 17
- 14
- 15
- 23
Answer
15
Reason — According to operator precedence, division will be done first followed by addition and then it will convert to integer.
x = int(13.25 + 4/2)
x = int(13.25 + 2.0)
x = int(15.45)
x = 15
The expression 8/4/2 will evaluate equivalent to which of the following expressions:
- 8/(4/2)
- (8/4)/2
Answer
(8/4)/2
Reason — As both the operators are division operators, the expression will be evaluated from left to right.
8/4/2 = 2/2 = 1.0
(8/4)/2
= 2/2
= 1.0
Which among the following list of operators has the highest precedence?
+, -, **, %, /, <<, >>, |
- <<, >>
- **
- I
- %
Answer
**
Reason — ** has highest precedence.
Which of the following expressions results in an error?
- float('12')
- int('12')
- float('12.5')
- int('12.5')
Answer
int('12.5')
Reason — int() are positive or negative whole numbers with no decimal point.
Which of the following statement prints the shown output below?
hello\example\test.txt
- print("hello\example\test.txt")
- print("hello\\example\\test.txt")
- print("hello\"example\"test.txt")
- print("hello"\example"\test.txt")
Answer
print("hello\\example\\test.txt")
Reason — Escape sequence (\\) is used for Backslash (\).
Which value type does input() return ?
- Boolean
- String
- Int
- Float
Answer
String
Reason — The input() function always returns a value of String type.
Which two operators can be used on numeric values in Python?
- @
- %
- +
- #
Answer
%, +
Reason — %, + are arithmetic operators.
Which of the following four code fragments will yield following output?
Eina
Mina
Dika
Select all of the function calls that result in this output
- print('''Eina
\nMina
\nDika''') - print('''EinaMinaDika''')
- print('Eina\nMina\nDika')
- print('Eina
Mina
Dika')
Answer
print('Eina\nMina\nDika')
Reason —
- print('''Eina
\nMina
\nDika''') — It is a multiline string and by adding \n extra line will be added. - print('''EinaMinaDika''') — There is no new line character.
- print('Eina\nMina\nDika') — It adds new line by \n new line character.
- print('Eina
Mina
Dika') — It creates an error because it is a multiline string with no triple quotes.
Which of the following is valid arithmetic operator in Python :
- //
- ?
- <
- and
Answer
//
Reason — // is valid arithmetic operator in Python.
For a given declaration in Python as s = "WELCOME", which of the following will be the correct output of print(s[1::2])?
- WEL
- COME
- WLOE
- ECM
Answer
ECM
Reason — The slicing will start from index 1 and return at every alternative step.
s[1] = E
s[3] = C
s[5] = M
output = ECM
Which of the following is an incorrect Logical operator in Python?
- not
- in
- or
- and
Answer
in
Reason — in
is a membership operator.
Which of the following is not a Tuple in Python?
- (1,2,3)
- ("One","Two","Three")
- (10,)
- ("One")
Answer
("One")
Reason — ("One") is a string data type.
The smallest individual unit in a program is known as a token.
A token is also called a lexical unit.
A keyword is a word having special meaning and role as specified by programming language.
The data types whose values cannot be changed in place are called immutable types.
In a Python expression, when conversion of a value's data type is done automatically by the compiler without programmer's intervention, it is called implicit type conversion.
The explicit conversion of an operand to a specific type is called type casting.
The pass statement is an empty statement in Python.
A break statement skips the rest of the loop and jumps over to the statement following the loop.
The continue statement skips the rest of the loop statements and causes the next iteration of the loop to take place.
Python's keywords cannot be used as variable name.
The expression int(x) implies that the variable x is converted to integer.
Answer
True
Reason — int(x) explicitly converts variable x to integer type.
The value of the expressions 4/(3*(2 - 1)) and 4/3*(2 - 1) is the same.
Answer
True
Reason — Parentheses has first precedence then multiplication then division has precedence.
4/(3*(2-1))
= 4/(3*1)
= 4/3
= 1.33333
4/3*(2-1)
= 4/3*1
= 4/3
= 1.33333
The value of the expressions 4/(3*(4 - 2)) and 4/3*(4 - 2) is the same.
Answer
False
Reason — Parentheses has first precedence then multiplication then division has precedence.
4/(3*(4-2))
= 4/(3*2)
= 4/6
= 0.6666
4/3*(4-2)
= 4/3*2
= 1.3333*2
= 2.6666
The expression 2**2**3 is evaluated as: (2**2)**3.
Answer
False
Reason — The expression 2**2**3 is evaluated as: 2**(2**3) because exponentiation operates from right to left (i.e., it is right associative).
A string can be surrounded by three sets of single quotation marks or by three sets of double quotation marks.
Answer
True
Reason — A string literal is a sequence of characters surrounded by single or double or triple double quotes or triple single quotes.
Variables can be assigned only once.
Answer
False
Reason — Python supports dynamic typing i.e., a variable can hold values of different types at different times.
In Python, a variable is a placeholder for data.
Answer
False
Reason — Variables represent labelled storage locations, whose values can be manipulated during program run.
In Python, only if statement has else clause.
Answer
False
Reason — Loops in Python can have else clause too.
Python loops can also have else clause.
Answer
True
Reason — Loops in Python can have else clause.
In a nested loop, a break statement terminates all the nested loops in one go.
Answer
False
Reason — In nested loops, a break statement will terminate the very loop it appears in.
Assertion. Assigning a new value to an int variable creates a new variable internally.
Reason. The int type is immutable data type of Python.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
In python, literal values have fixed memory locations and variable names reference them as values. This means that, although we can change the value of an integer variable, the process involves creating a new integer object with the updated value. Literal values, such as 10, have fixed memory locations, and variables act as references to these values. When we assign a new value to an integer variable, we are essentially creating a new object, and the variable now points to this new object. Hence, both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Assertion. """A Sample Python String""" is a valid Python String.
Reason. Triple Quotation marks are not valid in Python.
Answer
(c)
Assertion is true but Reason is false.
Explanation
A string literal is a sequence of characters surrounded by single or double or triple single quotes or triple double quotes.
Assertion. If and For are legal statements in Python.
Reason. Python is case sensitive and its basic selection and looping statements are in lower case.
Answer
(d)
Assertion is false but Reason is true.
Explanation
if is conditional statement and for is loop statement. Python is case sensitive and its selection and looping statements are in lower case.
Assertion. if and for are legal statements in Python.
Reason. Python is case sensitive and its basic selection and looping statements are in lower case.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
if is conditional statement and for is loop statement. Python is case sensitive and its selection and looping statements are in lower case.
Assertion. The break statement can be used with all selection and iteration statements.
Reason. Using break with an if statement is of no use unless the if statement is part of a looping construct.
Answer
(e)
Both Assertion and Reason are false.
Explanation
In python, the break statement can be used with iteration statements only. Using break with conditional statements will result in syntax error — SyntaxError: 'break' outside loop
Assertion. The break statement can be used with all selection and iteration statements.
Reason. Using break with an if statement will give no error.
Answer
(e)
Both Assertion and Reason are false.
Explanation
In python, the break statement can be used with iteration statements only. Using break with conditional statements will result in syntax error — SyntaxError: 'break' outside loop
What are tokens in Python? How many types of tokens are allowed in Python? Exemplify your answer.
Answer
The smallest individual unit in a program is known as a Token. Python has following tokens:
- Keywords — Examples are import, for, in, while, etc.
- Identifiers — Examples are MyFile, _DS, DATE_9_7_77, etc.
- Literals — Examples are "abc", 5, 28.5, etc.
- Operators — Examples are +, -, >, or, etc.
- Punctuators — ' " # () etc.
How are keywords different from identifiers?
Answer
Keywords are reserved words carrying special meaning and purpose to the language compiler/interpreter. For example, if, elif, etc. are keywords. Identifiers are user defined names for different parts of the program like variables, objects, classes, functions, etc. Identifiers are not reserved. They can have letters, digits and underscore. They must begin with either a letter or underscore. For example, _chk, chess, trail, etc.
What are literals in Python? How many types of literals are allowed in Python?
Answer
Literals are data items that have a fixed value. The different types of literals allowed in Python are:
- String literals
- Numeric literals
- Boolean literals
- Special literal None
- Literal collections
State True or False : "Variable declaration is implicit in Python."
Answer
True.
Reason — In Python, variable declaration is implicit. This means that we don't need to explicitly declare the data type of a variable before using it. The type of a variable is determined dynamically at runtime based on the assigned value. For example:
x = 5 # x is implicitly declared as an integer
name = "Ravi" # name is implicitly declared as a string
Out of the following, find those identifiers, which cannot be used for naming Variables or Functions in a Python program:
- Price*Qty
- class
- For
- do
- 4thCol
- totally
- Row31
- _Amount
Answer
- Price*Qty ⇒ Contains special character *
- class ⇒ It is a keyword
- 4thCol ⇒ Begins with a digit
Find the invalid identifier from the following :
- MyName
- True
- 2ndName
- My_Name
Answer
The invalid identifier are:
2ndName ⇒ Begins with a digit
True ⇒ It is a keyword
Which of the following is an invalid datatype in Python ?
- Set
- None
- Integer
- Real
Answer
Real
Reason — Real is not a standard built-in data type in Python.
Identify the valid arithmetic operator in Python from the following:
- ?
- <
- **
- and
Answer
**
Reason — Let's go through each option and see if its valid arithmetic operator or not:
- ? — The question mark is not a valid arithmetic operator in Python.
- < — It is a relational operator.
- ** — It is an arithmetic operator.
- and — It is a logical operator.
How are floating constants represented in Python? Give examples to support your answer.
Answer
Floating constants are represented in Python in two forms — Fractional Form and Exponent form. Examples:
- Fractional Form — 2.0, 17.5, -13.0, -0.00625
- Exponent form — 152E05, 1.52E07, 0.152E08, -0.172E-3
How are string-literals represented and implemented in Python?
Answer
A string-literal is represented as a sequence of characters surrounded by quotes (single, double or triple quotes). String-literals in Python are implemented using Unicode.
What are operators ? What is their function? Give examples of some unary and binary operators.
Answer
Operators are tokens that trigger some computation/action when applied to variables and other objects in an expression. Unary plus (+), Unary minus (-), Bitwise complement (~), Logical negation (not) are a few examples of unary operators. Examples of binary operators are Addition (+), Subtraction (-), Multiplication (*), Division (/).
Which of the following are valid operators in Python:
- **
- */
- like
- ||
- is
- ^
- between
- in
Answers
The valid operators are:
** ⇒ Exponentiation operator
is ⇒ Identity operator
^ ⇒ Bitwise XOR operator
in ⇒ Membership operator
What is an expression and a statement?
Answer
An expression is any legal combination of symbols that represents a value. For example, 2.9, a + 5, (3 + 5) / 4.
A statement is a programming instruction that does something i.e. some action takes place. For example:
print("Hello")
a = 15
b = a - 10
What all components can a Python program contain?
Answer
A Python program can contain various components like expressions, statements, comments, functions, blocks and indentation.
What are variables? How are they important for a program?
Answer
Variables are named labels whose values can be used and processed during program run. Variables are important for a program because they enable a program to process different sets of data.
Consider the given expression: not True and False or True
Which of the following will be correct output if the given expression is evaluated?
- True
- False
- None
- Null
Answer
True
Reason — The 'not' operator has the highest precedence, followed by 'and', which has precedence over 'or', and the evaluation proceeds from left to right.
not True and False or True
= False and False or True
= False or True
= True
Describe the concepts of block and body. What is indentation and how is it related to block and body?
Answer
A block in Python, represents a group of statements executed as a single unit. Python uses indentation to create blocks of code. Statements at same indentation level are part of same block/suite and constitute the body of the block.
What are data types? How are they important?
Answer
Data types are used to identify the type of data a memory location can hold and the associated operations of handling it. The data that we deal with in our programs can be of many types like character, integer, real number, string, boolean, etc. hence programming languages including Python provide ways and facilities to handle all these different types of data through data types. The data types define the capabilities to handle a specific type of data such as memory space it allocates to hold a certain type of data and the range of values supported for a given data type, etc.
Write the names of any four data types available in Python.
Answer
The names of any four data types in Python are:
- Integer
- String
- List
- Tuple
How many integer types are supported by Python? Name them.
Answer
Two integer types are supported by Python. They are:
- Integers (signed)
- Booleans
What are immutable and mutable types? List immutable and mutable types of Python.
Answer
Mutable types are those whose values can be changed in place whereas Immutable types are those that can never change their value in place.
Mutable types in Python are:
- Lists
- Dictionaries
- Sets
Immutable types in Python are:
- Integers
- Floating-Point numbers
- Booleans
- Strings
- Tuples
What is the difference between implicit type conversion and explicit type conversion?
Answer
Implicit Type Conversion | Explicit Type Conversion |
---|---|
An implicit type conversion is automatically performed by the compiler when differing data types are intermixed in an expression. | An explicit type conversion is user-defined conversion that forces an expression to be of specific type. |
An implicit type conversion is performed without programmer's intervention. | An explicit type conversion is specified explicitly by the programmer. |
Example: a, b = 5, 25.5 c = a + b | Example: a, b = 5, 25.5 c = int(a + b) |
An immutable data type is one that cannot change after being created. Give three reasons to use immutable data.
Answer
Three reasons to use immutable data types are:
- Immutable data types increase the efficiency of the program as they are quicker to access than mutable data types.
- Immutable data types helps in efficient use of memory storage as different variables containing the same value can point to the same memory location. Immutability guarantees that contents of the memory location will not change.
- Immutable data types are thread-safe so they make it easier to parallelize the program through multi-threading.
What is entry controlled loop? Which loop is entry controlled loop in Python?
Answer
An entry-controlled loop checks the condition at the time of entry. Only if the condition is true, the program control enters the body of the loop. In Python, for and while loops are entry-controlled loops.
Explain the use of the pass statement. Illustrate it with an example.
Answer
The pass statement of Python is a do nothing statement i.e. empty statement or null operation statement. It is useful in scenarios where syntax of the language requires the presence of a statement but the logic of the program does not. For example,
for i in range(10):
if i == 2:
pass
else:
print("i =", i)
Rewrite the adjacent code in python after removing all syntax error(s). Underline each correction done in the code.
30 = To
for K in range(0,To)
IF k%4 == 0:
print(K * 4)
Else:
print(K+3).
Answer
The corrected code is shown below:
To = 30 # Correction 1
for K in range(0,To): # Correction 2
if K % 4 == 0: # Correction 3
print(K * 4)
else: # Correction 4
print(K+3) # Correction 5
Explanation
Correction 1 — Variable should be on left side and literals should be on right side.
Correction 2 — Semi-colon was missing in the for loop syntax.
Correction 3 — if statement should be in lower case.
Correction 4 — else statement should be in lower case.
Correction 5 — Full stop should not be there at the end of print function.
Below are seven segments of code, each with a part coloured. Indicate the data type of each coloured part by choosing the correct type of data from the following type.
(a) int
(b) float
(c) bool
(d) str
(e) function
(f) list of int
(g) list of str
(i)
if temp < 32 :
print ("Freezing")
(ii)
L = ['Hiya', 'Zoya', 'Preet']
print(L[1])
(iii)
M = []
for i in range (3) :
M.append(i)
print(M)
(iv)
L = ['Hiya', 'Zoya', 'Preet']
n = len(L)
if 'Donald' in L[1 : n] :
print(L)
(v)
if n % 2 == 0 :
print("Freezing")
(vi)
L = inputline.split()
while L != ( ) :
print(L)
L = L[1 :]
(vii)
L = ['Hiya', 'Zoya', 'Preet']
print(L[0] + L[1])
Answer
(i) bool
(ii) str
(iii) list of int
(iv) int
(v) bool
(vi) list of str
(vii) str
Write the output of the following Python code:
for i in range(2,7,2):
print(i*'$')
Answer
$$
$$$$
$$$$$$
range(2,7,2)
returns [2, 4, 6] as it defines a range of 2 to 6 with a step of 2. The loop iterates as below:
- For
i = 2
, it prints$$
. - For
i = 4
, it prints$$$$
. - For
i = 6
, it prints$$$$$$
.
Fill in the missing lines of code in the following code. The code reads in a limit amount and a list of prices and prints the largest price that is less than the limit. You can assume that all prices and the limit are positive numbers. When a price 0 is entered the program terminates and prints the largest price that is less than the limit.
#Read the limit
limit = float(input("Enter the limit"))
max_price = 0
# Read the next price
next_price = float(input("Enter a price or 0 to stop:"))
while next_price > 0 :
<write your code here>
#Read the next price
<write your code here>
if max_price > 0:
<write your code here>
else :
<write your code here>
Answer
#Read the limit
limit = float(input("Enter the limit"))
max_price = 0
# Read the next price
next_price = float(input("Enter a price or 0 to stop:"))
while next_price > 0 :
if next_price < limit and next_price > max_price:
max_price = next_price
#Read the next price
next_price = float(input("Enter a price or 0 to stop:"))
if max_price > 0:
print("Largest Price =", max_price)
else :
print("Prices exceed limit of", limit);
Predict the output of the following code fragments:
count = 0
while count < 10:
print ("Hello")
count += 1
Answer
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Predict the output of the following code fragments:
x = 10
y = 0
while x > y:
print (x, y)
x = x - 1
y = y + 1
Answer
10 0
9 1
8 2
7 3
6 4
x | y | Output | Remarks |
---|---|---|---|
10 | 0 | 10 0 | 1st Iteration |
9 | 1 | 10 0 9 1 | 2nd Iteration |
8 | 2 | 10 0 9 1 8 2 | 3rd Iteration |
7 | 3 | 10 0 9 1 8 2 7 3 | 4th Iteration |
6 | 4 | 10 0 9 1 8 2 7 3 6 4 | 5th Iteration |
Predict the output of the following code fragments:
keepgoing = True
x=100
while keepgoing :
print (x)
x = x - 10
if x < 50 :
keepgoing = False
Answer
100
90
80
70
60
50
Inside while loop, the line x = x - 10
is decreasing x by 10 so after 5 iterations of while loop x will become 40. When x becomes 40, the condition if x < 50
becomes true so keepgoing
is set to False
due to which the while loop stops iterating.
Predict the output of the following code fragments:
x = 45
while x < 50 :
print (x)
Answer
This is an endless (infinite) loop that will keep printing 45 continuously.
As the loop control variable x is not updated inside the loop neither there is any break statement inside the loop so it becomes an infinite loop.
Predict the output of the following code fragments:
for x in [1,2,3,4,5]:
print (x)
Answer
1
2
3
4
5
x will be assigned each of the values from the list one by one and that will get printed.
Predict the output of the following code fragments:
for p in range(1,10):
print (p)
Answer
1
2
3
4
5
6
7
8
9
range(1,10)
will generate a sequence like this [1, 2, 3, 4, 4, 5, 6, 7, 8, 9]. p will be assigned each of the values from this sequence one by one and that will get printed.
Predict the output of the following code fragments:
for z in range(-500, 500, 100):
print (z)
Answer
-500
-400
-300
-200
-100
0
100
200
300
400
range(-500, 500, 100)
generates a sequence of numbers from -500 to 400 with each subsequent number incrementing by 100. Each number of this sequence is assigned to z
one by one and then z
gets printed inside the for loop.
Predict the output of the following code fragments:
x = 10
y = 5
for i in range(x-y * 2):
print (" % ", i)
Answer
This code generates No Output.
The x-y * 2
in range(x-y * 2)
is evaluated as below:
x - y * 2
⇒ 10 - 5 * 2
⇒ 10 - 10 [∵ * has higher precedence than -]
⇒ 0
Thus range(x-y * 2)
is equivalent to range(0)
which returns an empty sequence — [ ].
Predict the output of the following code fragments:
c = 0
for x in range(10):
for y in range(5):
c += 1
print (c)
Answer
50
Outer loop executes 10 times. For each iteration of outer loop, inner loop executes 5 times. Thus, the statement c += 1
is executed 10 * 5 = 50 times. c is incremented by 1 in each execution so final value of c becomes 50.
Predict the output of the following code fragments:
x = [1,2,3]
counter = 0
while counter < len(x):
print(x[counter] * '%')
for y in x:
print(y * '* ')
counter += 1
Answer
%
*
* *
* * *
%%
*
* *
* * *
%%%
*
* *
* * *
In this code, the for loop is nested inside the while loop. Outer while loop runs 3 times and prints % as per the elements in x in each iteration. For each iteration of while loop, the inner for loop executes 3 times printing * as per the elements in x.
Predict the output of the following code fragments:
for x in 'lamp':
print(str.upper(x))
Answer
L
A
M
P
The for loop extracts each letter of the string 'lamp' one by one and place it in variable x. Inside the loop, x is converted to uppercase and printed.
Predict the output of the following code fragments:
x = 'one'
y = 'two'
counter = 0
while counter < len(x):
print(x[counter], y[counter])
counter += 1
Answer
o t
n w
e o
Inside the while loop, each letter of x and y is accessed one by one and printed.
Predict the output of the following code fragments:
x = "apple, pear, peach"
y = x.split(", ")
for z in y :
print(z)
Answer
apple
pear
peach
x.split(", ") breaks up string x into a list of strings so y becomes ['apple', 'pear', 'peach']. The for loop iterates over this list and prints each string one by one.
Predict the output of the following code fragments:
x ='apple, pear, peach, grapefruit'
y = x.split(', ')
for z in y:
if z < 'm':
print(str.lower(z))
else:
print(str.upper(z))
Answer
apple
PEAR
PEACH
grapefruit
x.split(', ') breaks up string x into a list of strings so y becomes ['apple', 'pear', 'peach', 'grapefruit']. The for loop iterates over this list. apple and grapefruit are less than m (since a and g comes before m) so they are converted to lowercase and printed whereas pear and peach are converted to uppercase and printed.
Which of the following is the correct output for the execution of the following Python statement ?
print(5 + 3 ** 2 / 2)
- 32
- 8.0
- 9.5
- 32.0
Answer
9.5
According to operator precedence, exponentiation(**) will come first then division then addition.
5 + 3 ** 2 / 2
= 5 + 9 / 2
= 5 + 4.5
= 9.5
How many times will the following for loop execute and what's the output?
for i in range(-1, 7, -2):
for j in range (3):
print(1, j)
Answer
The loops execute 0 times and the code produces no output. range(-1, 7, -2) returns an empty sequence as there are no numbers that start at -1 and go till 6 decrementing by -2. Due to empty sequence, the loops don't execute.
How many times will the following for loop execute and what's the output?
for i in range(1,3,1):
for j in range(i+1):
print('*')
Answer
Loop executes for 5 times.
*
*
*
*
*
range(1,3,1) returns [1, 2]. For first iteration of outer loop j is in range [0, 1] so inner loop executes twice. For second iteration of outer loop j is in range [0, 1, 2] so inner loop executes 3 times. This makes the total number of loop executions as 2 + 3 = 5.
Find and write the output of the following python code:
for Name in ['Jay', 'Riya', 'Tanu', 'Anil'] :
print (Name)
if Name[0] == 'T' :
break
else :
print ('Finished!')
print ('Got it!')
Answer
Jay
Finished!
Riya
Finished!
Tanu
Got it!
The for loop iterates over each name in the list and prints it. If the name does not begin with the letter T, Finished! is printed after the name. If the name begins with T, break statement is executed that terminates the loop. Outside the loop, Got it! gets printed.
Is the loop in the code below infinite? How do you know (for sure) before you run it?
m = 3
n = 5
while n < 10:
m = n - 1
n = 2 * n - m
print(n, m)
Answer
The loop is not infinite. To know this without running it we can analyze how n is changed inside the loop in the following way:
n = 2 * n - m
Substituting value of m from m = n - 1,
n = 2 * n - (n - 1)
⇒ n = 2 * n - n + 1
⇒ n = 2n - n + 1
⇒ n = n + 1
Therefore, inside the loop n is incremented by 1 in each iteration. Loop condition is n < 10 and initial value of n is 5. So after 5 iterations, n will become 10 and the loop will terminate.
Write a program to print one of the words negative, zero, or positive, according to whether variable x is less than zero, zero, or greater than zero, respectively.
x = int(input("Enter x: "))
if x < 0:
print("negative")
elif x > 0:
print("positive")
else:
print("zero")
Enter x: -5
negative
Enter x: 0
zero
Enter x: 5
positive
Write a program that returns True if the input number is an even number, False otherwise.
x = int(input("Enter a number: "))
if x % 2 == 0:
print("True")
else:
print("False")
Enter a number: 10
True
Enter a number: 5
False
Write a Python program that calculates and prints the number of seconds in a year.
days = 365
hours = 24
mins = 60
secs = 60
secsInYear = days * hours * mins * secs
print("Number of seconds in a year =", secsInYear)
Number of seconds in a year = 31536000
Write a Python program that accepts two integers from the user and prints a message saying if first number is divisible by second number or if it is not.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if a % b == 0:
print(a, "is divisible by", b)
else:
print(a, "is not divisible by", b)
Enter first number: 15
Enter second number: 5
15 is divisible by 5
Enter first number: 13
Enter second number: 7
13 is not divisible by 7
Write a program that asks the user the day number in a year in the range 2 to 365 and asks the first day of the year — Sunday or Monday or Tuesday etc. Then the program should display the day on the day-number that has been input.
dayNames = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"]
dayNum = int(input("Enter day number: "))
firstDay = input("First day of year: ")
if dayNum < 2 or dayNum > 365:
print("Invalid Input")
else:
startDayIdx = dayNames.index(str.upper(firstDay))
currDayIdx = dayNum % 7 + startDayIdx - 1
if currDayIdx >= 7:
currDayIdx = currDayIdx - 7
print("Day on day number", dayNum, ":", dayNames[currDayIdx])
Enter day number: 243
First day of year: FRIDAY
Day on day number 243 : TUESDAY
One foot equals 12 inches. Write a function that accepts a length written in feet as an argument and returns this length written in inches. Write a second function that asks the user for a number of feet and returns this value. Write a third function that accepts a number of inches and displays this to the screen. Use these three functions to write a program that asks the user for a number of feet and tells them the corresponding number of inches.
def feetToInches(lenFeet):
lenInch = lenFeet * 12
return lenInch
def getInput():
len = int(input("Enter length in feet: "))
return len
def displayLength(l):
print("Length in inches =", l)
ipLen = getInput()
inchLen = feetToInches(ipLen)
displayLength(inchLen)
Enter length in feet: 15
Length in inches = 180
Write a program that reads an integer N from the keyboard computes and displays the sum of the numbers from N to (2 * N) if N is nonnegative. If N is a negative number, then it's the sum of the numbers from (2 * N) to N. The starting and ending points are included in the sum.
n = int(input("Enter N: "))
sum = 0
if n < 0:
for i in range(2 * n, n + 1):
sum += i
else:
for i in range(n, 2 * n + 1):
sum += i
print("Sum =", sum)
Enter N: 5
Sum = 45
Enter N: -5
Sum = -45
Write a program that reads a date as an integer in the format MMDDYYYY. The program will call a function that prints print out the date in the format <Month Name> <day>, <year>.
Sample run :
Enter date : 12252019
December 25, 2019
months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
dateStr = input("Enter date in MMDDYYYY format: ")
monthIndex = int(dateStr[:2]) - 1
month = months[monthIndex]
day = dateStr[2:4]
year = dateStr[4:]
newDateStr = month + ' ' + day + ', ' + year
print(newDateStr)
Enter date in MMDDYYYY format: 12252019
December 25, 2019
Write a program that prints a table on two columns — table that helps converting miles into kilometers.
print('Miles | Kilometres')
print(1, "\t", 1.60934)
for i in range(10, 101, 10):
print(i, "\t", i * 1.60934)
Miles | Kilometres
1 1.60934
10 16.0934
20 32.1868
30 48.2802
40 64.3736
50 80.467
60 96.5604
70 112.6538
80 128.7472
90 144.8406
100 160.934
Write another program printing a table with two columns that helps convert pounds in kilograms.
print('Pounds | Kilograms')
print(1, "\t", 0.4535)
for i in range(10, 101, 10):
print(i, "\t", i * 0.4535)
Pounds | Kilograms
1 0.4535
10 4.535
20 9.07
30 13.605
40 18.14
50 22.675
60 27.21
70 31.745
80 36.28
90 40.815
100 45.35
Write a program that reads two times in military format (0900, 1730) and prints the number of hours and minutes between the two times.
A sample run is being given below :
Please enter the first time : 0900
Please enter the second time : 1730
8 hours 30 minutes
ft = input("Please enter the first time : ")
st = input("Please enter the second time : ")
# Converts both times to minutes
fMins = int(ft[:2]) * 60 + int(ft[2:])
sMins = int(st[:2]) * 60 + int(st[2:])
# Subtract the minutes, this will give
# the time duration between the two times
diff = sMins - fMins;
# Convert the difference to hours & mins
hrs = diff // 60
mins = diff % 60
print(hrs, "hours", mins, "minutes")
Please enter the first time : 0900
Please enter the second time : 1730
8 hours 30 minutes
Please enter the first time : 0915
Please enter the second time : 1005
0 hours 50 minutes