Skip to main content

Revision basics of Python covered in Class XI


Python is

va general purpose  and Object Oriented programming language
valso called as Interpreted language
vInvented in the Netherlands, in February 1991
vdeveloped by Guido van Rossum 
vIt was named after famous BBS comedy show namely “Monty Python’s Flying Circus”

Features(advantages):

1.Object-oriented : support features like class, object ,data abstraction, inheritance, polymorphism etc.
2.Interpreted language: Python use interpreter as translator program
3.User friendly(easy to use and learn): simple syntax rules easy to use and learn. It is very  high language
4.Cross platform(portable): it can run on variety of platforms like windows, Linux/Unix, Macintosh
5.Free and open source: Downloading and installing Python is free and You can modify, improve its Source code .
6.Indentation: Is one of the greatest future in Python. It is used to identify a block in Python
7.Completeness: Python follows “batteries included” philosophy. All types of required functionality is available through python standard library.
8.Variety of Usage:  These days python is being used  in many fields/applications such as scripting, web application, GUI programs, database applications etc.

Limitations

1.Slow in Speed:Python code is executed line by line. But since Python is interpreted, it often results in slow execution.
2.Lesser libraries than C, Java, Perl: Its library is still not competent with languages like C,java, Perl
3.Lack of mobile computing and browsers: It is seen as a weak language for mobile computing. 
4.Not easily convertible: Syntax rules of python is very easy but most other language have strong syntax therefore it is very difficult to translate python program into another language program. It produce large number of runtime errors
5.Not Strong on Type binding: Python interpreter is not very strong on catching Type  mismatch issues.
6.Underdeveloped Database Access Layers:

As compared to the popular technologies like JDBC and ODBC, the Python’s database access layer is found to be bit underdeveloped and primitive. 


Working in Python: You can work in python using two modes.

1.Interactive mode(immediate mode): commands are given in front of Python prompt( >>>) one at a time. Then python executes the given command and give you output. For example

>>>2+5

7

Steps:

 click on start button

Click on all programs

Click on python3.7

Then click on python3.7 it will display command prompt(python shell) as

>>>

Type your command and press enter

>>>2+5

7

We cannot save the commands in Interactive mode.

  1.Script mode(Python IDLE): Python instructions or commands can be store in a file  or script with .py extension and the file can be  executed in one go as a unit. This saved file is called python script or python program.

Steps:

(A) Create program file

1.Click start button -> all programs->Python3.7-> IDLE
2.Click File->New in IDLE
3.It will open a new window. Type the commands you want to save in the form of a program or script. For example the simple hello world program, you will need to type following line

  print(“Hello World”)

4. File->Save and save file with a name hello.py and click on save button

(B) Run  program file: 

1.One the desired file using File->Open
2.Click Run->Run module command or press f5 key
3.It will executes all commands stored in module/program/script that you have opened.
4.It will display the complete output in a separate Python shell window.

       Hello World



Character set
A set of valid characters recognized by python. Latest Python version support both traditionalASCII character  and Unicode character set.
The ASCII character set is a subset of the Unicode character set
1. Lowercase/Uppercase letters:
a- z and A-Z
2. Digits: 0-9
3.  punctuation and symbols:
 >,<, " ", ' ',{ },[ ], ( ),*,+,-,/ ,#,*=, =, ==  etc
4. White space characters:
An actual space (" "), as well as a newline(\n), carriage return, horizontal tab(\t), vertical tab(\v),backspace "\b" etc
5. Others: ASCII code and UNICODE characters

TOKEN
Smallest individual unit of a program is known as token or lexical unit. 
1. Keywords 2. Identifiers 3. Literals 4. Operators 5. punctuators 

Keywords:
Keywords Reserve word of the compiler/interpreter which can’t be used as identifier.

python_keyword



Identifiers
Name given to any part of program is called identifier. 
A Python identifier is a name used to identify a variable,function, class, module or other object.
Rules to define Identifiers:

 An identifier must  starts with a letter( A to Z or a to z )or an underscore (_) 

 Python does not allow special characters

Identifier must not be a keyword of Python.
Python is a case sensitive programming language.
Thus, a and A  are two different identifiers
in Python.
Some valid identifiers :
 Myname, a_123, a2cd, date_2, _no
Some invalid identifier :
 2rno,break,my.book,data-cs

Literals(Constants-Values):

vData items or Values are called Literals
vPython allow five types of literals 
1. string 2. numeric 3.Boolean  4.special literal None 5.collection literals like tuples, list , set etc.

1. String literals:
vSet of one or more characters enclosed in single or double quotes or Triple Quotes.
vFor e.g. “asdf” , “1-2-3-3@” , ‘123’ , ‘ammy’s
vPython allows you two string types: single line and multiline

vSingle line: Enclosed in single or double quotes. They must terminate in one line.  For example s=“hello”
vMultiline :text spread across multiple line. We can create using two ways
(a)By adding a backslash at the end of every line before pressing enter to continue typing text on next line for example

S=‘hello\

     how are\

     you’

>>>S

Hello how are you

(b) By typing text in triple quotation marks(‘’’  ‘’’)

      for example

>>>s=‘’’ hello

                                  how are

                  you’’’

>>>print(s)

   hello

                                  how are

                  you 

Escape Characters

An escape character is a backslash \ followed by the character you want to insert.



#This example erases one character (backspace):

txt = "Hello  \bWorld!"

print(txt) 

  Output :HelloWorld

#A backslash followed by three integers will result in a octal value:

txt = "\110\145\154\154\157"

print(txt) 

      Output: Hello
    

2.Numeric literals:

(a) integers (b) float

Integers: numbers without fractional(decimal point) part. May contain +or – sign.

Float(real):numbers with fractional parts. May contain +or – sign. Must contain decimal point(.)

vIntegers: Three types
(a)Decimal: sequence of digits(0-9) . E.g. 34,234,+45,-456 etc.
(b)Octal: sequence of digits 0 to 7.Must starting with 0O(zero and letter O) e.g. 0O765, 0O14 etc
(c)Hexadecimal: Sequence of digits(0-9) or letters A to F but must  preceded with 0x or 0X.

For example 0x12FCD, 0X4A5EF, 0xD etc.

Long Integers:

Integers of unlimited size followed by lowercase or uppercase L eg: 87032845L

Complex numbers:

In the form of a+bj where a forms the real part and b forms the imaginary part of the complex number. eg: 3.14j



 

Float literals: they may written in two forms

(a)Fractional form:  e.g 2.0 , 17.5 , +3.5, -4.5 ,-0.0034 etc.
(b)Exponent form: consist of two parts: mantissa and exponent

                         mantissa E exponent

For example 5.8 can be written as

0.58 * 101=0.58E01 where mantissa is 0.58 and 01 is exponent

NOTE* numeric values with commas are not considered int or float value , rather Python treats them as a tuple. A tuple is a special type in Python that stores a sequences of values  



3. None Literal: It is used to indicate absence of value.

>>>a=None 

>>>a

>>>print(a)


4. Boolean literals : True and False are two Boolean literal in Python.Logical operators always results in True or False

>>>a=10

>>>b=25

>>>a>b

False


5.Literal Collections

Python provides the four types of literal collections

List, tuple,Set, Dictionary


List: 

List contains items of different data types. Lists are mutable i.e., modifiable.The values stored in List are separated by comma(,) and enclosed within square brackets([]). We can store different types of data in a List.

list=[1,2,3,4]

Tuple:

 Python tuple is a collection of different data-type. It is immutable which means it cannot be modified after creation.It is enclosed by the parentheses () and each element is separated by the comma(,)

list=(1,2,3,4)

Set:

Python set is the collection of the unordered dataset.It is enclosed by the {} and each element is separated by the comma(,).

set = {'apple','grapes','guava','papaya'}  

print(set)  

Dictionary:

Python dictionary stores the data in the key-value pair.

It is enclosed by curly-braces {} and each pair is separated by the commas(,).

dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}  

print(dict)  


Operators: 


Operators can be defined as symbols that are used to perform

 arithmetic and logical operations on data  or variable called operands.

Types of Operators

1. Arithmetic Operators.

2. Relational(comparison) Operators.

3. Assignment Operators.

4. Logical Operators.

5. Bitwise Operators

6. Membership Operators

7. Identity Operators



Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc.



+,-,*,


**   (Exponentiation)  Exponent - left operand raised to the power of right    ,    

 (division )Divide left operand by the right one (always results into float)     ,

 //   ( Floor division  )Modulus - remainder of the division of left operand by the right   ,

 %       (Modulus)

x = 15

y = 4


# Output: x + y = 19

print('x + y =',x+y)


# Output: x - y = 11

print('x - y =',x-y)


# Output: x * y = 60

print('x * y =',x*y)


# Output: x / y = 3.75

print('x / y =',x/y)


# Output: x // y = 3

print('x // y =',x//y)


# Output: x ** y = 50625

print('x ** y =',x**y)


Relational Operators

Comparison operators are used to compare values. It returns either True or False according to the condition.

These are >,>=,<.<=.==,!= 



x = 10

y = 12


# Output: x > y is False

print('x > y is',x>y)


# Output: x < y is True

print('x < y is',x<y)


# Output: x == y is False

print('x == y is',x==y)


# Output: x != y is True

print('x != y is',x!=y)


# Output: x >= y is False

print('x >= y is',x>=y)


# Output: x <= y is True

print('x <= y is',x<=y)


Assignment Operators(=)

Assignment operators are used in Python to assign values to variables.


a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left.


There are various (shorthand Assignment Operators) compound operators in Python like a += 5 that adds to the variable and later assigns the same. It is equivalent to a = a + 5.

These are +=,-=,*=,/=, //=,%=, **=,

a=5

a+=5 equals a=a+5

a-=5 equals a=a-5

a*=5 equals a=a*5


Logical operators

and ,or and not operators are logical operators. Always returns true or false

and returns true if both operands/conditions are true

or returns true if either of the  operand is true

not returns false if operand is true

x = True

y = False

print('x and y is',x and y)  # False

print('x or y is',x or y) # True

print('not x is',not x) #False


Membership Operators 

in and not in are the membership operators in Python. They are used to test whether a value or variable is found in a sequence (string, list, tuple, set and dictionary).


x = 'Hello world'

y = {1:'a',2:'b'}


# Output: True

print('H' in x)


# Output: True

print('hello' not in x)


# Output: True

print(1 in y)


# Output: False

print('a' in y)


Identity operators

is and is not are the identity operators in Python. They are used to check if two values (or variables) are located on the same part of the memory. It returns true if both have same object id. Two variables that are equal does not imply that they are identical.


When you ask Python about whether one object is the same as another object, you are asking if they have the same identity. 


x1 = 5

y1 = 5

x2 = 'Hello'

y2 = 'Hello'

x3 = [1,2,3]

y3 = [1,2,3]


# Output: False

print(id(x2),"   ", id(y1))

print(x1 is not y1)  # compare  object Identity not values

# Output: True

print(x2 is y2)   


# Output: False

print(x3 is y3)   




NOTE


The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory.


IS compare the reference of two variable is same or not while == operator compare values of two variables.

>>> s1='abc'

>>> s2='abc'

>>> s1==s2      #compare values of s1 and s2

True

>>> s1 is s2    # compare reference of s1 and s2

True



e,g

Python create two different object with same value when:

 input string from the keyboard/Assign complex values/

>>> s2=input("Enter a string")

Enter a string abc

>>> s1 is s2      # python create two different object with same value

False

e.g

>>> a=2+3.5j

>>> b=2+3.5j

>>> a is b 

False

>>> a==b

True

Bitwise operators

Bitwise operators are used to compare (binary) numbers:


For example, 2 is 10 in binary and 7 is 111

& (AND) Sets each bit to 1 if both bits are 1

|(OR) Sets each bit to 1 if one of two bits is 1

 ^(XOR) Sets each bit to 1 if only one of two bits is 1

~( NOT) Inverts all the bits


<<  ( Zero fill left shift )

shifts the left operand bits towards the left side for the given number of times in the right operand. In simple terms, the binary number is appended with 0s at the end.


Shift left  by pushing zeros in from the right and let the leftmost bits fall off


>> (Signed right shift) Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

       

 Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Operator Meaning                                Example

&           Bitwise AND                         x & y = 0 (0000 0000)

|         Bitwise OR                                   x | y = 14 (0000 1110)

~         Bitwise NOT                                    ~x = -11 (1111 0101)

^         Bitwise XOR                                   x ^ y = 14 (0000 1110)

>>         Bitwise right shift                           x >> 2 = 2 (0000 0010)

<<         Bitwise left shift                          x << 2 = 40 (0010 1000)





Operator Precedence

When an expression involve multiple operators , python resolves the order of execution through operator precedence.



Operator Associativity 


When two operators have the same precedence, associativity helps to determine which the order of operations.

Associativity is the order in which an expression is evaluated that has multiple operator of the same precedence. Almost all the operators have left-to-right associativity.

For example, multiplication and floor division have the same precedence. Hence, if both of them are present in an expression, left one is evaluates first.








# Left-right associativity

# Output: 3

print(5 * 2 // 3)

# Shows left-right associativity

# Output: 0

print(5 * (2 // 3))


**(RIGHT TO LEFT ASSOCIATIVITY)

>>> 2**3**2

512


>>>2**2**3

256







Variable :

Variable:

Variables are nothing but reserved memory locations. This means that when you create a variable you reserve some space in memory.

ØNamed location that refers to a value and whose values can be used and processed during program run.
Ø Python has no command for declaring a variable. To create a variable, just assign to its name the value of appropriate type.
Ø     Variable are not storage containers in Python like in C,C++ and java etc.
ØWe can use type(variable) command to determine type of variable
Øprint() function is used to display output of  variables
Ø

x = 5
y = "John"
print(x)
print(y)

x = 4 # x is of type int
x = "Sally" # x is now of type
str
print(x)

Multiple Assignment

Python allows you to assign a single value to several variables simultaneously. For example −


a = b = c = 1

Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example −


a,b,c = 1,2,"john"

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "john" is assigned to the variable c.


if we assign multiple values to a single variable 

a=1,2,3

print(a)  #a will be tread by default  tuple

ouput

(1, 2, 3)


Naming variable :

vMust not be a keyword.
vIdentifiers may contain letters , digits and underscore(_)
vAlways starts from letter or underscore
vUpper and lower case are different. Python is case sensitive as it treats lower and upper case character differently.

vAny special character is not allowed except underscore( _ )

Print variable : using print() method

Scope of variable : local and global




Data type


Standard Data Types

The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.


Python data types −

Numbers (int,float,complex)

boolean

String

None

Sequences (List,Tuple,set,Dictionary)



Number In Python

It is used to store numeric values Python has three numeric types: 1. Integers 2. Floating point numbers 3. Complex numbers


3. Complex numbers 

Complex numbers are combination of a real and imaginary part.Complex numbers are in the form of X+Yj, where X is a real part and Y is imaginary part. 

e.g. 

a = complex(5) 

# convert 5 to a real part val and zero imaginary part print(a) 

b=complex(101,23)

 #convert 101 with real part and 23 as imaginary part 

print(b)


Code Output :-

 (5+0j) (101+23j)


Comments in Python

 which is readable for programmer but ignored by python   interpreter

i. Single line comment: Which begins with # sign.

ii. Multi line comment (docstring): either write multiple line beginning with #

sign or use triple quoted multiple line. E.g.

‘’’this is my

first

python multiline comment

‘’’



List

1.A list is a collection which is ordered and changeable.
2.In Python lists are written with square brackets.
3.len() function is used to count the number of items in the list
4.append() function is used to add item  at the end of the list
5.Insert() is used to insert item at any given index position in the list

6.List can store different type of values.


It is a collections of items and each item has its own index value. Index of first item is 0 and the last item is n-1.Here n is number of items in a list.



Creating a list 
Lists are enclosed in square brackets [ ] and each item is separated by a comma.

 list1 = [‘English', ‘Hindi', 1997, 2000]
list2 = [11, 22, 33, 44, 55 ]
list3 = ["a", "b", "c", "d"]

Create list using  constructor method
It is also possible to use the list() constructor to make a new list.
fruits = list(("apple", "banana", "cherry")) # note the double round-brackets
print(fruits)
Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]

for x in fruits:

  print(x)

Change Item Value

To change the value of a specific item, refer to the index number:

fruit = ["apple""banana""cherry"]
thislist[1] = "blackcurrant"
print(thislist)


output:
["apple""blackcurrant""cherry"]


copy()   return the copy of given list
fruits = ['apple', 'banana', 'cherry', 'orange']
x = fruits.copy()
         print(x)


Looping / Iterative Statements 

for loop :

1.It is  used to iterate over a sequence  such as listtuple or string one by one.
2. Iterating over a sequence is called traversal.



# Program to find the sum of all numbers stored in a list

# List of numbers

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum

sum = 0

#iterate over the list

for val in numbers: 

  sum = sum+val

# Output:

The sum is 48print("The sum is", sum)


For loop with else clause

else block will be executed if loop   terminated normally 

digits = [0, 1, 5]

for i in digits: 

  print(i)

else:   

print("No items left.")


Otherwise  else block will not executed

for i in range(1, 4): 
    print(i) 
    break
else: # Not executed as there is a break 
    print("No Break") 





While Loop:
In python, while loop is used to execute a block of statements repeatedly until a given a condition is satisfied. And when the condition becomes false, the line immediately after the loop in program is executed.
else can also be used with while 

Syntax :

while expression:
    statement(s)

# Python program to illustrate  while loop 
count = 1
while (count < =10):   
     print(count)   
    count = count + 1


Nested Loops: 
Python programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept.
Syntax:
   

Comments

Popular posts from this blog

Writing CSV Files