<<

Class-XI

Computer Science

Python Fundamentals

Notes 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’. Python is a , as are , Fortran, BASIC, PHP, etc. Some specific features of Python are as follows:

• an interpreted (as opposed to compiled) language. Contrary to e.g. C or Fortran, one does not compile Python code before executing it. In addition, Python can be used interactively: many Python interpreters are available, from which commands and scripts can be executed. • a free software released under an open-source license: Python can be used and distributed free of charge, even for building commercial software. • multi-platform: Python is available for all major operating systems, Windows, Linux/, MacOS X, most likely your mobile phone OS, etc. • a very readable language with clear non-verbose syntax • a language for which a large variety of high-quality packages are available for various applications, from web frameworks to scientific computing. • a language very easy to interface with other languages, in particular C and C++. • Some other features of the language are illustrated just below. For example, Python is an object-oriented language, with dynamic typing (the same variable can contain objects of different types during the course of a program).

Python character : • Letters : A-Z , a-z • Digits : 0-9 • Special symbols : space,+,-,*,/,** etc. • Whitespace : blank space, tabs(->),carriage return, newline, formfeed • Other characters :python can process all ASCII and unicode characters as part of data PYTHON TERMINOLOGY : Tokens: A smallest individual unit in a program is known as tokens. For Example: He said, “Hurry up!”. Here in this English sentence two types of tokens are used : word and punctuators. In Program individual units or tokens together make components of a program. For Example :

# A sample program name = “Ram” age = 18 marks = 99.5 print(“NAME : ”, name, “AGE :”, age, “MARKS :” ,marks)

Here many tokens are present such as keyword, identifier and literals.

Keyword : print( ) String literal : “Ram” Integer literal : 18 Floating point literal :99.5 Punctuator : “ ”, : , Identifier : name , age , marks

Python has following tokens: a) Keywords ) 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) An identifier is an arbitrarily long sequence of letters and digits. 2) First character must be letter. 3) No special character except (_) is allowed. 4) Must not be keyword. 5) Upper and lower case letters are different. 6)Identifiers are unlimited in length. 7)The digits 0 to 9 can be the part of the identifier except the first character. Some valid identifiers are : Myfile, chk chk12, first_name file2 Some invalid identifiers are: Data-rec 29digits break my.file first$name

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. Name= “ram” Name1= ‘sita’ Grade = ‘a’ Multiline string: It can be created in two ways: (i) By adding a backslash Ex: text1 = ‘hello\ World’ (ii) By adding triple quotation mark Ex: str1 = ‘‘‘hello World. There I come!!! Cheers’’’ (You can use double quotes also) Size Of String

Python determines the size of the string as the count of characters in the string.Consider some of the example given below: “abc” size is 3

“\ab” size is 2( \a is an escape sequence, thus one character )

‘\\’ size is 1(\\ is an escape sequence to represent backslash)

“Seema\’s pen” size is 11(count the characters including blank character)

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) Octal integer literals: A sequence of digit (only from 0-7, 8 & 9 are invalid) staring with 0 is octal integer. Ex :012,0345 (c) Hexadecimal 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.

Floating point literals: They are also called real 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. The rule for writing a real literal in fractional form is: A real constant in fractional form must have at least one digit with the decimal point, either before or after, It may also have either + or - sign preceding it. A real constant with no sign is assumed to be positive.

(b) Exponent form: A real constant in Exponent format 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. Some invalid real literals in exponent form: 1.7 (no digit specified for exponent) 0.17E2.3 (Exponent cannot have fractional part) The rule for writing a real literal in exponent form is : A real constant in exponent form has two parts: a mantissa and an exponent . The mantissa must be either an integer or a proper real constant. The mantissa is followed by a letter E or e and an exponent. The exponent must be an integer.

Complex numeric literal : a +b J or a+ b j a is real part and b J is imaginary part. 3) Boolean literal : True and False are the only two Boolean literal values in Python. 4)special literal None : It indicates absence of value . Value1 =10 Value2 = None print(value1) print(value2) 10 None 5) Literal Collections : List , Tuple, Dictionary and sets are called literal collection . 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.

Operators: They are the tokens that trigger some computations when applied to variables. There can be unary or binary. Unary operator requires one whereas binary operators require two operand. For ex: +a (unary operator +) a + b (binary operator +)

Unary Operators : Unary operators are those operators that require one operand to operate upon. Following are some unary operators:

+ Unary plus

- Unary minus

~ Bitwise complement

not logical negation

Different types of Binary operator are: ➢ Relational operator (< , > , >= , <= , == , !=) ➢ Logical operator (and , or ) ➢ Assignment operator(/= , += , *= , -=) ➢ Membership operator( in , not in ) ➢ Arithmetic operators(+,-,*,/,//,%) ➢ Identity operators (is, is not)

The operations are represented by operators and the objects of the operation are referred to as . An operator is used to perform specific mathematical or logical operation on values. The values that the operators work on are called operands. For example, in the expression 10 + num, the value 10, and the variable num are operands and the + (plus) sign is an operator. Python supports several kinds of operators whose categorization is briefly explained in this section. Python compares strings lexicographically, using ASCII value of the characters. If the first character of both the strings are same, the second character is compared, and so on.

ARITHEMETIC OPERATOR:

Python supports arithmetic operators that are used to perform the four arithmetic operations as well as modular division, floor division and exponentiation.

+ Addition adds the two numeric values on either side of the operator. This operator can also be used to concatenate two strings on either side of the operator >>> num1 = 5 >>> num2 = 6 >>> num1 + num2 11 >>> str1 = "Hello" >>> str2 = "India" >>> str1 + str2 'HelloIndia'

- Subtraction Subtracts the operand on the right from the operand on the left >>> num1 = 5 >>> num2 = 6 >>> num1 - num2 -1

* Multiplication Multiplies the two values on both side of the operator >>> num1 = 5 >>> num2 = 6 >>> num1 * num2 30 It Repeats the item on left of the operator if first operand is a string and second operand is an integer value. >>> str1 = 'India' >>> str1 * 2 'IndiaIndia'

/ Division Divides the operand on the left by the operand on the right and returns the quotient. >>> num1 = 8 >>> num2 = 4 >>> num2 / num1 0.5

% Modulus Divides the operand on the left by the operand on the right and returns the remainder. >>> num1 = 13 >>> num2 = 5 >>> num1 % num2 3

// Floor Division Divides the operand on the left by the operand on the right and returns the quotient by removing the decimal part. It is sometimes also called integer division. >>> num1 = 13 >>> num2 = 4 >>> num1 // num2 3 >>> num2 // num1 0

** Exponent Performs exponential (power) calculation on operands. That is, raise the operand on the left to the power of the operand on the right >>> num1 = 3 >>> num2 = 4 >>> num1 ** num2 81

RELATIONAL OPERATOR:

Relational operator compares the values of the operands on its either side and determines the relationship among them. num1=30 , num2=20 , num3= 30, str1= “sita” , str2= “am”

== Equals to if the values of two operands are equal, then the condition is True, otherwise it is False.If num1=10 and num2=20 also str1= “ram” and str2= “sita” >>> num1 == num2 False >> str1 == str2 False

!= Not equal to If values of two operands are not equal, then condition is True, otherwise it is False >>> num1 != num2 True >>> str1 != str2 True >>> num1 != num3 False

> Greater than If the value of the left-side operand is greater than the value of the rightside operand, then condition is True, otherwise it is False >>> num1 > num2 True >>> str1 > str2 True

< Less than If the value of the left-side operand is less than the value of the rightside operand, then condition is True, otherwise it is False >>> num1 < num3 False >>> str2 < str1 True

>= Greater than or equal to If the value of the left-side operand is greater than or equal to the value of the right-side operand, then condition is True, otherwise it is False >>> num1 >= num2 True >>> num2 >= num3 False >>> str1 >= str2 True

<= Less than or equal to If the value of the left operand is less than or equal to the value of the right operand, then is True otherwise it is False >>> num1 <= num2 False >>> num2 <= num3 True >>> str1 <= str2 False

ARITHEMETIC ASSIGNMENT OPERATOR :

Assignment operator assigns or changes the value of the variable on its left.

= Assigns value from right-side operand to leftside operand >>> num1 = 2 >>> num2 = num1 >>> num2 2 >>> country = 'India' >>> country 'India'

+= It adds the value of right-side operand to the left-side operand and assigns the result to the left-side operand x += y is same as x = x + y >>> num1 = 10 >>> num2 = 2 >>> num1 += num2 >>> num1 12 >>> num2 2 >>> str1 = 'Hello' >>> str2 = 'India' >>> str1 += str2 >>> str1 'HelloIndia'

-= It subtracts the value of right-side operand from the left-side operand and assigns the result to left-side operand x -= y is same as x = x - y >>> num1 = 10 >>> num2 = 2 >>> num1 -= num2 >>> num1 8

*= It multiplies the value of right-side operand with the value of left-side operand and assigns the result to left-side operand x *= y is same as x = x * y >>> num1 = 2 >>> num2 = 3 >>> num1 *= 3 >>> num1 6 >>> a = 'India' >>> a *= 3 >>> a 'IndiaIndiaIndia'

/= It divides the value of left-side operand by the value of right-side operand and assigns the result to left-side operand x /= y is same as x = x / y >>> num1 = 6 >>> num2 = 3 >>> num1 /= num2 >>> num1 2.0

%= It performs modulus operation using two operands and assigns the result to left-side operand x %= y is same as x = x % y >>> num1 = 7 >>> num2 = 3 >>> num1 %= num2 >>> num1 1

//= It performs floor division using two operands and assigns the result to left-side operand x //= y is same as x = x // y >>> num1 = 7 >>> num2 = 3 >>> num1 //= num2 >>> num1 2

**= It performs exponential (power) calculation on operators and assigns value to the left-side operand x **= y is same as x = x ** y >>> num1 = 2 >>> num2 = 3 >>> num1 **= num2 >>> num1 8

IDENTITY OPERATOR:

Identity operators are used to determine whether the value of two a variable is of a certain type or not. Identity operators can also be used to determine whether two variables on either side of the operator point towards the same memory location or not. var1 is var2 results to True if id(var1) is equal to id(var2) >>> num1 = 5 >>> type(num1) is int True >>> num2 = num1 >>> id(num1) 1433920576 >>> id(num2) 1433920576 >>> num1 is num2 True

LOGICAL OPERATOR:

There are three logical operators supported by Python. These operators (and, or, not) are to be written in lower case only. The logical operator evaluates to either True or False based on the logical operands on either side. Every value is logically either True or False. By default, all values are True except None, False, 0 (zero), empty collections "", (), [], {}, and few other special values. So if we say num1 = 10, num2 = -20, then both num1 and num2 are logically True. and Logical AND If both the operands are True, then condition becomes True >>> True and True True >>> num1 = 10 >>> num2 = -20 >>> bool(num1 and num2) True >>> True and False False >>> num3 = 0 >>> bool(num1 and num3) False >>> False and False False or Logical OR If any of the two operands are True, then condition becomes True >>> True or True True >>> True or False True >>> bool(num1 or num3) True >>> False or False False not Logical NOT Used to reverse the logical state of its operand >>> num1 = 10 >>> bool(num1) True >>> not num1 >>> bool(num1) False

MEMBERSHIP OPERATOR:

Membership operators are used to check if a value is a member of the given sequence or not.

It returns True if the variable/value is found in the specified sequence and False otherwise. >>> a = [1,2,3] >>> 2 in a True >>> '1' in a False not in returns True if the variable/value is not found in the specified sequence and False otherwise >>> a = [1,2,3] >>> 10 not in a True >>> 1 not in a False >>>“jap” not in “japan” False >>>“Jap” in “japan” False >>>“jap” in “japan” true >>>‘e’ in “japan” False

MEMORY MAP

Order of Precedence Of Operators Description

1 ** Exponentiation (raised to the power) 2 ~ ,+, - Complement, unary plus and unary minus 3 * ,/, %, // Multiply, divide, modulus and floor division 4 +, - Addition and subtraction 5 <= ,< ,> ,>= Relational operators 6 == ,!= operators 7 =, %=, /=, //=, -=, +=,*=, **= Assignment operators 8 is, is not Identity operators 9 in, not in Membership operators 10 not, or, and Logical operators

Writing your First Python Program

There are two ways in which you can write and execute a basic Python program:

1. In Interactive mode - where you write a program and execute it

Using Script mode - where you execute and already saved Python program(.py file)

BAREBONE OF A PYTHON PROGRAM #This program shows a program’s components------comments a=15 ------statement b= a-10 ------expressions print(a+3) ------statement if b>5 : ------expressions print(“value of a was more than 15 intially. ”)------indentation else: print(“value of a was 15 0r less initially.”)------indentation

This sample program contains components like: (i) expressions (ii) statements (iii) comments (iv) function (v) blocks and indentation

Expressions : An expression is any legal combination of symbols that represents a value. An expression represents something. A+5 (3+5) /4

Statements : A statement is a programming instruction that does something i.e. some action takes place. a=15 b=a-10 print(b)

Comments : Comments are additional readable information, which is read by the programmers but ignored by python interpreter. In python, comments begin with the symbol # and end with the end of physical line. It can be done in two ways. (i) By adding # sign #This program shows a program’s components #Definition of function follows #Main program code follow now (ii) Type comment as a triple-quoted multi line ‘’’multi line comments are used for detailed additional Information related to the program in Question. ‘’’ Function :A function is a code that has a name and it can be reused by specifying its name in the program, where needed. Block and Indentation : Sometimes a group of statements is part of another statement of function. Such a group is called block or code block. For example : if b<5 print(“less than five ”) print(“thank you”) Python uses indentation to create blocks of code. Statements at same indentation level are part of same block.

Variables and Assignments Variable represent labeled storage locations whose value can be manipulated during program run. Ex: x= 5 IMPORTANT NOTE

PYTHON CALLS EVERY ENTITY THAT STORES ANY VALUE AS AN OBJECT.

Python calls every entities that stores any value or any type of data as an object. A=10 An object is an entity that has certain properties and shows a certain type of behavior. for Example integer values are objects –they hold whole number only and have many properties like that support all arithmetic operations. Every python object has three key attributes associated with it: (i)The type of an object : The type of an object determines the operation that can be performed on the object. Built in function type( ) returns the type of an object: For ex: >>> a= 4 >>>type(a) >>>type(4) (ii)The value of an object : It is the data item contained in the object. Using print() statement you can display the value of an object. >>>a=4 >>>print(4) 4 >>>print(a) 4 (iii)The id of an object : the id of the object is generally the memory location of the object. Built-in function id( ) returns the id of an object. >>>id(4) 30854612 >>>a=4 >>>id(a) 30854612 IMPORTANT NOTE: The id of a variable is same as the id() of value it is storing. For ex: >>>id(4) 30854612 >>>a=4 >>>id(a) 30854612 >>>b= 5 >>>id(5) 30899120 >>>id(b) 30899120 >>>b= b-1 >>>id(b) 30854612 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

SIMPLE INPUT AND OUTPUT :

Reading Data from the user In Python to get a value from user we use input() function. The function input() is used in following manner. Name= input(“Enter Your Name ”) The value which you enter will be assigned to variable name. Now consider the following command sequence. >>>name= input(“Enter your name :”) Enter your name : Ram >>>Age = input(“Enter you Age:”) Enter your Age : 16 Name ‘simar’ Age ‘16’ IMPORTANT NOTE The input( ) function returns a value of string type. So it is displaying both he values in single quotes. To convert a string value into integer int () function is used.

Output Through print( ) statement The output() function of python is a way to send output to standard output device, Which is normally a monitor. For example: print(“hello”) # a string print(17.5) #a number print(“ram”, 12+5 , “years”) #multiple comma separated expressions

Programs in Python Q1. Write a program to obtain three numbers and print their sum.

#To input three numbers and print their sum Num1=int(input(“Enter first number”) ) Num2=int(input(“Enter second number”)) Num3=int(input(“Enter third number”)) Sum=Num1+Num2+Num3 print(“The three numbers are : ” , Num1, Num2, Num3) print (“The sum is : ” , Sum)

Q2.Write a program to obtain radius of circle and find the area

#To calculate area of a circle Radius=float(input(“Enter the radius : ”) ) Area = 3.14 * Radius * Radius print(“The area of circle is : ” , Area )

Q3.Write a program to input name, age and marks in one subject of a student

#Program to enter and display information of a student Name=input(“Enter your name : ”) Age=int(input(“Enter your age : ” ) ) Marks=float(input(“Enter your marks : ”)) print(“The name you entered is : ” , Name) print(“The age is : ”, Age ) print(“The marks is: ” , Marks )

Q4.Write a program to read length and breadth of a rectangle and calculate its area. #Program to calculate area of a rectangle Length = float(input(“Enter length of a rectangle: ”) ) Breadth= float(intput (“enter the breadth of rectangle : ” ) ) Area = Length * Breadth print(“the area of rectangle : ” , Area)