<<

Class-XII Computer Science

Python Revision Tour -1

What is python ?

Python is object oriented high level computer language developed by Guido Van Rossum in 1990s . It was named after a British TV show namely ‘Monty Python’s Flying circus’.

Features of Python: Python is very powerful interpreted language (executes the code line by line at a time).

Some advantages of python are:  Easy to use  Expressive language  Cross platform  Free and open sources Python character set:  Letters : A-Z,a-z  Digits : 0-9  Special symbols : space,+,-,*,/,** etc.  Whitespace : blank space, tabs(->),carriage return, newline, formfeed PYTHON TERMINOLOGY : Tokens: A smallest individual unit in a program is known as tokens. Python has following tokens: a) Keywords b) Identifiers c) Literals ) Operators e) Punctuators

Keywords: It is a word having special meaning and must not be used as normal identifier. Ex : if , while ,int etc.

Identifier: They are fundamental building blocks of a program and used to declare variable, objects, class, function etc. Identifier’s forming rules are : 1) First character must be letter. 2) No special character except (_) is allowed. 3) Must not be keyword. 4) Upper and lower case letters are different. Literals: They are data items that have a fixed value. Different types of literals are: 1) Strings 2) Numeric 3) Boolean 4) Special literal- none 5) Literal collection

1) String: String literals are enclosed in quotes(either in single or double) . For ex: ‘a’,’abc’,”x”,”xyz” It also allows to have certain nongraphic characters (those character that cannot be typed directly from keyboard e.g. backspace, tabs, carriage return etc. ) There are two string types: (A) single line (B) multiline Single line string: are created by enclosing text in singe quotes (‘ ’) or double quotes (“ ”) and must terminate in one line. Multiline string: It can be created in two ways: (a) By adding a backslash Ex: text1 = ‘hello\ World’ (b) By adding triple quotation mark Ex: str1 = ‘‘‘hello World. There I come!!! Cheers’’’ (You can use double quotes also)

2) Numeric: It is of three types int, float and complex . Integer: literals are whole numbers without any fractional part. There are three types of integer literals. (a) Decimal integer literals: A sequence of digit unless it begins with 0 is taken to be a decimal integer literal.Ex: 23 ,456 etc. (b) integer literals: A sequence of digit (only from 0-7, 8 & 9 are invalid) staring with 0 is octal integer.Ex :012,0345 (c) integer literals: A sequence of digit (from 0-9 & 10-A, 11-B, 12-C, 13-D,14-E, 15-F) preceded by ox or OX is taken to be a hexadecimal number.Ex: 0xAB,0X1,0XCD3 etc. 3) Floating point literals: They are numbers having fractional part. These may be written in one of the two forms called fractional form and exponent form (a) Fractional form: It consists of signed or unsigned digits including a decimal point between digits for ex: 2.0, -13.0, 0.7 (b) Exponent form: It consists two parts: mantissa and exponent. Ex: 5.8 will be written as 0.58*10 = 0.58E01 Where 0.58 is mantissa and 1 is exponent.

4) Delimiters: It is a sequence of one or more characters used to specify the boundary between separate independent regions in plain text or other data streams. Most common delimiters are () , {} , [] , @ , # , : , = etc.

5) Operators: They are the tokens that trigger some computations when applied to variables. There can be unary or binary. Unary operator requires one operand whereas binary operators require two operand. For ex: +a (unary operator +) a + b (binary operator +) Different types of operator are:  Relational operator (< , > , >= , <= , == , !=)  Logical operator (and , or)  Assignment operator(= , /= , += , *= , -=)  Membership operator( in , not in )

The operations are represented by operators and the objects of the operation are referred to as operands.

Variables and Assignments Variable represent labeled storage locations whose value can be manipulated during program run. Ex: x= 5 Dynamic Typing : x=10 print(x) x = “HELLO” print(x) The output is : 10 HELLO Here variable x is holding integer and later it hold string variable .Dynamic typing is only supported by python. Assignment : In python we can assign same value to multiple variables in a single statement and multiple values to multiple variables in a single statement. Ex : a=b=c=10 x,y,z =10,20,30

DATA TYPE: It identify type of data and set of valid operation for it. They are of different types : (i) Numbers (ii) string (iii) list (iv) tuple (v) dictionary

Numbers are of three types: integers, floating point and complex numbers.

Integers are again of two types: integers (signed) and Boolean (true or false).

String data type can hold any type of known characters i.e. letters, characters and special characters .ex: ”123”.”abss” etc.

List data type a group of comma separated value of any data type between square brackets ex: [1,2,3] , [‘a’,’b’,’c’] etc.

Tuples: It is a group of comma-separated values of any data type within parentheses. ex: p= (1, 2, 3), q= (‘a’, ‘e’, ‘l’)

Dictionaries: it is an unordered set of comma-separated key: value pairs, within {}. EX: {‘a’:1, ‘e’:2, ‘I’:3} Data objects : It can be mutable and immutable types .Mutable data types that can change their value whereas immutable data type can never change their value in place. Ex : list , dictionary ,set(mutable)

Expressions :An expression in python is any valid combination of operators and atoms.

Different types of expressions in python are:

(1)Arithmetic expression: It Involve numbers and arithmetic operators. Ex: 2+3**5

(2)Relational expression: It involve variables and relation operators. Ex: X >Y , y!=z

(3)Logical expression : It involves variables and logical operators .Ex :a or b

(4)String expression : only two operators * and + can be applied on strings. For example : “and” + “then” will print and then “and” + 2 will print andand In a mixed arithmetic expression python converts all operands upto the type of the largest operand which is called type promotion.

Statement Flow Control : It can be of three types.

(1)Simple statement : any single executable statement is called simple statement. For ex: a = 10

(2)Empty statement : A statement which does nothing is empty statement. It takes the following form : Pass

(3)Compound statement: It is a group of statement executed as a unit. The Conditionals and the loops are compound statement. Conditional statement includes if statement ,if-else statement and if-elif statement.

Loop are of two types : while loop and for loop .

Conditional statement : If statement : syntax : if : statement Example : if grade==’A’: print(“well done”) If-else statement : syntax: if :

statement else: statement Example: if grade == ‘A’ : print (“well done”) else: print (”try again”) If-elif statement :syntax: if : statement elif : statement else : statement

Example : num=int(input(“enter the number”)) If num<0: print(“Invalid entry. Valid range is 0 to 999.’’) elif num<10: print(“single digit number is entered”) elif num<100: print(“double digit number is entered”) elif num<=999: print(“three digit number is entered”) else: Print(“invalid entry.valid range is 0 to 999.”) Sample runs of this program are given below; Enter a number (0..999) : -3 Invalid entry. Valid range is 0 to 999. Looping statement:

for loop : syntax: for variable in range statement Example : for value in range (3,18): print(val) Will print the value from the 3 to 17 Example : range(7)- 0,1,2,3,4,5,6

While loop : syntax: while Loop Example: count=1 While(count<=10) Print(count) count=count +1 Will print values from 1 to 10 Jump statement –break and continue : A break statement skips the rest of the loop and jumps over to the statement following the loop. Program to illustrate the difference between break and continue statement.

print( “the loop with break will give output as”) for I in range (1,11): if i%3 == 0: break else: print(i) print(“the loop with continue will give output as “) for I in range(1,11) : if I %3 ==0: continue else: print(i) The output produced by above program as: The loop with break will give output as 1 2 The loop with continue will give output as 1 2 4 5 7 8 10

Program to calculate the factorial of a number. num=int(input(“Enter a number”) fact =1 a= 1 while a<= num : fact *= a a += 1 print(“The Factorial is “,fact)

Nested Loop : A loop may contain another loop in its body. This form of a loop is called nested loop. Example: Program to produce the given code using nested loop * * * * * * * * * * for i in range(1,6): for j in range(1,i): print(“*”,end= ‘ ‘) print()

ASSIGNMENTS (To Be Done In Practice Note Book)

Q1. (a) What are tokens in python? How many types of tokens are allowed in python? (b) How are the keywords different from identifiers? (c) What are data types? How are they important? (d) How many ways are there in python to represent an integer literal? (e) How many strings are supported in python? (f) What will the output of the following code: 1) x,y = 2, 6 x,y = y,x+2 print(x, y) 2) x,y = 7,12 x,y,x = x+1,y+3,x+10 print(x,y) (g) Which of the following is valid arithmetic operator in python: 1) || 2) ? 3) < 4) and (h) Write the types of tokens from the following: 1) sin () 2) randint () (i) Identify the following types of literals? 23.789, true, “true”, OXFACE, False (j) Differentiate between an expression and a statement in python? (k) How can you create a multi-line string in python? (l) Find the output of the following code: 1) x = 10 y = 5 for i in range (x-y*2): print(“%”,i) 2) count =0 while count <10: print(“hello”) count+=1 3) x=10 y=0 while x>y: print(x,y) x=x-1 y=y+1 4) for x in ‘lamp’: print(str.upper(x))

(m) Rewrite the following code after removing the errors. 40=x for y in range(0,x) if y%4 == 0 print(y*4) else: print(y+3)

( c ) Find the output :

1) or name in [‘Jayes’, ‘Ramya’, ‘Taruna’, ‘Suraj’]: print (name) if name [0] == ‘T’: break else: print(‘Finished’) print(‘got it’) 2) for x in range (3): for y in range (4): print(x,y,x+y) 3) for p in range (1,10): print(p) (d ) What are immutable and mutable data type ?