Review of Python Class XII- Worksheet 1

Python Revision Tour -Notes

1. Define the term Token, Keyword and Identifiers with suitable example.

Token : Smallest individual unit that is used to create a program is called token or lexical unit. Python has following tokens:

(i) Keywords        (ii) Identifiers          (iii) Literals        (iv) Operaters        (v) Puncatuators

Keyword: Keyword is a reserve word having special meaning in the programming language. For example True, False, for, if, elif, while, def, in , break, continue are some keywords used in Python Language.

Identifiers: Identifers are non-keyword words that are used as name for variable, functions, modules etc. Python is a case sensetive and treat upper case and lower case characters differently. Ex. Mynum, num20, x, y, my_file etc.

2. What are the common rules to define Python identifiers (Names)?

Naming rule for Python identifiers are:

  • Variable name must starts with alphabet or _ (underscore).
  • Cannot use any special character in variable name except underscore (_)
  • There should not be any space in variable name.
  • Keywords cannot be used as variable name

3. Define the term Literals with suitable example.

Literals are data items that have a fixed or constant value. Literals are of following type:

  • String Literals : Python has single line strings and multiline strings. String value in enclosed in single quote ('       ') or double quote ("      ") and triple quote ('''      ''') or ("""       """) For example:
    city = "Pilibhit"
    sentence = "This is a sentence."
    paragraph = """This is a paragraph. It is
    made up of multiple lines and sentences."""
  • Numeric Literals : Numeric literrals are numberic values and these can be Integer literals , Floating Point lterals, Complex literals and specail literal None

4. Name basic datatype used in Python?

Python has five standard data types- Numbers (int, float, complex), String , List, Tuple, Dictionary

5. How will Python evaluate expression 20 + 30 * 40?

= 20 + (30 * 40)     # Step 1 precedence of * is more than that of +
= 20 + 1200          #Step 2
= 1220                  #Step 3

6. What will be output of the expression (5<10) and (10<5) or (3<18) and not 8<18

(5<10) and (10<5) or (3<18) and not 8<18
True and False or True and not True
False or True and False
False and False
False

7. Define the term statement in context of Python with suitable example?

In Python, a statement is a unit of code that the Python interpreter can execute.
Example:
>>> x = 4                    #assignment statement
>>> cube = x ** 3      #assignment statement
>>> print (x, cube)     #print statement

8. What is type conversion?

Converting one data type into another is called type conversion. Python offers Implicit Type conversion and Expilicit Type conversion.
Implicit Type conversion : When python compiler perform the data conversion automatically and not instructed by programmer. For example
n1, n2 = 10, 20.0
sm=n1+n2
print(sm)       # the value of sm will be 30.0 which is a float, while n1 is int type and n2 is float type.

Explicit Type conversion: When a data type is converted into another data type forcefully by a programmer. It's syntex is
(new_data_type) expression

For example :

>>>a=10
>>> b=20
>>> c=str(a)+str(b)
>>> print(c)     # here value of c will be 1020 as a and b are integer but str(a) converts int to string.

9. What is debugging? What are different types of error?

Mistakes and errors in a program code is called bug. The process of Identifying and removing errors from the program is called debugging. Different types of errors are :

  • Syntax Errors
  • Logical Errors
  • Runtime Errors

* Syntax Error : Python has its own rules that determine its syntax. The interpreter interprets the statements only if it is syntactically correct. If any syntax error is present, the interpreter shows error message(s) and stops the execution there.

* Logical Error : A bug in a program that occurs due to faulty logic is called logical error. Interpreter does not identify logical error but it executes the program and logical error gives wrong output. Logical errors are also called semantic errors as they occur when the meaning of the program (its semantics) is not correct.

* Runtime Error : A runtime error causes abnormal termination of program while it is executing. Runtime error is when the statement is correct syntactically, but the interpreter cannot execute it. For example Divide by zero errror.

10. Write a program to swap two numbers using a third variable.

a=int(input('Enter value for object a '))
b=int(input('Enter value for object b '))
print('a=',a,' b=',b)
a,b=b,a      #swapping
print('after swapping now a=',a, ' b=',b)

Output

Enter value for object a 20
Enter value for object b 30
a= 20 b= 30
after swapping now a= 30 b= 20

11. Write a program to find average of three numbers.

x=int(input('Enter first number '))
y=int(input('Enter first number '))
z=int(input('Enter first number '))
avg=(x+y+z)/3
print(' Average = ' avg)

12. Define List, Tuple and Dictionary with suitable example for each.


List: List is a sequence of values enclosed in square brackets [ ]. Values of list are called list items or elements. List items are indexed /ordered and mutable.
For Example:-
subject = ['physics', 'chemistry', 1997, 2000];
lst2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];

Tuple: A tuple is a sequence of immutable Python objects enclosed in ( ) parentheses. For example:
tup = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"

Dictionary: An unordered sequence of key:value pair is called dictionary. Dictionary item consists key:value pair, where key and value separated by colon : symbol. Dictionary items are enclosed in { } curly braces. Dictionary keys are immutable but the value is mutable. For example
rec = {'Name': 'Anil',   'Age': 17,    'Class' : 12'}


13. Create empty list, tuple and dictionary.

Creating empty list:
(i)         lst =list()
(ii)        mylst = [   ]

Creating empty Tuple:
(i)         Tp =tuple()
(ii)        Tpl = ( , )

Creating empty dictionary:
(i)         Dct =dict()
(ii)        mydict = {   }

14. Write a program to print negative, zero or positive if the input value for a variable is less than zero, zero, or greater than zero respectively.

x=int(input('Enter any integer '))
if x<0:
        print('Input number is negative')
elif x==0:
        print('Input number is zero ')
else:
        print('Input number is positive')

15. What is the role of comment and indentation in a program?

In Python we can give comment by # symbol. Comments provide explanatory notes to the readers of the program. Compiler or Interpreter ignores the comments and do not execute them. They are like user manual and used for documentation purpose in a program.

Indentation makes the program more readable. In python indentation is used to create a block of code. Indentation alos helps in nesting of groups of control statements.

16. Convert following for loop into while loop?

n=int(input('Input any number '))
for x in range(1,11):
      pro = n * x
      print(pro)

Answer : Converted code by using while loop in place of for
x=int(input('Input any number '))
x=1
while(x<11):
      pro = x * n
      print(pro)
      x=x+1

17. What is the error in following code. Don't remove any line or add any code.

x=int(input('Input any number '))
x=1
while(x<11):
      pro = x * n
      print(pro)
 x=x+1

Answer :
Above code has logical error in line number 6 i.e. x=x+1 should be the part of while loop. Here it is outside the loop and thus the while loop became infinite loop as the value of x will not getting any increment to reach to final value. The correct code should be:


x=int(input('Input any number '))
x=1
while(x<11):
      pro = x * n
      print(pro)
      x=x+1

18. How many time the following loop will execute and what will be the output?

for i in range(-1,-7,-2):
        for j in range(3):
                 print(i,j)

Answer : There are two for loops. Outer one is for i and inner one is for j. Value generated for i are -1,-3 and -5 as i terminates at -6. Inner loop j will generate 0,1,2 for each i. Thus Inner loop j executes 9 times while outer loop i executes 3 times. The output will be

-1 0
-1 1
-1 2
-3 0
-3 1
-3 2
-5 0
-5 1
-5 2


19. Write a program to input any positive number and print the sum of the digits of that number.

x=int(input('Enter any positive number '))
if x>0:
        dsum=0
        while x!=0:
                rem=x%10
                dsum=dsum+rem
                x=x//10
         print('Sum of digit is ',dsum)
else:
         print('Enter any positive integer ')

20. Write a program that repeatedly asks numbers from a user and print the sum of numbers input by user. It terminate the program when user input 0.

mysum=0
n=1
while n!=0:
      n=int(input('Enter any number '))
      mysum=mysum+n
      print('Sum of numbers =',mysum)