Getting started with python
Getting started with python
Definition:
“It’s a general purpose, interpreted , object oriented high level programming language.”
Python used by companies like IBM,HP Google, Youtube, i-Robot,NASA, etc.
1. Features
Easy to learn and easy to understand.
It’s a general purpose programming language, i.e. we can develop both scientific and non-
scientific applications.
Free and open source software.
Expressive programming language.
Extensible
Embedded
Platform Independent
Variety of applications can be developed.
Web application
GUI programs
Database applications
Games
2. Dis advantages
Not faster
Lesser libraries compared to C, C++ and Java
Not strong on type binding
Not easily convertible
3. Tokens
The smallest individual unit of a program is called ‘token’
There are 5-types of tokens
1) Keywords
2) Identifiers
3) Literals
4) Punctuators
5) Operators
INTRODUCTION TO PYTHON 19
1) Keywords
These are pre-defined words which has special meaning which we cant change.
The keywords in python are: and are reserved by the programming language
and as assert break class continue def
del elif else except False finally for
from global if importin is lambda nonlocal None
not or pass raise return
True try while with yield
Note: True, False and None are reserved words.
2) Identifiers
These are the names given as variable names or method names or file names or class names etc.
Identifier rules
An identifier should starts with alphabet only.
An identifier can have digit(s) anywhere except starting character.
No keyword/reserved word should be used as an identifier.
An identifier can be any length.
No special characters are allowed except underscore (_).
Python is case sensitive programming language, i.e. upper case letters are different from
lower case letters.
Eg: Identify the valid identifiers among the following
(a) First varia ble (b) while (c) For (d) for1
3) Literals
These are the constants whose values doesn’t change throughout program execution.
Types of literals in python are:
String literals
Numerical literals
Boolean literals
special literals
literal collection
INTRODUCTION TO PYTHON 20
4) punctuators
5) Operators
INTRODUCTION TO PYTHON 21
Subtraction (-)
Multiplication (*)
Division/quotient (/)
Remainder (%)
Floor division (//)
Exponent (**)
Eg(1):
>>>x=5
>>>y=3
>>>z=x+y
>>>print(z)
8
Eg(2):
>>>x=5
>>>y=3
>>>z=x-y
>>>print(z)
2
Eg(3):
>>>x=5
>>>y=3
>>>z=x*y
>>>print(z)
15
Eg(4):
>>>x=5
>>>y=3
>>>z=x/y
>>>print(z)
1.6667
Eg(5):
>>>x=5
INTRODUCTION TO PYTHON 22
>>>y=3
>>>z=x%y
>>>print(z)
2
Floor division(//) discards fraction part from the result if both operands are numbers
without fraction, otherwise this will discard fraction part and it will put ‘.0’
Eg(6):
>>>x=5
>>>y=3
>>>z=x//y
>>>print(z)
1
Eg(7):
>>>x=5.0
>>>y=3
>>>z=x//y
>>>print(z)
1.0
Exponent (**) gives first value to the power of second value.
Eg(8):
>>>x=5
>>>y=3
>>>z=x**y
>>>print(z)
125
Eg(1): >>>2<3
True
False
Note: Every character has its own ASCII value. ‘a’=97, ‘b’=98,…..’z’=122 , ‘A’=65,’B’=66,’’’’’’Z’=90,
‘0’=48,’1’=49,…..’9’=57.
False
‘is’ operator will return ‘False’ if both values doesn’t share common location.
Eg(1):
>>>a=’hi’
>>>b=’bye’
>>>c=input(‘enter string:’)
enter string:hi
>>>a==c
True
>> a is c
INTRODUCTION TO PYTHON 24
False
(d) Logical Operators
These are used to combine two/more conditions as single condition.
The logical operators are:
and
or
not
‘and’ operator result will be ‘True’ iff all conditions result is true, otherwise ‘False’.
‘or’ operator result will be ‘False’ iff all conditions result is false, otherwise ‘True’.
X Y X and Y X or Y
False False False False
False True False True
True False False True
True True True True
‘not’ operator converts True to False or vice versa.
X not X
False True
True False
Decimal to binary
INTRODUCTION TO PYTHON 25
(27)10=(11011)2
(36)10=(100100)2
1. Give the powers (starts from 0) for all the binary digits from right side.
2. Sum of product of each individual digit to 2 to the power of power.
Ans:
INTRODUCTION TO PYTHON 26
Decimal value=1 X 25 + 0 X 24 + 0 X 23 + 1 X 22 + 0 X 21 + 0 X 20
=32+0+0+4+0+0
=36
Bitwise AND (&) will be ‘1’ if all bits are 1, otherwise ‘0’.
Bitwise OR (|) will be ‘0’ if all bits are 0, otherwise ‘1’.
Bitwise XOR (^) will be ‘0’ if all bits are same, otherwise ‘1’.
X Y X&Y X|Y X^Y
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Eg(2): >>>a=5| 3
>>>print(a)
7
Eg(3): >>>a=5^3
INTRODUCTION TO PYTHON 27
>>>print(a)
6
Eg:
>>> a=[1,2,3,4]
>>> 2 in a
True
>>> 20 in a
False
>>> 20 not in a
True
INTRODUCTION TO PYTHON 28
Operator Precedence (from highest priority to lowest)
Operator Meaning
() Parenthesis
** Exponent
~ Bitwise complement
+ - Unary plus , unary minus
* , / , //, % Multiplication,division,floor division,modulo division
+- Addition subtraction
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
<,<=,>,>=,==,!= Comparison operators
is, is not Identity
not Logical NOT
and Logical AND
or Logical OR
Note-1: If there are two/more operators with same priority in same expression, then we have to
evaluate them based on associativity.
4. Datatypes(types)
INTRODUCTION TO PYTHON 29
I) Numericals
Integers
Eg:
>>> a=123456789*123456789
>>> type(a)
<class 'int'>
Floating point numbers
All numbers with fraction part are float in python.
Fraction parts can also be represented with exponent.
>>> a=123.4
Eg:
(or)
>>> a=1234E-1
>>> type(a)
<class 'float'>
complex numbers
Complex numbers will be made up of with two float values.
Complex numbers will be in the form of a+bj (‘a’ represents ‘real’ part and ‘b’ represent ‘imag’
part)
Eg:
>>> a=10+20j
>>> a.real
10.0
>>> a.imag
20.0
Note: type(var) will return the datatype of ‘var’.
INTRODUCTION TO PYTHON 30
II) None:
‘None’ represents no value / unknown / unspecified value.
‘None’ is not same as 0 (zero).
Eg(1):
>>> c=None
>>> type(c)
<class 'NoneType'>
III) Sequence
Ordered collection of items indexed by positive or negative integers.
It is of three types.
(a) Strings
(b) Lists
(c) Tuples
(a) Strings:
String is ordered collection of characters enclosed in single/double/triple quotes.
String characters identified by indexes.
Positive indexes are used to visit the string from beginning to ending.
Negative indexes are used to visit the string from ending to beginning.
Eg:
>>> s='python'
(or)
>>> s="python"
(or)
>>> s='''python'''
(or)
>>> s="""python"""
INTRODUCTION TO PYTHON 31
All characters in string identified by using indexes. i.e. every character has its own index value.
Eg: >>>s=’python’
>>>s[2]
‘t’
>>>s[-2]
‘o’
Eg:
(b) Lists
It is ordered collection of items of any type.
List enclosed in []
List items identified by indexes.
Positive indexes are used to visit the List from beginning to ending.
Negative indexes are used to visit the list from ending to beginning.
Eg:
INTRODUCTION TO PYTHON 32
Lists are mutable.
Eg:
(c) tuples
It is ordered collection of items of any type.
Tuple enclosed in ()
Tuple items identified by indexes.
Positive indexes are used to visit the List from beginning to ending.
Negative indexes are used to visit the list from ending to beginning.
Eg:
INTRODUCTION TO PYTHON 33
IV) Sets
It is unordered collection of items of any type.
Sets doesn’t allow duplicate values.
Sets represents in curly brackets{}.
Eg:
V) Dictionaries
It is collection of key:value pairs.
Dictionaries also represents in culry brackets.
The ‘values’ in dictionary identified by using ‘keys’.
Eg:
5. Variables
Variables will be created automatically once we assign a value.
Variables doesn’t occupy space in python.
Eg:
>>> a=20
>>> b='hi'
Assigning same value to multiple variables.
Eg:
>>> a=b=c=20
Assigning different values into different variables.
Eg:
>>> a,b,c=10,20,30
Lvalue
INTRODUCTION TO PYTHON 34
These are variable/objects into which we can store values.
Lvalues can come either in LHS or RHS.
Lvalues represents operands.
Eg:
>>> a=20
>>> b=a
Rvalue
Rvalues will come only RHS.
Eg:
>>> a=20
>>> 20=a
SyntaxError: can't assign to literal
6. EXPRESSION
Expression is a statement which is a combination of operators and operands.
Types of expressions.
(a) Arithmetic Expressions
(b) Relational Expressions
(c) Logical Expressions
(d) String Expressions
(e) Compound Expressions
Eg(2)
>>> 10>5<6
True
INTRODUCTION TO PYTHON 35
Eg(3)
>>> 10>5<4
False
Eg(2)
>>> 10<5 or 5>4
True
Eg(3)
>>> 10<5 and 5>4
False
Eg(4)
>>> 10>5 and 5>4
True
Eg(5)
>>> 5 or 6
5
Eg(6)
>>> 6 or 5
6
Eg(7)
>>> 5 and 6
6
Eg(8)
>>> 6 and 5
5
Note-1: Logical ‘or’ will give first number if it is non-zero value. If first number value is zero(0),
then it will return second number.
Note-2: Logical ‘and’ will give second number if first number is non-zero value. If first
number/second number value is zero (0), then it will return zero.
INTRODUCTION TO PYTHON 36
Eg(9):
>>> 0 or 6
6
Eg(10):
>>> 0 and 6
0
>>> 20 and 0
0
Eg(2):
In anode example ‘TypeError’ has come, because we can’t concatenate ‘str’ value with an
‘int’ value.
Eg(3):
INTRODUCTION TO PYTHON 37
In above example we didn’t get any error, because ‘b’ value is ‘str’ value but not ‘int’ value.
Eg(4):
In above example, the given value ‘Rama’ stored in ‘name’ variable as string.
INTRODUCTION TO PYTHON 38
In above example, the given value ‘178’ stored in ‘age’ variable as string instead of
number, because input() function will return only string values.
Python offers two functions int() and float() which are used to covert string value into
numbers.
Eg(1): A python statement to read ‘age’ of student from console as a number without
fraction.
In above example the variable ‘age’ value is 17 which is an int value, because we
converted the string value into int value using int() function.
Eg(2): A python statement to read ‘marks’ of student from console as a number with
fraction.
(b) Print()
This function is used to print the statement that has been specified in quotes except escape
sequence.
Few Escape Sequence characters and their meaning listed in the following table.
Eg(1):
Python’s print() function will come few default parameter like end and sep etc.
By default end value is ‘\n’.i.e. end=’\n’. If we want we can change this value.
Eg(1):
print('I Love')
print('Python')
The output of above two line is as follows, because in print default end=’\n’
Output:
I Love
Python
Eg(2):
print('I Love',end=' ')
print('Python')
The output of above two line is as follows, because we changed end=’ ’
Output
INTRODUCTION TO PYTHON 40
I Love Python
Eg(3):
print('I Love',end='@')
print('Python')
The output of above two line is as follows, because we changed end=’@’
Output
I Love@Python
By default sep value is ‘ ’(space).i.e. sep=’ ’. If we want we can change this value.
Eg(1):
a=input('Enter string1:')
b=input('Enter string2:')
print(a,b)
Output:
Enter string1:XI
Enter string2:IP
XI IP
Note: In above output, ‘a’ value is ‘XI’ and ‘b’ value is ‘IP’. We didn’t give any space at the end of
‘a’ value or in the beginning of ‘b’ value, but output there is a space in between ‘a’ and ‘b’
values. Because by default ‘sep’ value is ‘ ‘(space).
Eg(2):
a=input('Enter string1:')
b=input('Enter string2:')
print(a,b,sep='@')
Output:
Enter string1:XI
Enter string2:IP
XI@IP
print() statement with formatted string (using %):
Python supports few string formatting characters like %d or %i (int values), %f (float values) and
%s (str values).
Syntax:
print(‘string formatting character’ % (values))
Note: In above example, string formatting character and values are separated by ‘%’ not by
comma (,).
INTRODUCTION TO PYTHON 41
Eg(1): #filename: print_formatted1_str.py
a,b,c=10,20.5,'30'
print('a values =%i b value is=%f c values is=%s'%(a,b,c))
Output
a values =10 b value is=20.500000 c values is=30
Note: In above example, first string format character is ‘%i’, that’s why the first value must int
values in the list values and second formatted string character is ‘%f’ then second value
must be float value in the list values and so on.
Output
a values =10 b value is=20.500000 c values is=30
Note: In above example, third string format character is ‘%i’, that’s why the third value must int
value in the list of values
format() function in print() statement:
This allows multiple substitutions and value formatting.
format () method is divided into two types of parameters:
Positional parameters: list of parameters that can be accessed with index of parameter
inside curly braces {index}
Eg(1): FileName: print_format_positional_para.py
a,b,c=10,20.5,'30'
print ('a value is {} b value is {} and c values is{}'.format(a,b,c))
print ('a value is {0} b value is {1} and c values is{2}'.format(a,b,c))
Output
a value is 10 b value is 20.5 and c values is30
a value is 10 b value is 20.5 and c values is30
Note: In above example, we are specifying index in {}, then python will assume indexes
starts from 0, 1, 2….
Keyword parameters: list of parameters of type key=value, that can be accessed with
key of parameter inside curly braces {key}
Eg(1): FileName: print_format_keyword_para.py
INTRODUCTION TO PYTHON 42
a,b,c=10,20.5,'30'
print ('a value is {g} b value is {s} and c values is{p}'.format(g=a,s=b,p=c))
Output
a value is 10 b value is 20.5 and c values is30
Note: In above example, within curly braces we used variable names instead of indexes.
We assigned values into these variables in format () function.
8. Comments
Comments are non-executable statements, i.e. python doesn’t interpret the comments.
Comments are used to explain the logic or to prepare the documentation.
Mainly there are two types of comments in python. They are
Single-line comments
Multi-line comments
Single line comments starts with ‘#’ symbol.
Eg:
print('Hello')
#print('this line doesnt execute')
print('I Love Python')
Output
Hello
I Love Python
Triple quotes are used to represent multi line comments. The lines which we would like to put in
comments should be in between triple quotes
Eg:
print('Hello')
'''
Informaics practices
for
class_XI
new syllabus
'''
print('I Love Python')
Output
Hello
I Love Python
Note: in above example, the statements which are represented in triple quotes doesn’t execute.
INTRODUCTION TO PYTHON 43
SAMPLE QUESTIONS
1. Which of the following are syntactically correct strings? Give reason for invalid one(s).
(a) ‘This is great course!’
(b) ‘Informatics “practices” for class XI’
(c) ‘This is great course!”
(d) “hello
2. What is the error in the following python statement?
print(‘name is=’,name)
3. Why the following code is giving errors?
print(‘Hi’)
print(‘Hello’)
print(‘Bye’)
print(‘see..you’)
4. What will be the output of following code?
x,y=10,20
x,y=x,y+20
print(x,y)
5. What is the role of indentation in python?
6. Write a python program to find simple interest?
7. Write a python program to find area of triangle?
8. Write a python program that accepts marks in three subjects and prints their total and average?
9. Find out the error(s) in the following and re-write the corrected and underline the corrections
made?
(a) temp=90 (b) a=[10,20,30] (c) a=10
print temp print (a[5]) b=’hi’
print(a+b)
(d) c=int(‘hi’)’
10. What will be the output after the following code fragment is executed.
(a) c= 2*3 /4 + 5-6/7 *8 (b) b= ((12*13) /14 + (15-16)/17) *18
print(c) print(b)
INTRODUCTION TO PYTHON 44
11. What will be the output after the following code fragment is executed.
x,y=10,20
x,y=x,y+20
print(x,y)
INTRODUCTION TO PYTHON 45