0% found this document useful (0 votes)
5 views102 pages

Python Fundamentals

Uploaded by

nagulan0407
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views102 pages

Python Fundamentals

Uploaded by

nagulan0407
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 102

Unit 2

Chapter 2 Python Fundamentals


Learning Outcomes
➢ Differentiate interpreter and compiler
➢ Write programs to display messages on screen
➢ Identify different tokens in given code
➢ Perform simple math operations
➢ Evaluate python statements using different types of data.
Introduction To Python

• Python is a general purpose interpreted, Python Software


interactive, object-oriented and high-level
1 ) https://www.python.org/downloads/
programming language.
2) https://www.anaconda.com/
• Creator : Guido van Rossum.
• Year: I991.
• Uses:
➢ software development,
➢ web development (server-side),
➢ system scripting,
➢ Mathematics.
Strengths of Python Weakness of Python

➢ Easy to use ➢ Not the fastest Language


➢ Expressive Language ➢ Lesser Libraries than C , Java, Perl
➢ Interpreted Language ➢ Not Strong on Type binding
➢ Completeness ➢ Not easily convertible
➢ Cross Platform Language
➢ Free and Open Source
➢ Portable and platform independent
➢ Variety of usage/ Applications
L.O: Differentiate interpreter
and compiler

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.

• Letters :–A-Z,a-z 1.Keywords


2.Identifiers
• Digits :–0-9
3.Literals
• Special symbols :–Special symbol available over
4.Operators
keyboard
5.punctuators
• White spaces:–blank space, tab, carriage return,
newline, form feed
Keywords
• Predefined words with special
meaning to the language processor. None True and
• Reserved for special purpose and as assert async
await break class
must not be used as normal continue def del
identifiers names. elif else except
finally for from
global if import
• To get the list of keywords in is lambda
nonlocal not or
import keyword pass raise return
s = keyword.kwlist try while with
yield False
Identifiers
• A Python identifier is a name used to identify a variable, function, class, module or other
object.

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


zero or more letters, underscores and digits (0 to 9).

• Python does not allow special characters

• Identifier must not be a keyword of Python.

• Python is a case sensitive programming language.

• Thus, Rollnumber and rollnumber are two different identifiers in Python.

• Some valid identifiers : Mybook, file123, z2td, date_2, _no

• Some invalid identifier : 2rno,break,my.book,data-cs


Literals
• Literals are data items that have fixed value.
• It can be defined as number, text, or other data that represent values to be stored in variables.
Types of Literals
Numeric Literal : are numeric values in decimal/octal/hexadecimal form.
Example of Integer Literals (Numeric Literal)
age=18 , D2=0o56 (Octal) D3=0x12 (Hex)

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

• \t- horizontal tab

• \\- backslash

• \’ single quote

• \”- Double quote


Example

>>> print("Happy\tNew\tYear") >>> print("Hello \'World\' ")

Happy New Year Hello 'World'

>>> print("Hello\nWorld") >>> print("Hello \"World\" ")


Hello Hello "World"
World
>>> print("Hello \\World")

Hello \World
RECAP

print('Hey, what\'s up?' )


print("Multiline strings\ncan be created\nusing escape
sequences.")
print("C:\\Users\\Pat\\Desktop")
print("Happy\tNew\tYear")
txt = "We are the so-called \"Vikings\" from the north."
print(txt)
print("I will go\tHome")
print("See you\jtommorow")
print( "I love to use \t instead of using 4 spaces")
print( "I love to use \\t instead of using 4 spaces")
RECAP- Output

Hey, what's up?


Multiline strings
can be created
using escape sequences.
C:\Users\Pat\Desktop
Happy New Year
We are the so-called "Vikings" from the north.
I will go Home
See you\jtommorow
I love to use instead of using 4 spaces
I love to use \t instead of using 4 spaces
Operators
Operators can be defined as symbols that are used to perform operations
on operands.
Unary ( operator which operates on one operand) and binary operators
(requires two operands to operate upon)
Types of Operators

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

Used to assign values to the variables.


OUTPUT
QUESTIONS
a=5
b=7
c=3
a**=2
a*=b
b-=7
c+=a+5
c%=10
print(a) OUTPUT
print(b) 175
print(c) 0
3
Concept of L Value and R Value

➢ 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

The membership operators in Python are used to validate whether a value is


found within a sequence such as strings, lists, or tuples.

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.

>>> a=2 >>> b=4


>>> b=2
>>> id(a)
>>> id(b)
1372415088 1372415120
>>> id(b) >>> a is b
1372415088 False
>>> a is b
True
Precedence of all the operators in Python
Associativity of Python Operators
Associativity is the order in which an expression is evaluated that has multiple
operators of the same precedence. Almost all the operators have left-to-right
associativity. But the exponent operator (**) has right-to-left associativity in
Python.

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

Concatenation means joining strings together end-to-end to create a new


string.
+ operator results in addition to int objects and concatenation in strings.
Concatenation between
x = "Python is "
different data types will
y = "awesome"
raise TypeError.
z= x+y
print(z)
If the strings are placed next to each other without + operator this will result
in a concatenation. s1="Welcome"
s2="to"
s3="python"
s='Welcome’ 'to’ 'Python' s4=s1+" " + s2+" "+ s3
print (s) #Output:WelcometoPython print (s4)

#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

Question: Evaluate the Following statement.


34 + 12 / 4 – 45
Solution:

Question: Evaluate the Following statement


1 + 2 * 3 ** 4 / 9 % 6 + 7
Solution:
Evaluate Python expressions

Question1: Evaluate the Following statement.


4*5+ 7*2-8%3+4

Question2: Evaluate the Following statement


Logical AND operator: If the first
5.7//2-1+4 or not 2==4
expression evaluated to be false
while using and operator, then
Question2: Evaluate the Following statement
the further expressions are not
not 2**4>6*2
evaluated.
▪ Integer division or floor
division
▪ E.g. 5/2=2.5 ▪ Modulus operator
5//2=2 E.g. 5%2=1
-5//2=-3 -5%2=1
5//-2=-3 5%-2=-1
Here result will be floored Python’s modulo operator always returns a
(round down). So 5/2=2.5 so number having the same sign as the denominator
5//2=2 (divisor) and therefore the equation running on the
For negative numbers, -5/2=- back will be the following:
2.5 so -5//2=-3 & 5//-2=-3 mod = a — math.floor(a/b) * b
i.e., returning the largest For example, working with our example, we’d get:
integer less than or equal to x. mod = 5 — math.floor(5/2) * 2
mod = 5–2*2 = 1
Punctuators
• They are symbols that are used in programming languages to organize sentence structures,
statements, expressions.

• Following are the python punctuator.


• ‘ (Single Quote) ,“ (Double Quote)
• # (Hash), \ (backward slash)
• ( ) (parenthesis), [ ] (Square bracket), { } (Curly bracket)
• @ (at the rate)
• , (comma)
• : (colon)
• . (dot)
• = (Assignment)
Components of Python Program
A python program contain the following components

❖ Expression: -An expression is defined as a ❖ Statement:-instruction that does


combination of constants, variables, and something.
operators. ❖ e.g
An expression always evaluates to a value. a = 20
E.g. (20 + 4) / 4 #combination of operator print("Calling in proper sequence")
and literals , evaluates to a value ❖Function
5 #value is an expression
a code that has some name and it can be
‘hai’ #string is also an expression reused.
❖Block& indentation:
Python interpreter evaluates the expression
group of statements is block.
and returns the result .
Indentation at same level create a block.
Components of Python Program (continued…)

❖Comments: which is readable for programmer but ignored by python


interpreter. Comments are used to add a remark or a note in the source code.
▪ Single line comment: which begins with # sign.
▪ 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 ‘’’
Identify the components of the given python
program

#This is my first program

''' This

program is to

add two numbers'''

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

print() function in Python is used to print output on the screen.


Syntax
print([expression/variables,sep=<‘seperator string’>,end=<‘end string’>])
e.g.
print(122)
Output :-
122
print('hello India')
Output :-
hello India
print(‘Computer',‘Science')
print(‘Computer',‘Science',sep='&')
sep and end values are strings .
print(‘Computer',‘Science',sep='&',end='.')
Output :- default sep value is single space and
Computer Science end value is newline(‘\n’)
Computer&Science
Computer&Science.
L. O . To print data on the screen
• To define and use variables
Find the output

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.

Eg., >>> print( 'My','name','is','Priya')

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

print( 'My name is Priya') OUTPUT


My name is Priya
print('I am 17 years old') I am 17 years old
print( 'My','name','is','Priya',sep='...') My...name...is...Priya
DATA TYPES

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

It is used to store two possible values either True or False


e.g.
bool=‘bat'>’ball’ ◦ True , False and None
print(bool) are built-in constants/
literals in Python
Output
True
Bool=‘car’>’cat’
Output
False

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.

size of the string Str3 is 5.


SIZE OF STRINGS

# to check the size of a string, use built in String value Size


function len(stringname).
“abc” 3
All Python (3.x) strings store Unicode
characters ‘hello’ 5

‘\\’ 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

Set is an unordered collection of items


separated by commas and the items are >>> s={10,20,30,40,30}
enclosed in curly brackets { }. A set is similar to
>>> s
list, except that it cannot have duplicate
entries. {40, 10, 20, 30} #sets do not allow duplicate
entries
Once created, elements of a set cannot be
changed. >>> s={1,2,[3,4]}
E.g., Traceback (most recent call last):
>>> s={10,20,30,40} File "<pyshell#11>", line 1, in <module>
>>> s[3] s={1,2,[3,4]}
TypeError: unhashable type: 'list'
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module> Application of Sets In Python
The Python sets are highly useful to efficiently remove
s[3] duplicate values from a collection like a list and to
TypeError: 'set' object is not subscriptable perform common math operations like unions and
intersections.
UNORDERED COLLECTION - DICTIONARY

Mapping is an unordered data type in Python.


Dictionary is an unordered collection of comma separated key : value pairs within curly braces { },
with the requirement that within a dictionary, no two keys can be the same
Dictionaries permit faster access to data.

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

>>> l1=[1,2,3] >>> d={'name':'Arya','class':12}


>>> d['name']='Jenny'
>>> id(l1)
>>> d
55305960
{'name': 'Jenny', 'class': 12}
>>> l1[2]=7

>>> id(l1)

55305960
L. O
• To define and use variables Variables

Variable is a name given to a memory location. A variable can consider as a


container which holds value.

Python is a type infer language that means you don't need to specify the data
type of variable.

In Python we can use an assignment statement to create new variables and


assign specific values to them.

Python automatically get variable data type depending upon the value assigned
to the variable.
L. O
• To define and use variables Variable Definition

Variables must always be assigned values before they are used in


expressions as otherwise it will lead to an error in the program.
Wherever a variable name occurs in an expression, the interpreter
replaces it with the value of that particular variable.
L. O
• To define and use variables Assigning Values To Variable

name = ‘python‘ # String Data Type

sum= None # a variable without value

a = 23 # Integer

b= 6.2 # Float 29.2

sum = a + b

print (sum)
L. O Program to display values of variables
• To define and use variables
in Python.

#To display values of variables


message = "Keep Smiling"
print(message)
userNo = 101
OUTPUT
print('User Number is', userNo)
Keep Smiling
User Number is 101
L. O Write a Python program to find the area of a
• To define and use variables rectangle given that its length is 10 units and
breadth is 20 units.

#To find the area of a rectangle

length = 10

breadth = 20

area = length * breadth

print(“ The area of the rectangle is: “,area,”sq units”)


L. O
• To define and use variables
Multiple Assignment

Assign a single value to many variables

a=b=c=1 # single value to multiple variable

a,b= 1,2 # multiple value to multiple variable

a,b= b,a # value of a and b is swapped

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

b , c , a = a+1 , b+2 , c-1 #Statement 2

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

Using an undefined variable in an expression/statement causes an


error called NameError.

e.g. print(x)
x = 20
produce NameError
L. O
• To define and use variables DYNAMIC TYPING

A variable pointing to a value of a certain type, can be made to point to a


value/object of different type. This is called Dynamic Typing.
e.g.
X =10
print(X)
X = “Hello World”
print(X)
output :
10
Hello World
L.O
• To print the type of a variable type()

Type of a variable can be found using the type( ) in following manner :

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.

Python has two types of type conversion.

Implicit Type Conversion

Explicit Type Conversion


L.O : To convert data from one type Implicit Conversion
to another.

It is performed by the compiler without the programmer’s intervention,


done automatically by Python.
Compiler converts all operands up to the type of the largest operands and
this is called type promotion or coercion.
e.g.
nint=12
nflo=10.23
nnew= nint +nflo OUTPUT

print (nnew, type(nnew)) 22.23 <class 'float'>


L.O : To convert data from one type
to another.
Explicit 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

int (x )- Converts x to an integer


float(x ) - Converts x to a floating-point number
str( x) - Converts x to a string representation
complex(x ) - Converts x to a complex number
bool(x) – Converts to Boolean value
chr(x) - Converts x to a character
ord(x) – converts x to its equivalent ASCII value
L.O : To convert data from one type
to another. EXAMPLE
>>> int(5.6)
>>> float(3) >>> str(3)
5 3.0
'3'
>>> int('5') >>> float('3')
5 3.0 >>> str(2.5)
>>> int(3+5j) >>> float('3.0') '2.5'
Traceback (most recent call last): 3.0 >>> str(True)
File "<pyshell#2>", line 1, in <module>
>>> float(3+2j)
int(3+5j) 'True'
Traceback (most recent call last):
TypeError: can't convert complex to int
File "<pyshell#12>", line 1, in <module>
>>> str(False)
>>> int(True)
float(3+2j) 'False'
1
>>> int(False) TypeError: can't convert complex to float >>> str(2+3j)
0 >>> float(True) '(2+3j)’
>>> int(None) 1.0
Traceback (most recent call last):
>>> str(None)
>>> float(False)
File "<pyshell#35>", line 1, in <module> 0.0 'None'
int(None)
>>> float(None)
TypeError: int() argument must be a string, a bytes-like
object or a number, not 'NoneType’ Traceback (most recent call last):
>>> int('5.6') File "<pyshell#36>", line 1, in <module>
Traceback (most recent call last): float(None)
File "<pyshell#0>", line 1, in <module> TypeError: float() argument must be a string or a
int('5.6') number, not 'NoneType'
ValueError: invalid literal for int() with base 10: '5.6'
L.O : To convert data from one type
to another. EXAMPLE
>>> complex(5) >>> bool(5)
(5+0j) True
>>> bool(5.6)
>>> complex(2.0)
True
(2+0j)
>>> bool(0)
>>> complex(2.6) False
(2.6+0j) >>> bool(None)
>>> complex('3') False
(3+0j) >>> bool(2+5j)
>>> complex('3.0') True
>>> bool(-7)
(3+0j)
True
>>> complex(True)
>>> bool(0+2j)
(1+0j) True
>>> complex(False) >>> bool(0+0j)
0j False
>>> complex(None)
Traceback (most recent call last): >>> bool('hai')
True
File "<pyshell#3>", line 1, in <module>
>>> bool('')
complex(None)
False
TypeError: complex() first argument must be a >>> bool(' ')
string or a number, not 'NoneType'
True
L.O : To convert data from one type
to another. ASCII TABLE

ASCII stands for


American
Standard Code for
Information
Interchange.
Computers can
only understand
numbers, so an
ASCII code is the
numerical
representation of
a character such
as 'a' or '@' or an
action of some
sort.
UNICODE

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

>>> chr(65) >>> ord('A')


65
'A'
>>> ord('/')
>>> chr(47) 47
'/' >>> ord('\n')
>>> chr(50) 10
>>> ord('2')
‘2’
50
L.O : To convert data from one type Program of explicit type conversion from
to another. int to float

#Explicit type conversion from int to float


num1 = 10
num2 = 20
num3 = num1 + num2
print(num3)
print(type(num3))
num4 = float(num1) + num2
print(num4)
print(type(num4))
L.O : To convert data from one type Program of explicit type conversion from
to another. float to int.

#Explicit type conversion from float to int

num1 = 10.2

num2 = 20.6

num3 = (num1 + num2)

print(num3)

print(type(num3))

num4 = int(num1 + num2)

print(num4)

print(type(num4))
L.O : To convert data from one type
to another. Type conversion between numbers and strings.

#Type Conversion between Numbers and Strings


priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie
print("The total is Rs." + totalPrice )
Traceback (most recent call last):
File "C:\ty.py", line 5, in <module>
print("The total is Rs." + totalPrice )
TypeError: can only concatenate str (not "int") to str
L.O : To convert data from one type
to another. Type conversion between numbers and strings.

#Type Conversion between Numbers and Strings


priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie
print("The total in Rs." + str(totalPrice))
OUTPUT

The total in Rs.70


L.O : To convert data from one type
to another.
Type conversion from string to integer or float values.

#Explicit type conversion


icecream = '25'
brownie = '45'
#String concatenation
price = icecream + brownie
print("Total Price Rs." + price)
OUTPUT

Total Price Rs.2545


L.O : To convert data from one
type to another.
Type conversion from string to integer or float values.

#Explicit type conversion - string to integer


icecream = '25'
brownie = '45'
#String concatenation
price = int(icecream)+int(brownie)
print("Total Price Rs." + str(price))
OUTPUT

Total Price Rs.70


L.O
• To input data from the user. READING NUMERIC LITERALS

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

This function is used to evaluate the value of a string. It takes a string as an


argument, evaluate it as Python expression and returns the result.
Syntax
eval(expression)
Example
>>>eval(‘2+3’)
5
L.O
• To input data from the user. Example

>>> marks=eval(input("Enter marks:"))


Enter marks:90.5
>>> marks+2
92.5
L.O
• To input data from the user. POSSIBLE ERRORS WHEN READING NUMERIC VALUES

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

Traceback (most recent call last):


File "<pyshell#9>", line 1, in <module>
age=int(input("How old are you?"))
ValueError: invalid literal for int() with base 10: '20.5'
L.O
• To input data from the user. POSSIBLE ERRORS WHEN READING NUMERIC
VALUES
2) While inputting integer values using float( ) with input( ), make sure that the value being entered
must be float type compatible.

>>> marks=float(input("Enter marks:"))


Enter marks:5.6.7

Traceback (most recent call last):


File "<pyshell#13>", line 1, in <module>
marks=float(input("Enter marks:"))
ValueError: could not convert string to float: '5.6.7'
L.O
• To input data from the user. POSSIBLE ERRORS WHEN READING NUMERIC VALUES

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.

num1=eval(input(“Enter number 1:”))


num2=eval(input(“Enter number 2:”))
num3=eval(input(“Enter number 3:”))
sum = num1 + num2 + num3
print(“Three numbers are :” , num1, num2, num3)
print(“Sum is :” , sum)
L.O Program to obtain no of prefects in 4 houses Jupiter, mars,
To write programs for taking input
Neptune and Saturn in class 11A and find the total no of
from the user and displaying result.
prefects in the class
L.O
To identify different types of errors. Debugging

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.

A=2+(3-5 # parentheses must be in pairs


L.O
To identify different types of errors. Logical Errors

A logical error is a bug in the program that causes it to behave incorrectly. A


logical error produces an undesired output but without abrupt termination of
the execution of the program.

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

A runtime error causes abnormal termination of program while it is executing. Runtime


error is when the statement is correct syntactically, but the interpreter cannot execute it.
Runtime errors do not appear until after the program starts running or executing.

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.

Following figure shows how this changes 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

Look at the following code:


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.
Following figure shows how this changes 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.

You might also like