Python Fundamentals
Python Fundamentals
Interpreter Compiler
This language processor converts a HLL program It also compiles the HLL program into machine
into machine language by converting and executing language but the conversion manner is different.
line by line.
It converts the entire HLL program in one go, and
If there is any error in any line, it reports at the same reports all the errors of the program along with the
time and program execution cannot resume until line numbers.
the error is rectified.
After all errors are removed, the program is
recompiled and after that the compiler is not needed
in the memory as the object program is availabe.
Two ways to use interpreter
Interactive mode Script mode-
• store code in a file and use the
type Python commands and the
interpreter to execute the contents of
interpreter displays the result:
the file, which is called a script.
>>> 1 + 1 • Python scripts have names that end
with .py.
2
• To execute the script, press F5.
Useful for testing code but cannot • ^D (Ctrl+D) or quit () is used to leave
save the statements for future use. the interpreter.
• ^F6 will restart the shell.
Python Character Set Tokens (Lexical unit)
• Character set is a set of valid characters that a Smallest individual unit in a program is known as
language can recognize. token.
Floating point literals: real numbers and may be written in fractional form (0.45) or
exponent form (0.17E2).
Example of Float Literals (numeric literal)
height = 6.2, G=6.63E-34, e=1.603E-19
Rules
1. Commas cannot appear in a Floating literal.
2. It may contain either + or – sign.
Types of Literals
String Literal : are sequence of characters surrounded by quotes (single,
double or triple)
Example of String Literals
name = ‘Sara’ , fname=“Sakshi” , name=“”” Sara John”””
Complex number literal : are of the form a+bJ, where a, b are int/floats and
J(or j) represents −1 i.e. imaginary number.
Example:
C1=2+3j
Boolean Literals: It can have value Special Literal None: The None literal is
True or False. used to indicate absence of value.
Example: Example :
b=False c=None
Escape sequence (Non-graphic characters)
• Non-graphic characters are those
characters that cannot be typed
directly from keyboard.
• \n- newline
• \\- backslash
• \’ single quote
Hello \World
RECAP
1. Arithmetic Operators.
2. Relational Operators.
3. Logical Operators.
4. Assignment Operators.
5. Membership Operators
6. Identity Operators
7.Augmented assignment operators
Arithmetic Operators
OUTPUT PRECEDENCE OF
QUESTIONS ARITHMETIC OPERATORS
print(45+23)
PE(MD) (AS) = read PEMDAS
print(45-23) P=parenthesis ()
print(4*12) E=exponential
OUTPUT M, D = multiplication and
print(15/2) 68 division
print(15//2) A, S=addition and subtraction
22
print(5**4) 48 Example:
print(22%3) 5+2*3 =11
7.5 (5+2)/2 = 3.5
7 12*3%4//2+6= 6
12*(3%4)//2+6 = 24
625
1
Relational Operators
Relational operators are used to compare values
OUTPUT OUTPUT
QUESTIONS
False
print(45==23)
True
print(23==23)
True
print(45>23)
print(45<=23)
False
print(45!=23) True
Logical Operators
Logical Operators are used to perform logical operations on the given two variables or
values. Example
>>> 5>2 and 7>5
True
>>> 5>7 or 7>5
True
>>> not(5>7)
True
True and True is True True or True is True not True is False
True and False is False True or F is True not False is True
F and True is False False or True is True
False and False is False False or False is False
Logical Operators- Short-circuiting
and operator
If the first value is False, Python doesn't evaluate the second—it already knows the result will be False.
Or operator
If the first value is True, Python skips the second—it knows the result is True.
Note: Non-Boolean ValuesPython allows and and or to return the actual values, not just
True/False.
Assignment Operator/ Augmented Assignment Operators
➢ In Python, the l-value refers to the left-hand side of an assignment operator, while the r-value
refers to the right-hand side of an assignment operator.
➢ The l-value is associated with a valid memory location in the computer. The memory location
can be checked by using the id( ) function.
➢ The r-value may be any valid expression which is executed by the interpreter.
➢ Consider the following assignment statement:
➢ x = 5+2
➢ In the statement above, the l-value is 'x' as it is on the left-hand side of the = operator.
➢ The r-value is 7 as it is on the right-hand side of the = operator, and is generated by
performing the addition operation on 5 and 2.
➢ The memory location of x may be checked by executing the command id(x)
Membership Operators
Example
>>> 'h' in "hello"
True
>>> 'h' not in "hello"
False
>>>
Python Object
An object is an entity that has certain properties and that exhibit a certain type of behaviour.
e.g., integer values are objects- they hold whole numbers only and they have properties (infinite
precision) and behavior (arithmetic operations)
>>> a=10
>>>type(a) a 10
>>>print(a) # data item contained in the object.
>>>id(a) # memory location of the object.
Identity Operators
• Every object in Python is assigned a unique identity (ID) which remains the same for the lifetime of
that object.
• Identity operators in Python compare the memory locations of two objects.
For example, multiplication and division have the same precedence. Hence, if
both of them are present in an expression, the left one is evaluated first.
Example
>>>100/10*10
100
>>>2 ** 3 ** 2
512
Replication Operators
The repetition operator * will make multiple copies of that particular object
and combines them together. When * is used with an integer it performs
multiplication but with list, tuple or strings it performs a repetition.
s1="python"
print (s1*3) # Output:pythonpythonpython
Concatenation Operators
#Output:Welcome to python
Write equivalent Python Statement for mathematical expression
4𝑥
y= - y=4*x/3
3
z=3xy+7 - z = 3 *x * y + 7
(𝒙+𝟒)
z= - z = (x + 4) / (y - 2)
(𝒚−𝟐)
Evaluate Python expressions
E.g.
‘’’This is my
first
python multiline comment ‘’’
Identify the components of the given python
program
''' This
program is to
def add():
a=2+3
print (a)
add()
SYNTAX
❖ The syntax of a computer language is the set of rules that defines the
combinations of symbols that are considered to be correctly
structured statements or expressions in that language.
❖ It refers to the grammar of a programming language.
L. O . To print data on the screen
• To define and use variables Output statement
var1=‘Computer Science‘
var2=‘Informatics Practices‘
print(var1,' and ',var2 )
OUTPUT
print(“Sum of 2 and 3 is”, 2+3)
a=25 Computer Science and Informatics Practices
Sum of 2 and 3 is 5
print(“Double of”, a , “is”, a*2) Double of 25 is 50
L. O . To print data on the screen
FEATURES OF PRINT STATEMENT
• To define and use variables
1. It auto-converts the items to strings i.e., if you are printing a numeric value, it will
automatically convert it into equivalent string and print it.
2. It inserts space between items automatically because the default value of sep argument is
space (‘ ‘). The sep argument specifies the separator character. The print( ) automatically adds
the sep character between the items/objects being printed in a line.
My name is Priya
3. It appends a newline character (‘\n’) at the end of the line unless you give your own end
argument.
L. O . To print data on the screen
• To define and use variables Find the output
Every value belongs to a specific data type in Python. Data type identifies the type of data
values a variable can hold and the operations that can be performed on that data.
Boolean consist of two constants, True and False. A Python sequence is an ordered collection of
Boolean True value is non-zero, non-null and non-empty. items, where each item is indexed by an
Boolean False is the value zero. integer.
Boolean in Python
String comparison in Python takes place character by character. That is, characters in the same
positions are compared from both the strings. Unicode values of letters in each string are compared
one by one. Result of > and < operator depends on Unicode values of letters at index where they
are not the same.
SEQUENCES - STRINGS
❖ String is a group of characters. (alphabets, digits or special characters including spaces).
❖ String values are enclosed either in single quotation(’) marks or in double quotation marks(“) .
❖ Quotes mark the beginning and end of the string for the interpreter.
❖ numerical operations cannot be performed on strings
E.g., name=“Keerthana”
Single line strings- created by enclosing text in single quotes(‘ ‘) or double quotes (“ “). They must
terminate in one line.
Text1= ‘hello world!’
Multiline Strings :- for text spread across multiple lines.
MULTILINE STRINGS
It can be created in two ways :
a) By adding a backslash at the end of normal single-quote/double quote strings.
In normal strings, just add a backslash in the end before pressing Enter to continue typing text
on the next line.
For instance,
Text1=’hello\
world’
b) By typing the text in triple quotation marks (No backslash needed at the end of line)
Python allows to type multiline text string by enclosing them in triple quotation marks(both triple
apostrophe or triple quotation marks will work)
Text1 = “““ Hello
World “““
SIZE OF STRINGS
1. Python determines the size of a string as the 4. For multiline strings created with
count of characters in the string. single/double quotes and backslash character at
2. Size of escape sequence is 1. the end of the line - while calculating size, the
backslashes are not counted in the size of the
3. For multiline strings created with triple string.
quotes – the EOL(end of line) character at the
>>>Str4 = ‘a\
end of the line is also counted in the size.
b\
>>>Str3 = ‘‘‘ a
b c’
>>>Str4
c ‘‘‘
‘abc’
>>>Str3
‘a\nb\nc’ size of the string Str4 is 3.
‘\\’ 1
‘\n’ 1
“\va” 2
“Seema\’ s pen” 11
STRINGS
Each character in a string is assigned a number. This number is called the index/ subscript
The string "PYTHON" has six characters, numbered 0 to 5, as shown below:
P Y T H O N
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
In Python , indices begin with 0 in the forward indexing and -1.-2,…….. In the backward direction.
>>>print( 'PYTHON’[4])
‘O’ >>> print('PYTHON'[7])
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
print('PYTHON'[7])
IndexError: string index out of range
SEQUENCES - LIST
List is a sequence of items separated by commas and the items are enclosed in square brackets [ ].
Each item has its own index value
E.g.,
>>>L1=[10,20,30,40]
>>>L2=[‘red’, ’green’, ’orange’, ’yellow’]
>>>L3= [‘Nitha’,102, True, None,3.67]
>>>print(L1)
[10,20,30,40]
>>>print(L2[2])
Orange
SEQUENCES- TUPLE
Tuple is a sequence of items separated by commas and items are enclosed in parenthesis (optional).
Each item has its own index value
List and tuple, both are same except, a list is mutable python objects and tuple is immutable Python
objects. Immutable Python objects means you cannot modify the contents of a tuple once it is assigned.
E.g.
>>>T1=(10,20,30,40)
>>>T2=‘red’, ’green’, ’orange’, ’yellow’
>>>T3= (‘Nitha’,102, True, None,3.67)
>>>print(T1)
(10,20,30,40)
>>>print(T2[2])
orange
UNORDERED COLLECTION - SETS
Example
dict1 = {'Fruit':'Apple’, 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
>>>dict= {'Subject': 'comp sc', 'class': '11’}
>>> dict
{'Subject': 'comp sc', 'class': '11’}
>>> print ("Subject : ", dict['Subject'])
Subject : comp sc
>>> dict= {'Subject': 'comp sc', 'class': '11','class':'12'}
>>> dict
{'Subject': 'comp sc', 'class': '12'}
Iterables In Python
Python data types strings, lists, tuples. dictionary etc. are all iterables.
An iterable is any Python object that can return its members, one at a time. Since you can access
elements of strings, lists, tuple and dictionary one at a time, these are all iterables.
Mutable and Immutable Data Types
Variables whose values can be changed after they are created and assigned are called mutable.
Variables whose values cannot be changed after they are created and assigned are called
immutable.
When an attempt is made to update the value of an immutable variable, the old variable is
destroyed and a new variable is created by the same name in memory.
MUTABLE - EXAMPLE
>>> id(l1)
55305960
L. O
• To define and use variables Variables
Python is a type infer language that means you don't need to specify the data
type of variable.
Python automatically get variable data type depending upon the value assigned
to the variable.
L. O
• To define and use variables Variable Definition
a = 23 # Integer
sum = a + b
print (sum)
L. O Program to display values of variables
• To define and use variables
in Python.
length = 10
breadth = 20
Note:
Values are assigned in order-The first variable is assigned the first value, the second
variable gets the second value, and so on.
Python first evaluates all the expressions on the right-hand side (RHS), after evaluation,
the results are assigned to the variables on the left-hand side (LHS) in sequence.
L. O
• To define and use variables Find the output
a=b=c=1
print(a, b, c)
023
L. O
• To define and use variables Guess the output of following code fragment?
p,q=3,5
q , r=p-2 , p + 2 Note:
expressions separated
print(p , q , r) with commas are
evaluated from left to
right and assigned in
315 same order
L. O
• To define and use variables Guess the output of following code fragment?
x , x = 20 , 30
y , y = x + 10 , x + 20
30 50
print(x , y)
L. O
• To define and use variables NameError: name not defined
e.g. print(x)
x = 20
produce NameError
L. O
• To define and use variables DYNAMIC TYPING
Syntax:
type(<variable name>)
e.g.
>>> a = 10
>>> type(a)
<class ‘int’>
>>> b = 20.5
>>> type(b)
<class ‘float’>
L.O
• To input data from the user. SIMPLE INPUT
The built in function input( ) is used to take input from user.
Syntax:
Variablename= input ( [prompt])
Prompt is the string , to display on the screen prior to taking the input, and it is
optional.
e.g.
>>> name=input(“Enter your name:")
Enter your name: Simran
The input() takes the data typed from the keyboard, converts it into a string and
assigns it to the variable on left-hand side of the assignment operator (=).
L.O
• To input data from the user. input()
The input( ) function always returns a value of String type. So even numeric
literals are converted to string.
>>> age= input("Enter your age:")
Enter your age:12
>>> age+1
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
age+1
TypeError: can only concatenate str (not "int") to str
L.O : To convert data from one type
to another.
Type Conversion
We can change the data type of a variable in Python from one type to another.
Such data type conversion can happen in two ways: either explicitly (forced)
when the programmer specifies for the interpreter to convert a data type to
another type; or implicitly, when the interpreter understands such a need by
itself and does the type conversion automatically.
L.O : To convert data from one type
to another.
Type Conversion
The process of converting the value of one data type (integer, string, float, etc.)
to another data type is called type conversion.
Explicit conversion, also called type casting happens when data type conversion takes place
because the programmer forced it in the program.
Syntax
(new_data_type) (expression)
Eg:
>>> int(2.6)
2
>>> float(3)
3.0
L.O : To convert data from one type
to another.
Type conversion functions in Python
The Unicode Standard is the universal character-encoding standard used for representation of
text for computer processing.
L.O : To convert data from one type
to another. EXAMPLE
num1 = 10.2
num2 = 20.6
print(num3)
print(type(num3))
print(num4)
print(type(num4))
L.O : To convert data from one type
to another. Type conversion between numbers and strings.
Python offers two functions int( ) and float( ) to be used with input( ) to
convert the values received through input( ) into int and float types.
Syntax
<variable_name> = int(input(“String to be displayed”) )
OR
<variable_name> = float(input(“String to be displayed”) )
Example
>>> age= int(input("Enter your age:"))
Enter your age:12
>>> age+1
13
eval()
1. While inputting integer values using int( ) with input( ), make sure that the
value being entered must be int type compatible.
>>> age=int(input("How old are you?"))
How old are you?20.5
3) Values like 73 , 73. or .73 are all float convertible, hence python will be able to convert
them to float and no error shall be reported if you enter such values.
>>> marks=float(input("Enter marks:"))
Enter marks:.73
>>> marks
0.73
>>> marks=float(input("Enter marks:"))
Enter marks:73.
>>> marks
73.0
>>> marks=float(input("Enter marks:"))
Enter marks:73
>>> marks
73.0
L.O
To write programs for taking input
from the user and displaying result.
Program to obtain three numbers and print their sum.
The process of identifying and removing mistakes known as bugs or errors from
a program is called debugging.
Errors occurring in programs can be categorised as:
i) Syntax errors
ii) Logical errors
iii) Runtime errors
L.O
To identify different types of errors. Syntax Errors
Python has its own rules that determine its syntax. The interpreter
interprets the statements only if it is correct. If any syntax error is
present, the interpreter shows error message(s) and stops the
execution there.
Eg.
E.g.,
to find the average of two numbers 10 and 12. If we write the code as 10 +
12/2, it would run successfully and produce the result 16. But the correct output
should be 11.
L.O
To identify different types of errors. Runtime Error
E.g.,
i) When a user enters non -numeric value for the denominator of division operation.
ii) If the denominator entered is zero then also it will give a runtime error like “division
by zero”.
L.O:-To identify different tokens,
types of errors. Write Python
statements
NCERT TEXT BOOK QUESTIONS
L.O:-To identify different tokens,
types of errors. Write Python
statements
NCERT TEXT BOOK QUESTIONS
Garbage Collection
amount = 10 #Line 1
amount = 5 #Line 2
print(amount)
When you assign a value to a variable, the variable will reference that value until you assign it a different value.
For example, The statement in Line 1 creates a variable named amount and assigns it the value 10.
Then, the statement in Line 2 assigns a different value, 5, to the amount variable.
The old value, 10, is still in the computer’s memory, but it can no longer be used because it isn’t referenced by a
variable.
When a value in memory is no longer referenced by a variable, the Python interpreter automatically removes it
from memory. This process is known as garbage collection.
Garbage Collection