























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
An introduction to Python programming language, including its interpreter and interactive mode, values and types, variables, expressions, statements, modules, and functions. It also covers the features of Python, its applications, and the modes of execution. the sequence data types available in Python, including strings, lists, and tuples, and the operations that can be performed on them. It also provides examples of how to create, access, slice, concatenate, repeat, update, insert, and delete elements in lists.
Typology: Study notes
1 / 31
This page cannot be seen from the preview
Don't miss anything!
Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables,
expressions, statements, tuple assignment, precedence of operators, comments; Modules and functions,
function definition and use, flow of execution, parameters and arguments; Illustrative programs: exchange
the values of two variables, circulate the values of n variables, distance between two points.
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language.
It was created by Guido van Rossum during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was released in the year 2000.
compile your program before executing it.
directly to write your programs.
that encapsulates code within objects.
Level programmers and supports the development of a wide range of applications.
Python Features:
simple. It uses few keywords.
platforms.
program before executing it. You can simply run the program.
, ActiveX, etc.
current problem, no need to worry about the low level details.
Applications:
Python interpreter:
Interpreter: To execute a program in a high-level language by translating it one line ata time.
Compiler: To translate a program written in a high-level language into a low-level language all at once, in
preparation for later execution.
Compiler Interpreter
Compiler Takes Entire program as input
Interpreter Takes Single instruction as input
Intermediate Object Code is Generated
No Intermediate is
Generated
Object Code
Conditional Control Statements are
Executes faster
Conditional Control
Executes slower
Statements are
Memory Requirement is More (Since Object
Code is Generated)
Memory Requirement is Less
Program need not be compiled every time
Every time higher level program is
converted into lower level program
Errors are displayed after entire program is checked Errors are displayed for every instruction
interpreted (if any)
Example : C Compiler Example : PYTHON
Modes of python interpreter :
Python Interprete r is a program that reads and executes Python code. It uses 2 modes of Execution.
Interactive mode:
Advantages:
Drawback:
In interactive mode, you type Python programs and the interpreter displays the result:
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you to enter code. If you
type 1 + 1, the interpreter replies 2.
print ('Hello, World!')
Hello, World!
Auto completion with smart indentation.
Python shell to display output with syntax highlighting.
Value:
Value can be any letter, number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different datatypes.)
Data type :
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
Python has four standard data types:
Numbers:
Sequence:
datatypes.
**1. Strings
Strings:
characters.
lines and sentences."""
Immutable i.e the contents of the string cannot be changed after it is created.
Indexing:
Example: A[0] or A[-5] will display “H”
Example: A[1] or A[-4] will display “E”
Operations on string:
Creating a string >>> s="good morning" Creating the list with elements of different
data types.
Indexing >>> print(s[2])
o
print(s[6])
position 0
position
the
the
item
item
in
in
the
the
Slicing( ending
position - 1)
print(s[2:])
od morning
nd till
last.
Repetition
list2*
['god', 6.78, 9, 'god', 6.78, 9, 'god',
Creates new strings, concatenating
multiple
copies of the same string
Updating the list >>> list1[2]=
print( list1)
[‘python’, 7.79, 45, ‘hello’]
Updating the list using index value
Inserting an element
list1.insert(2,"program")
print(list1)
['python', 7.79, 'program', 45,
'hello']
Inserting an element in 2
nd position
Removing an element
list1.remove(45)
print(list1)
['python', 7.79, 'program', 'hello']
Removing an element by
giving the element directly
Tuple:
instead of square brackets.
remove elements from the tuple.
Basic Operations:
Creating a tuple >>> t=("python", 7.79, 101,
"hello”)
Creating the tuple with elements
of different data types.
Indexing
print(t[0]) python
t[2]
position
position
Slicing( ending
position - 1)
print(t[1:3])
till2nd.
Concatenation >>> t+("ram", 67)
('python', 7.79, 101, 'hello', 'ram',
the end of another tuple elements
Repetition >>> print(t2)*
('python', 7.79, 101, 'hello',
'python', 7.79, 101, 'hello')
concatenating multiple copies of the
same string
Altering the tuple data type leads to error. Following error occurs when user tries to do.
Mapping
Dictionaries:
(or mapped) to a value.
pairs( The association of a key and a value is called a key- value pair)
Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and lists.
Creating a
dictionary
>>> food = {"ham":"yes", "egg" :
"yes", "rate":450 }
print(food)
{'rate': 450, 'egg': 'yes', 'ham':
'yes'}
Creating
elements
types.
the
of
dictionary
different
with
data
Indexing >>>> print(food["rate"])
Accessing the item with keys.
Slicing( ending
position - 1)
print(t[1:3])
Displaying items from 1st till 2nd.
If you try to access a key which doesn't exist, you will get an error message:
words = {"house" : "Haus", "cat":"Katze"}
words["car"]
Traceback (most recent call last): File
"
Data type Compile time Run time
int a=10 a=int(input(“enter a”))
float a=10.5 a=float(input(“enter a”))
string a=”panimalar” a=input(“enter a string”)
list a=[20,30,40,50] a=list(input(“enter a list”))
tuple a=(20,30,40,50) a=tuple(input(“enter a tuple”))
Example:
Names like myClass, var_1, and this_is_a_long_variabl e
Valid declarations Invalid declarations
Num Number 1
Num num
Num1 addition of program
_NUM 1Num
NUM_temp2 Num.no
IF if
Else else
Statements :
n = 17
print (n)
Here, The first line is an assignment statement that gives a value to n. The second line is
a print statement that displays the value of n.
Expressions:
a=
a+3+2 7
z=("hi"+"friend")
print(z) hifriend
INPUT: Input is data entered by user (end user) in the program. In python, input
() function is available for input.
Example:
#python accepts string as default data type. Conversion is required for type.
OUTPUT: Output can be displayed to the user using Print statement.
Example:
A hash sign (#) is the beginning of a comment.
Anything written after # in a line is ignored by interpreter.
Eg: percentage = (minute * 100)/60 # calculating percentage of an hour
Python does not have multiple-line commenting feature. You have to comment each line
individually as follows:
Example :
Docstring is short for documentation string.
It is a string that occurs as the first statement in a module, function, class, or method definition. We
must write what a function/class does in the docstring.
Triple quotes are used while writing docstrings.
Syntax:
functionname__doc.__ Example:
Most of the programming languages like C, C++, Java use braces { } to define a block of code. But,
python uses indentation.
Blocks of code are denoted by line indentation.
It is a space given to the block of codes for class and function definitions or flow control.
In tuple packing, the values on the left are ‘packed’ together in a tuple:
right:
Example:
mailid='god@abc.org'
name,domain=mailid.split('@')
print name god
print (domain) abc.org
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator
Types of Operators:
Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction, multiplication etc.
Assume, a=10 and b=
Operator Description Example
operand.
right hand operand from left hand a – b = - 10
/ Division Divides left hand operand by right hand operand b / a = 2
% Modulus Divides left hand operand by right hand operand and returns
remainder
b % a = 0
** Exponent Performs
operators
exponential (power) calculation on a**b =10 to the
power 20
// Floor Division - The division of operands where the result is the
quotient in which the digits after the decimal point are removed
Examples
a=
b=
print("a+b=",a+b)
print("a-b=",a-b)
print("ab=",ab)
print("a/b=",a/b)
print("a%b=",a%b)
print("a//b=",a//b)
print("ab=",ab)
Output:
a+b=
a-b= 5
a*b= 50
a/b= 2.
a%b=
a//b=
a**b= 100000
Comparison (Relational)Operators:
Operator Description Example
== If the values of two operands are equal, then the condition (a == b) is
Multiply It multiplies right operand with the left operand and assign the
result to left operand
c *= a is
equivalent to c
= c *a
Divide It divides left operand with the right operand and assign the result
to left operand
c /= a is
equivalent to c
= c /ac
/= a is
equivalent to c
= c /a
Modulus It takes modulus using two operands and assign the result to left
operand
c %= a is
equivalent to c
= c % a
**= Exponent
Performs exponential (power) calculation on
operators and assign value to the left operand
c **= a is
equivalent to c
= c ** a
//= Floor
Division
It performs floor division on operators and assign value to the left
operand
c //= a is
equivalent to c
= c // a
Example
a =
b =
c = 0
c = a + b
print("Line 1 - Value of c is ",c)
c += a
print("Line 2 - Value of c is ", c)
c *= a
print("Line 3 - Value of c is ",c)
c /= a
print("Line 4 - Value of c is ", c)
c = 2
c %=a
print("Line 5 - Value of c is ",c)
c **= a
print("Line 6 - Value of c is ",c)
c //= a
print ("Line 7 - Value of c is ", c)
Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.
Line 5 - Value of c is
Line 6 - Value of c is 2097152
Line 7 - Value of c is
Logical Operators:
Example
a = True
b = False
print('a and b is', a and b)
print('a or b is' ,a or b)
print('not a is', not a)
Output
x and y is False
x or y is True
not x is False
Bitwise Operators :
Example: Let x = 10 (0000 1010 in binary)and
y = 4 (0000 0100 in binary)
Example
a = 60
Output
Line 1 - Value of c is 12
b = 13
c = 0
c = a & b;
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is- 61
print "Line 1 - Value of c is ", c
c = a|b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c
c = a^b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
c =~a; # - 61 = 1100 0011
Line 5 - Value of c is 240
Line 6 - Value of c is 15
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description
** Exponentiation (raise to the power)
~ + - Complement, unary plus and minus (method names for the
last two are +@ and - @)
<< Right and left bitwise shift
& Bitwise 'AND'
^ | Bitwise exclusive OR' and regular
OR'
<= <>>= Comparison operators
<> == != Equality operators
= %= /= //= - = += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
useful way to remember the rules:
order you want. Since expressions in parentheses are evaluated first, 2 * (3-1)is 4, and (1+1)**(5-2)
is8.
3*2 is 18, not 36.
not 4, and 6+4/2 is 8, not5.
Examples:
a=9-12/3+3*2- 1
a=?
a=9-4+3*2- 1
a=9-4+6- 1
a=5+6-1 a=11-
1 a=
find m=?
m=-43||8&&0||- 2 m=-
43||0||-2 m=1||- 2
m=
Parameters And Arguments, Return statement, Arguments types, Modules
A large program is divided into basic building blocks called function.
Need For Function:
coded and combined into single program. Each subprogram is called as function.
subprograms.
Types of function:
Functions can be classified into two categories:
i) Built in functions
modified.