Computer Science Capsule 4 –
Starting With Python, Control Structure ,Library functions
Points to Revise
- Python is an open-source, high level, interpreter-based Programming language
- There are two modes to use the python interpreter:
i. Interactive Mode
ii. Script Mode
- Python Character Set :
It is a set of valid characters that a language recognize, which includes Letters(A-
Z, a-z), Digits (0-9)and Special Symbols.
- Data types of a programming language specify the means to identify the type of
data and the associated operations of manipulating it.
- There are several data types in Python — integer, boolean, float, complex, string,
list, tuple, None and dictionary. Among these String, List and Tuple are Sequence
data type and Dictionary is an Mapping Data type
- TOKENS :
Smallest individual unit in a program is known as token. There are five types of
token in python: Keyword, Identifier, Literal, Operators 5. Punctuators
Keyword are also known as reserved words that has special meaning to the
Python interpreter.
An identifier is the term used to represent program elements such as function
name or class name. The objects used in Python codes are also referred to as
identifiers.
Literals refer to the data items, which do not change their values during a program
execution
Python Operators are special symbols used to perform an action on data items.
Different operators are
- Arithmetical Operators : +, -, *,/, //,% and **
- Relational Operator : >, <, >=, <=, ==, !=
- Logical operator : and, or, not
- Assignment operator : =
- Shorthand assignment Operator : +=, -+, *=, /=, //=, **=, %=
- Identity Operators : is and is not
- Membership Operator : in and not in
Punctuators are used to separate different units of a program. Some examples of
punctuators are ( ) , { }, [ ] , : etc.
- Mutable and Immutable Data type
The Mutable data types are those that can change their value in the same place
i.e in the same memory address. List, dictionary are examples of Mutable data
types.
Objects of Immutable Data types are those whose values cannot be changed in
the same memory location. int, float, string, tuple etc are examples of Immutable
data type
- The Built-in function id() returns the memory address of an object and type()
returns the data type of the object
- Escape Sequence are string literals which are used to represent the non-printable,
non-graphic characters like backspace, tabs, carriage return(enter) etc. \n and \t
are two escape sequences used to represent new line and tab.
- Comments are non-executable statements in a program.
- The process of converting data type of one object into another data type is called
Type conversion. There are two types of Type Conversion
- Implicit type conversion or Automatic conversion.
This type of conversion is performed by Python automatically on its own and
happens when different data types are mixed in an expression
- Explicit type conversion or Type casting
An Explicit type conversion is programmer defined conversion that forces a
data item / object of a specific type to be converted to another data type.
- input() function allows the user to enter a data and store it in the given object
name in the form of a string.
- print() function of Python is used to display the data
- Control Structure refers to the program segment which controls the flow of program
execution.
- In a programming language , there are 3 control structures : Sequence, Selection
and Iteration.
- Python uses here types of statements – simple statement, compound statement
and empty Statement.
- Any single executable statement in Python is a simple statement.
- Python uses indentation for blocks and nested blocks.
- The if statement is used for selection or decision making.
- The looping constructs while and for allow sections of code to be executed
repeatedly under some condition.
- for statement iterates over a range of values or a sequence.
- The statements within the body of for loop are executed till the range of values is
exhausted.
- The statements within the body of a while are executed over and over until the
condition of the while is false.
- If the condition of the while loop is initially false, the body is not executed even
once.
- The statements within the body of the while loop must ensure that the condition
eventually becomes false; otherwise, the loop will become an infinite loop,
leading to a logical error in the program.
- The break statement immediately exits a loop, skipping the rest of the loop’s
body. Execution continues with the statement immediately following the body of
the loop.
- When a continue statement is encountered, the control jumps to the beginning of
the loop for the next iteration.
- A loop contained within another loop is called a nested loop
- Modules make it easier to reuse the same code in more than one program. If we
need a set of functions that is needed in several different programs, we can use
the required module.
- To use these modules in a program, it needs to be imported by using syntax –
import modulename or use from statement to import specific functions from a
module using syntax - from <module_name> import function_name
- The various modules are math,statistical and random. The random module of
Python provides random number generation. A math module of Python is used for
mathematical opeartions and statistical module is for performing statistical
operations.
Assignment
1. What will be the output of the following statement:
print(27 / 3 % 2 * 4**2 )
a. 0 b. 16.0
c. 32 d. 4.0
2. State True or False
A Python objects can be assigned only once in a Python program.
3. What will be the output of the following statement?
print(95 and 34 or not(35 > 95))
a. True b. False c. 34 d. 95
4. Which operator among the following is valid Python operator?
a. ** b. *= c. =/ d. ==
5. Which of the following is an valid assignment statement
a. n1 n2 n3 = 12,34,45
b. n1,n2 ,n3 = 12 34 45
c. n1 = n2 = n3 = 12,34,45
d. n1,n2 ,n3 = 12,34,45
6. What will be the output of the following expression?
not True and False or True
a. True
b. False
c. Null
d. None
7. Which operator among the following cannot be used in a relational expression?
a. > b. = c. != d. <=
8. Which of the following is an invalid identifier name to be used in Python?
a. sub%marks b. _if c. yes d. true
9. Which of the following is valid keyword in Python?
a. int b. none c. True d. false
10. Assertion(A) :
num = int(input("Enter number –"))
The above statement is used to accept an integer from the user and assign it to
the object num.
Reasoning(R) :
The concept of Implicit conversion is used here
a. Both A and R are true and R is the correct explanation for A
b. Both A and R are true and R is not the correct explanation for A
c. A is True but R is False
d. A is false but R is True
11. Write the output of the following if the user enters for num1 is 17
>>> num1 = input(“Enter a number”)
>>> num2 = num1 * 2
>>> print(num2 + num1)
12. What will be the output of the following statements?
a. print(27 / 3 % 2 * 2 ** 2)
b. print(15 + 23 - 2 ** 3 > 10 // 3 +7)
13. Rewrite the corrected code for the following. Also underline the corrections.
side = input(int("Enter a Number"))
side ** 2 = area
area =* 2
print(area =,area)
14. Evaluate the following expressions. Also show the steps of evaluation.
a. >>> a, b, c= 7,3,5
>>> a // b * c ** 2 – b
b. >>> x, y, z =9, 4, 6
>>> x < y or z != x+y and not y > z
15. a. Give the no. of bytes taken by the following string literal:
i. “unit test” ii. “midterm\texam”
16. What is Escape Sequence? Explain the use of two escape sequence with the
help of a suitable example.
17. Give the output of the following code:
b = int (33/4)
c, d= b % 3, b + 5
e, f = 4 + c ** 2, 3 * c
f -= b + c
print (b+c , e+f , sep="*",end ="@@")
print(b + c + e + f / 4)
18. Explain the use of is operator. In which situation n1 is n2 will return True if n1 and
n2 are integer objects n1 and n2. Explain with example.
19. Differentiate between
a. = and ==
b. / and //
c. * and **
d. id() and type()
e. not and !=
20. In Python the data type of the object is same as the data type of the literal
assigned to it. What is this process called? Explain with example.
21. In an object assignment statement, _____or ______ or _______ can be used as
rvalue whereas _______ only can be used as lvalue
22. Name and explain two arithmetic operators which can be used for numeric as
well as string data of Python with suitable example.
23. Explain the use of sep and end in a print statement with example.
24. Answer the questions with reference to the following Python statements.
n1 = int(“enter a number”)) #statement 1
n1,n2 = n1 + 10, n1 - 5
a. Name all identifiers and literals used above with it’s data type
b. Which concept of Python is used in Statement 1
25. What will be the output of the following statements?
a. print(type(input("enter a value"))
b. print(type(print("DPS VK"))
c. num = 120
print(type(id(num)))
c. num, val = 120, True
print(num + val)
26. Name any two sequence data types of Python. Explain the common features of
sequence data type.
27. The data types int, float are examples of Immutable data types of Python. Give
Python statements to prove it.
28. Answer the following
a. The smallest individual unit of a program is _____.
b. An object is an example of _______
c. ______ can be assigned to an object when object of data type is required
to be created in a program.
d. ______ and ____ are examples of keywords which can be also be used
as Literals.
e. ______ and ____ are examples of punctuators
29. Name the data type which can store only two literals and can also be manipulated
as integer data type with suitable example.
30. Explain the use of – as unary and Binary operator with suitable examples.
31. Name the following:
a. Two operator which are right associative in their operation
b. A name used to refer the memory location where a data item is stored.
c. +=, *= are example of which type of operator.
d. The small explanatory description used in a program to explain
statement(s)
32. How many times will the following code be executed.
a=5
while a>0:
print(a)
print(“Bye”)
a) 5 times
b) Once
c) Infinite
d) none of the mentioned
33. What is the output of the following?
a) i=1
while True:
if i%3 == 0:
break
print(i)
i+=1
b) i=1
while False:
if i%2 == 0:
break
print(i)
i += 2
c) x = 'abcd'
for i in 123:
print(i)
d) p=1
for a in range(6):
b=a
while b<=p:
print(b+a,end="*")
b+= 1
print()
p+=1
a+=1
e) p=10
while True:
p= p-1
if p%2!=0:
continue
if p==0:
break
f) s=4
while s<10:
s+=5
if s<=8:
print(s,end=’ ‘)
continue
else:
print(“program ends”)
34. Write an equivalent while statement for the following code. Also write the
number of times the loop will execute.
for k in range(10,0,-1):
print(k,end= ‘ ‘)
if k%10==5:
break
35. Write a program to input x and n and find sum of the following series:
x/3! - 2x2/5! + 3x3/7! -......nxn/(2n+1)!
36. Write a program to input a number n and Write a menu driven program to do
the following:
i Count all odd digits of the number n
ii. Form a number by decrementing each digit by 1.The digit 0
should be replaced with 9.
For example:
If the original number is 520, the new number should be 419
37. Write the Python statement for each of the following tasks using BUILT- IN
functions/methods only:
a. To change the value part of an existing dictionary object
b. To display the number of times a data item as parameter appears in the
list.
c. The method used to add a new element to an existing dictionary
d. The method which searches a given value in a tuple and returns the index
of the first occurrence of a search value.
e. The method used to return a list containing all words present in a string
f. The method which delete an element in a list, if it’s value is given as
argument.
38. Name the Python Library modules which need to be imported to invoke the
functions : (i) tan() (ii) randrange()
39. What possible outputs(s) will be obtained for the following code is executed?
import random
num = random.randint (1,3)
posn = [“FIRST, “SECOND”, “THIRD”, “FOURTH”]
for I in posn:
for J in range(0, num):
print (I, end = “%”)
print ()
a. FIRST%
SECOND%
THIRD%
b. FIRST%
SECOND%SECOND%
THIRD%THIRD%THIRD%
c. FIRST%FIRST%
SECOND%SECOND%
THIRD%THIRD%
FOURTH%FOURTH%
d. FIRST%
SECOND%SECOND%
THIRD%THIRD%THIRD%
FOURTH%FOURTH%FOURTH%FOURTH%
40. What possible output(s) is/are expected to be displayed on the screen at the time
of execution of the program from the following code? Also specify the maximum
and minimum value that can be assigned to the variable R when K is assigned
value as 2.
import random
Signal = [ 'Stop', 'Wait', 'Go' ]
for K in range(2, 0, -1):
R = randrange(K)
print (Signal[R], end = ' # ')
a. Stop # Wait # Go #
b. Wait # Stop #
c. Go # Wait #
d. Go # Stop #