0% found this document useful (0 votes)
4 views

Getting started with python

Python is a high-level, interpreted, object-oriented programming language created by Guido Van Rossum in 1991. It is known for its ease of learning, versatility in application development, and being free and open-source, although it has some disadvantages such as slower performance and fewer libraries compared to other languages. The document also covers key concepts like tokens, operators, data types, and the structure of Python programming.

Uploaded by

Preeti Jain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Getting started with python

Python is a high-level, interpreted, object-oriented programming language created by Guido Van Rossum in 1991. It is known for its ease of learning, versatility in application development, and being free and open-source, although it has some disadvantages such as slower performance and fewer libraries compared to other languages. The document also covers key concepts like tokens, operators, data types, and the structure of Python programming.

Uploaded by

Preeti Jain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Introduction to Python

 Python language is invented by Guido Van Rossum in 1991,Feb.


 He took ‘python ‘word from the comedy serial ‘monty python’s flying circus’ which was
telecasted in BBC.

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

Ans: (c) For (because, this started with capital letter)

(d) for1 (its not keyword)

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

These are the separators like . ‘ ” ‘’’ @ # () [] {} , \

5) Operators

 Operator is a symbol that performs operation on operand(s).


 The types of operators in python are:
(a) Arithmetic operators
(b) Relational operators
(c) Identity operators
(d) Logical operators
(e) Bitwise operators
(f) Assignment operators
(g) Membership operators

(a) Arithmetic operators


These will perform arithmetic operations like addition, subtraction, multiplication, etc.
There are two types of arithmetic operators
i. Unary operators
ii. Binary operators
(i) Unary operators
 These will perform operation on only one operand.
 The unary operators are
 Unary plus (+)
 Unary minus (-)
 Complement (~)
 not
Note: complement (~) is bitwise and ‘not’ is logical operators
 Unary plus (+) and unary minus represents sign of a value.
Eg(1): x=+5 (or) x=5
Eg(2): x=-5
(ii) Binary operators
 These will perform operation on exactly two operands.
 The binary operators are:
 Addition (+)

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

(b) Relational Operators


 These are used to compare to operands.
 Also called as comparison operators.
 The relational/comparison operators are:
Lessthan(<)
Lessthan or equalsto(<=)
Greaterthan(>)
Greaterthan or equalsto(>=)
INTRODUCTION TO PYTHON 23
Is equals to (==)
Not equals to (!=)
 The result of relational operator is ‘bool’ value(i.e. True/False)

Eg(1): >>>2<3

True

Eg(2): >>> ‘a’<’A’

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.

Eg(3): >>> ‘aB’<’aA’

False

(c) Identity operators:


 Identity operators are ‘is’ and ‘is not’.
 ‘is’ operator will return ‘True’ iff both values share common location.
Eg(1)
>>>a=10
>>>b=15
>>>c=10
>>>a==c
True
>> a is c
True

 ‘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

(e) Bitwise operators:


 These will perform operations on bits of numbers but result will be in the form of decimal
only.
 The bitwise operators are
 Bitwise and (&)
 Bitwise or (|)
 Bitwise XOR (^)
 Bitwise complement (~)

Decimal to binary

1. Divide the decimal value with 2.


2. Note the remainder.
3. Repeat step1 and step2 till quotient is not divisible by 2.
4. Take all the reminders from bottom to top.

Eg(1) convert (27)10 into binary.

INTRODUCTION TO PYTHON 25
(27)10=(11011)2

Eg(2) convert (36)10 into binary.

(36)10=(100100)2

Binary to Decimal conversion

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.

Eg(1) convert (100100)2 into decimal number.

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

So, (100100)2= (36)10

 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

Eg1: >>>a=5 & 3


>>>a
1

Eg(2): >>>a=5| 3
>>>print(a)
7

Eg(3): >>>a=5^3
INTRODUCTION TO PYTHON 27
>>>print(a)
6

 Bitwise complement (~) converts 1 to 0 or 0 to 1.

(f) Membership operators


 ‘in’ and ‘not in’ are the membership operators.
 ‘in’ will return True if the value is in sequence, otherwise ‘False’.
 ‘not in’ will return ‘True’ if the value is not in sequence, otherwise ‘False’.

Eg:
>>> a=[1,2,3,4]
>>> 2 in a
True
>>> 20 in a
False
>>> 20 not in a
True

(g) Assignment operators


 This is used to assign a value into a variable.
 The assignment operators are:
 Assignment (=)
 Assign sum(+=)
 Assign difference (-=)
 Assign mulplication (*=)
 Assign quotient(/=)
 Assign mod(%=)
 Assign floor division(//=)
 Assign exponent(**=)
Eg:
>>> a=10
>>> a+=5
>>> print(a)
15

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.

Note-2: Associativity of all operators is from left to right except **(Exponent).

4. Datatypes(types)

This specifies the type of value and its associated operations.

INTRODUCTION TO PYTHON 29
I) Numericals

 These are the numbered values.


 It is of 3-types
 Intergers
 Floating point numbers
 Complex numbers

Integers

 All numbers without fraction part are integers in python.

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’

 Strings are immutable (string can’t be changed.).

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:

 Tuples are immutable.


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

(a) Arithmetic Expressions


It is the combination of arithmetic operators and operands.
Eg:
>>> a=2+3*4/5%6
>>> print(a)
4.4
Note: The equivalent expression for above example is a=2+ (((3*4)/5) %6)
(b) Relational Expression
It is the combination of relational operators and operands.
Eg(1):
>>> 10>5
True

Eg(2)
>>> 10>5<6
True

INTRODUCTION TO PYTHON 35
Eg(3)
>>> 10>5<4
False

(c) Logical Expression


It is the combination of logical operators and operands.
Eg(1)
>>> 10<5 or 5>6
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

(d) String expression


 It is the combination of string operators(*,+) and strings.
 ‘+’ operator will concatenate two string values.
 ‘*’ operator repeats the given string for given number of times.
Eg(1):
>>> a='hi'
>>> b='bye'
>>> c=a+b
>>> print(c)
Hibye

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):

(e) Compound Expressions


 It is the combination of two/more expressions.
Eg(1):

 The above expression will execute as follows.(Here, we followed operator precedence.)


a =2+12/5 and 7 or 8
=2+2.4 and 7 or 8
=4.4 and 7 or 8
=7 or 8
a =7

7. Input and Output functions


Python allows input() function to take input and print() function to print output.
(a) input()
 This is used to get input interactively from user.
 This function will return the given input in the form of string.
Syntax:
variable=input(‘message to be displayed’)
Eg(1): A python statement to take name of student from console.

 In above example, the given value ‘Rama’ stored in ‘name’ variable as string.

Eg(2): A python statement to read ‘age’ of student from console.

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.

Escape Sequence Meaning


\\ Single back slash
\’ Single quote
INTRODUCTION TO PYTHON 39
\” Double quote
\a Bell sound
\b Backspace
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab

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.

 Eg(2): #filename: print_formatted2_str.py


a,b,c=10,20.5,30
print('a values =%i b value is=%f c values is=%i'%(a,b,c))

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)

(c) a = 17 (d) x=5


b = 23 y=x+3
print( "a =", a, "and b =", b ) x=x-1
a += b z=10
a,b=b,a x=x+z
print( "a =", a, "and b =", b ) print('x: {}, y: {}, z: {}'.format(x, y, z))

(e) print(14//4, 14%4, 14.0/4) (f) print(2*'No' + 3*'!')


print(2 * ('No' + 3*'!'))
(g) print('how\nis it\nnow')

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

You might also like