0% found this document useful (0 votes)
7 views56 pages

Python Programming Basics Explained

Uploaded by

aditipanchal647
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)
7 views56 pages

Python Programming Basics Explained

Uploaded by

aditipanchal647
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

Getting Started with Python

Types of Programming Language:-


1.​Modular Approach
2.​Procedural Approach
a.​Modular
b.​Emphasis on procedure
c.​ No emphasis on data
d.​Repetition of process
3.​Object oriented programming Language
a.​Reusability - reusing the same object
b.​Encapsulation - means object contains component,
method
c.​ Abstraction - means showing relevant components,
hiding background details
d.​Polymorphism - means many forms, one thing can be
presented in many form
e.​Inheritance - means making changes object and creating
a new object
f.​ Modularity - means can make module
Object oriented Programming Language
1.​Class - layout or blueprint
2.​Object - instance occupy memory, space
Example
1.​Animal, Dog
Animal - class
Dog- instance
2.​Car, Maruti Ciaz, Maruti Alto
Car - Class
Maruti Ciaz - instance
Maruti Alto- instance
Why Python????
1.​Easy to use
a.​Object Oriented Language - class, object
b.​High level language
c.​ Friendly approach
2.​Expressive language
a.​Simpler than C++, Java
b.​Compact
c.​ Easy to understand
3.​Interpreter language
a.​Line by line error will occur
b.​Packages available can used
c.​ redistribution
4.​Cross platform language
a.​Execute on windows, linux etc
b.​Portable language
5.​Free and open source
6.​Variety of applications
a.​Web development
b.​scripting language
c.​ GUI
d.​Game development
e.​Database application
f.​ System administrations
g.​Rapid prototyping
Minus of Python
1.​Not a fast language
2.​Lesser libraries than C++, Java
3.​Not strong type binding
4.​Not easily Convertible
Python Fundamentals
Character set - set of valid character which can recognized by the
programming character
●​ Alphabets : upper(A-Z) and lowercase(a-z)
●​ Digit : 0-9
●​ Special characters: like colon(:), comma(,), (),{},[],quotes etc
●​ Whitespace: blank(s), tab space, carriage return, etc
●​ Other characters: unicode characters, ASCII value

Token
Smallest unit in a program is called Token. All the editor give different
colors to different tokens
1.​Keyword - reserved word, the special meaning is understandable
by the Python Interpreter eg if, while, for, or, and etc,True
Viva Question
Q How to find a word's keyword without compiling or interpreting
it?
Ans
The color specified by the editor for keywords
Q what is an editor?
Ans
Editor allows you to move up,down,right,left, write a program,
modify, execute and see the output, save. Different languages a
give different color to the token
2.​Identifier - are fundamental building block of a program, different
parts of the program, can be variable name, function name, class
name, object name,list, dictionary, tuple, sets name etc. Any
word which is not a keyword
Rule for giving identifier:
●​ Allowed Alphabets and digit and arbitrarily long sequence
of character
●​ Combination uppercase and lowercase alphabets, digits,
only special character underscore(_)
●​ other special characters or spaces are not allowed
●​ Name must begin with an alphabet or even underscore,
must not begin with digit, though you have digit name
●​ Python is a case sensitive language and name are
identified by their case eg In Python Age,age,AGE are
different identifiers
Age=10
age=17
These are 2 identifiers, 2 variables
●​ Identifier cannot be a keyword
for=12
Wrong for is an keyword so it cannot be declared as a
variable
For=12
Now it is correct as For is not a keyword
Q identify the correct identifier from the following, if not correct,
justify
a.​MyFile​ ​ correct
b.​My File​ ​ incorrect​ ​ spaces are not allowed
c.​ CHK​​ ​ correct
d.​25Dec​ ​ incorrect​ ​ cannot begin with a digit​
e.​Dec25​ ​ correct
f.​ _DS​ ​ ​ correct
g.​DS_​ ​ ​ correct
h.​for​ ​ ​ incorrect​ ​ it is keyword​
i.​ Break​ ​ correct
j.​ [Link]​ ​ incorrect​ ​ No other special characters are
allowed
k.​ My_File_1_1​ correct
l.​ My_file-12​​ incorrect ​ ​ - is not allowed
m.​Date​​ ​ correct
3.​​ Literal -​ constant values, fixed value that does not
change throughout the program
a.​Numeric literal
b.​String literals
c.​ Boolean literals
d.​Special literal
e.​Other literals
4.​​ Punctuator -symbols used in the program {},(),-,_,[]
5.​Operators - symbols that triggers som computation, action
applied to variables or literals, other objects in an expression
a.​Unary
i.​ Unary +
ii.​ Unary -
iii.​ Bitwise Complement
iv.​ Not logical operator
b.​Binary
i.​ Arithmetic operators
ii.​ Relational
iii.​ Logical
iv.​ Assignment
v.​ Membership
vi.​ identity
vii.​ Bitwise
viii.​ Shift
Literals
-​ Constant or fixed value
-​ Will not change through out the program
-​ Eg 12, “Lion”, etc
12 and “12”
12 is a numeric literal, can do any arithmetic operation, “12” is
string or character literal, can be (+) concatenation,(*)repetition
Numeric literal
1.​Integer literal
An integer value
without commas
Sign (+,-) can be used
●​ Decimal integer literal - integer value , base 10 eg 67
system will take this as (67)10 , displays as it is

print(67)
Output
67
No conversion
●​ Octal integer Literal - integer value that begins with 0o,
base 8, converts to decimal before assign or display

print(0o67)
Convert: 6*8+7*1=55
Output
55
There will be a conversion

●​ Hexa-decimal integer literal - integer value begins with 0x,


base 16, converts to decimal before assign or display

print(0x67)
Convert: 6*16+7*1= 103
Output
103
There will be a conversion
●​ Long integer integer literal - long integer values L or l, no
conversion, base 10
print(56L)
Output
56

2.​Float literal
●​ Floating point value
●​ Decimal point (only 1) eg 3.2.2 is wrong
●​ Sign (+,-) can be used eg -45.5
●​ Decimal point is used you have to give at least 1 digit before
decimal and one after eg .3, 3. is wrong
●​ Commas are not allowed
○​ Floating point literal - number with decimal point 23.56,
67,90, 90,00, 78.09, 0.34
○​ Exponential floating point - e or E is used for exponential
power

Shift decimal point after the first digit


Use 10 raise to positive value if decimal point is shift left, if shift
to right then negative exponent value

234567.956
Exponential form : 2.34567956 x 105
2.3456756E5
0.0345678
Exponential form: 3.45678 x 10-2
3.45678E-2

Q what is the floating point value


1.​3.567E2
356.7
2.​4.789E5
478900.0
478900 - integer literal
478900.0 - floating point literal
3.​5.678912E4 →
56789.12
4.​4.67891E-3 ←
0.00467891
5.​9.3456E-5 ← to left
0.000093456

Comments
-​ No executable statement
-​ To make your program readable, understandable
-​ 2 types
-​ Single line begins #
#print(“hello”)
Command will not executed
print(“hello”) #print statement
Comments appear in Red color in Python IDLE
-​ Multi line comment begin “”” or ‘’’ end “”” or ‘’’

Non numeric Literals


1.​String Literal
-​ Anything in quotation marks is a string
-​ Arithmetic operator used +, *
-​ As it display
-​ Python uses 3 types of quotation marks
-​ Single quotes ‘ ‘ eg ‘a’ ‘apple’, ‘computer science’
-​ Double quotes eg “a”, “apple”, “Computer science”
-​ Triple quotes ‘’’ ‘’’ or “”” “””

Single quotes or double quotes are single line


Quotes within quotes we use different types of quotes
print(“he said,’hello how are you?’”)
Output
he said,’hello how are you?’
print(“Father’s name is Mr Kapoor”)
Output
Father’s name is Mr Kapoor

Error
print(‘he said, ‘hello’’)
print(“India won “1 gold medal””)
Correct
print(“he said, ‘hello’”)
print(‘he said, “hello”’)

Triple quotes (“”” “””) or (‘’’ ‘’’)


-​ Multiline output
-​ print(“”” this is a file
This is a new file
This is my file
This is a Python file”””)

Output
This is a file
This is a new file
This is my file
This is a Python file

-​ Multiline comments
-​ Docstring → will do in class 12
Use of \ in Python
​ To continue a line or command
print(“hello \
friends”)
This is single line
hello friends
print(‘’’hello \
friends’’’)
Even triple quotes are used but use \ it will be printed in one line only
Error
print(“hello
friends”)
WRONG or INVALID

But in Triple quotes \ for same line display or multiple lines if you want
to display in multiple lines

Triple quotes in place of single quotes and double quotes but Vice
versa is not possible

Special string or character - Escape sequence character


-​ Non graphical character
-​ Produce an output
-​ Begin with \ and occupies 1 byte
-​ Characters are:-
-​ \n newline character​​ print new line in the output,
takes to first column of new line
print(“hello\nfriends”)
Output
hello
friends
Same as
print(“””hello
friends”””)
Using escape sequence character in double quotes

print(“My file\nis a \nPython print(“””My file


program”) is a
Python program”””)

Output Output
My file My file
is a is a
Python program Python program
Standard way in all the Only in Python
programming language

-​ \t tab space
4 spaces in between
print(“hello\tfriends”)
Output
hello friends

print(“hello\t\nfriends”)
Output
hello
friends
​ ​ ​ ​ ​ ​ ​
-​ \a beep sound produce
-​ \r carriage return just like \n
-​ \v vertical tab
-​ \b backspace
print(“hello\bfriends”)
Output
hellfriends

print(“hello\b\tfriends”)
hello friends

If not printing any character after \b then you will not see
the effect of \b, in other words \t or \n after \b there will be
no change in output

print(“hello\b\tfriends”) print(“hello\tfriends”)
hello friends hello friends

print(“hello\b\nfriends”) print(“hello\nfriends”)
hello hello
friends friends

Effect of \b is not visible if you use \n or \t after \b


print(‘hello\t\bfriends”)
hello friends
Remember: - no graphical character before and after \b
will not make any difference in the output

-​ \ can be used to suppress the special meaning of any


character
\”
\’
\?
\\
For output as
He says,”hello everyone!”
print(“he says,\”hello everyone!\””)
This technique works in all the programming
languages
print(‘he says,”hello everyone!”’)
This is Python style

print(“ a\2356”)
Python will consider \2 as escape sequence
Rewrite as
print(“a\\2356”)
Output
A\2356

print(“hello\​ ​ means only one line of output


friends”)
Different form
print(“””hello​ ​ means multiple line of output
friends”””)
Though
print(“””hello\​ ​ means same as \ make one line output
friends”””)

2.​Boolean Literals - True or False


3.​Special Literal - None does not means 0

; in Python is used to write 2 more statements in the same line

print(“hello”)
print(“How are you”)

Rewrite as
print(“hello”); print(“how are you”)
Every line is a statement. Statement are 2 types
1.​Simple
2.​Complex or compound statements or block statement

Simple statement means one after another


#this is my first program in Python
print("hello")
print("bye")
print("how are you?"); print("hope you are doing well!!")

Rules for Writing a Python program


1.​It is case sensitive language, keywords in lowercase only
Eg
a=10
Use a not A
A variable name a is different from variable name A
2.​Blank lines - has no significance , give as per your convenience,
2 blanks lines between 2 functions, main program
3.​No symbol to terminate a line
4.​colon(:) to represent a start of a block
5.​Proper indentation is a must
6.​For Indentation use spaces, whitespace(tab)
7.​While printing can print space, whitespace using \t,\v,\n,\r
8.​To write more than one statement in the same line use
semicolon(;)
9.​Comments should be given in a program, First comment in the
“”” (triple quotes) of function or program is called Docstring.
10.​ Save your program giving a meaningful name for YOU
Variable in Python
Named labels, in RAM whose value can be modified during the
execution of the program and it can be processed within the program.
They are not available outside of the program file, can be used in shell
once program is executed

Declare a variable
variablename(identifier)=value
Eg
a=10
s=”Computer”
f=9.8
-​ To declare a numeric variable assign numeric literal
-​ To declare a string variable assign string literal

How memory is assigned to a Python variable


-​ Named label whose value can be changed during the process
-​ Python has no Datatype
-​ What is a Data type?
-​ Type in which variable is declared
-​ What type of data can be stored in a variable
-​ How much memory is allocated to the variable
-​ Range of data that can be stored in a variable
-​ Declare variable by a assigning a value to the variable
-​ Declare a variable
-​ Assign value
-​ But in Python we simply assign the value to a variable and it is
declared, memory is allocated

Syntax:
variable=value
Eg
x=12
name=”Ajay”
marks=90.2

Declare and define - occupy space in memory


Initialize - first value of the variable in the declaration statement
Assign - giving a new value or expression( calculated) to the variable,
for assigning we use assignment operator(=)

x=10
x=12
Now, value of x 12 it is no more 10
x=12*2
Now, the value x will be 24

In Python we assign to declare and define


If you need a variable in Python just assign a value
and it will declared or define

Difference variable other programming languages and Python

Other programming Python


Each variable has a data type, No data type and variable does
there primitive data type not need a datatype
size of variable if fixed Size is not fixed
Range of data is fixed No range - big data
First declare then assign Assign the value to declare
Python declare a variable

Memory in Traditional programming language


In Python

Lvalue- changes with rvalue


Variable = value/ expression/variable
a=10
a=10*5
a=b #b is predefined, a will become label of same memory as b
Value will be allotted to a
← goes from right to left LHS← RHS
Data flows from right to left
Error
A # must give some value
10=a #constant cannot be equal to a variable
In Python
Some data in Python is preloaded

20241 20242 20243 20244 20245 20246


9 10 11 12 13 14

a=10
a will be a label of memory 20242

a=12
Now, a will become label of memory 20244
b=12
Now, 20244 has 2 labels a and b

Advantage of the method:-


1.​Dynamic typing
-​ Variable has no data type
-​ Value assigned to the variable, variable becomes label of
that value
-​ type() it show the type according to value assigned to the
variable
a=10
print(type(a))
<class ‘int’>

-​ When assign another value the label will shift to that value
-​ No change in that memory, a new memory will be given,
id() displays memory address of the variable
a=10
print(id(a))
20242
a=12
print(id(a))
20244

-​ New value, new data type can be given


a=10
print(type(a))
<class ‘int’>
a=”hello”
print(type(a))
<class ‘str’>
Memory address as well type can be changed

Type​​ ​ ​ output
Integer​ ​ ​ <class ‘int’>
Floating​ ​ ​ <class ‘float’>
String/ character​ <class ‘str’>
Boolean​ ​ ​ <class ‘bool’>
List​ ​ ​ ​ <class ‘list’>
Tuple​ ​ ​ <class ‘tuple’>
Dictionary​ ​ <class ‘dict’>

-​ Multiple assignment
a,b=1,2
Here, a will get 1 and b will get 2
a,b,c=1,”hello”,4.3
Here,
a=1, b=”hello”, c=4.3
a=b=c=1
All the variable will be 1, a,b,c are labels of memory
assigned to 1

Easy swapping
Exchanging values of variable
a,b=b,a
a← b, b ← a
-​ Substitution and solve then assign
a=2
b=3
a,b=b*2,a=3
Substitute values of a and b
=> a,b=3*2,2*3
Now solve right side
=> a,b=6,6
Now assign value to a and b
Therefore a=6 , b=6

a,b,c=2,3,4
Here a=2,b=3,c=4
b,c,a=a*3,b*5,c*2
= 6,15,8
Now assign
b=6, c=15, a=8

a,b=2,3
a,b,b,a=a*2,b*3,b*4,a*3
=4,9,12,6
a=4
b=9
b=12 #changes the previous value
a=6
Finally a=6,b=12

x=2
y=x/2
x=”hello”
y=x/2
Error str cannot be divided
a,b=2,3
a,b=a*2,b*3
# a will become 4 b will ne 9
b,a=b*4,a*3
#b=36,a=12
After one statement Python uses the latest value of the
variable

How to display data in Python????


●​ Use print() to print the data
print()
●​ Use literal be numeric or non numeric
print(“this is a string”)
print(literal/variable)
●​ Between 2 literals or 2 variable use comma
print(a,b)
Python will give 4 spaces in between them
●​ If Operator is used then solve and displays the
answer
●​ One print statement prints on one line
●​ To print a blank give
print() → prints a blank line
●​ Use escape sequence characters in Python
Eg
print(“hello\nfriends”)
Output
hello
friends
●​ sep :- new separator between 2 variables,
literals
a=12
b=13
print(a,b,sep=”#”)
Output
12#13

print(a,b)
Output
12 13
But this will change the line
●​ end this will not change the line but it will print
that between 2 lines
print(a,end=”#”) → this will not change the line
print(b)
Output
12#13

print(a)
print(b)
Output
12
13
●​ Remember sep by default \t (4 spaces) and end
by default is \n (new line character)
●​ Both can be used together
a,b,c,d=12,13,14,15
print(a,b,sep=”#”,end=”!”)
print(c,d,sep=”&”,end=”%”)
print(“over”)
print(a,b,sep="#",end="!");print(c,d,sep="&",en
d="%");print("over")
Output
12#13!14&15%over
Remember: end has an advantage if and
only if you write in a file or colab
notebook
●​ print(a=15)
→ assign 15 value to a Python will answer as it
will give an error
●​ print(“a,b,sep=’#’”)
a,b,sep=’#’
●​ print(a,b) print(“a,b”)
12 13 a,b
●​ Python read inside quotes except for escape
sequence
●​ If you give an expression(equation ) solve then
displays the answer
print(a+b)
Output
25
print(3.14*r*r)
Solves and give answer
r=2
print(“area=”,3.14*r*r)
area=12.54
print(“area=”,3.14*r*r,” sq m”)
area=12.54 sq m
print(“area=”,3.14*r**2,”sq m”)
area= 12.54 sq m
print(“area=”,3.14*r**2,”sq m”,sep=” “)

How to accept the data???


●​ Function - input()
●​ Can be give
input() → empty ()
input(“message”)
Eg
input(“enter data ”)
Enter data = → can input data here
print(“enter data”)
input()
Enter data
= → input here

print(“enter data”, end=” “)


input()
Enter data =

●​ Return data in string or text form


●​ Convert the data into the type you want
Eg
For integer data use int()
variable=int(input(“enter data:”))
Eg
a=int(input(“enter the value of a: “))
int() → for integer data
float() → for floating point values
str() → for string
●​ Without conversion then data will always be string
●​ Convert eval() → data converted as per the value

a=int(input(“Enter data:”)) a=eval(input(“enter data:”))

This will accept only integer This will take any type of data
data
Separate function for different One function for all the data
data types type
int(), float(), str(),
Restrict user to input the User to input any type of data
correct form of data

Operators in Python
1.​Unary operators
a.​One operand
2.​Binary operators
a.​Two operands
b.​Types
i.​ Arithmetic operators(+,-,*,/,//,**,%)
Q Write a program in Python to add the number 10,15 and display
the answer
Steps for finding the solution
1.​How many variables are required to execute the program?
2.​How these variables will get value
3.​Input ???
4.​output???
Algorithm:
Step 1: start
Step 2: let a=10
Step 3: let b=15
Step 4: let sum=a+b
Step 5: print(sum)
Step 6: stop

a=10
b=15
sum=a+b
print("sum=",sum)

Q Write a program in Python to accept 2 variables from the user


and find their sum.
Solution:
1 input - 2 variable
2 find sum by adding them
3. Find sum by adding them
Algorithms
Step 1: start
Step 2: input a
Step 3: input b
Step 4: sum=a+b
Step 5: print(sum)
Step 6:stop

a=int(input("enter the 1st number:"))


b=int(input("enter the 2nd number:"))
sum=a+b
print("sum=",sum)
Q what is the difference between
print(“sum”) and print(sum)
Ans

print(“sum”) print(sum)
“Sum” is a string literal so will Python will consider sum as a
be printed as it is variable and display the data in
sum variable( displays rvalue
of the variable)
You can give anything in This has to be an identifiers
quotes, alphabets, digits or
any special character
No need to declare Declare or assign the value
In Python sum,Sum,SUM are 3 different identifiers
sum=a+b
print(Sum)
It is an Error

Q Write a program in Python to accept 3 numbers, find their sum


and product.
a=int(input("Enter the 1st number:"))
b=int(input("Enter the 2nd number:"))
c=int(input("Enter the 3rd number:"))
sum=a+b+c
product=a*b*c
print("Sum of ",a,",",b,",",c,"=",sum)
print("product=",product)

print("Sum of ",a,",",b,",",c,"=",sum)
Other ways of writing this message
●​ print(a,”+”,b,”+”,c,”=”,sum)
●​ print(“SUM=”,sum)
●​ print(“Sum=”,a+b+c)
●​ print(“the Sum of “,a,b,c,” is “,sum)
●​ Message must : -sum of the 3 number, message
that indicates that it is sum
Q Why I must give a message before input or
printing output ?
Ans
-​For programmer’s reference
-​To make understandable for user
-​Eg
-​print(sum) --> 25
-​print(“sum=”,sum) → sum=25
-​Meaningful messages
-​Message should be too long or too short,crisp
message.
Operators in Python
1.​Unary → one operator and one operand
a.​Unary +
x=7
print(+x)
7
b.​Unary -
Before positive → negative, before negative → positive, no
change in the value of x until using assignment operator is
used
x=-7
print(-x)
7
x=7
print(-x)
-7
print(x)
7

But,
x=7

x=-x
Now value of x will change to -7
c.​ Logical not
2.​Binary operator → one operator, 2 operands
a.​Arithmetic operator
i.​ Add ​​ ​ ​ +
ii.​ Subtract​ ​ ​ -
iii.​ Multiply​ ​ ​ *
iv.​ Divide​ ​ ​ / (answer in floating point)
v.​ Floor division​ ​ //(answer is integer)
vi.​ remainder(Modulus)​ %(remainder)
vii.​ Power​ ​ ​ **​ (raise to power)
divide , floor division, modulus
Example
​ a=11
​ b=2
​ print(a/b)
​ Answer: 5.5
​ print(a//b)
​ 5 (before decimal point)
​ print(a%b)

Floor integer → gives lower integer of a decimal number


9.1 → floor is 9.0
9.9 → floor is 9.0
b.​Assignment operator (=) to assign the value, store the
data or value in RHS to variable in LHS, declare a
variable
i.​ a=2
ii.​ a=b=3
iii.​ a=7*4
iv.​ Error print(a=2)
v.​ Error a=2=b
c.​ Augmented assignment operator​
i.​ += when a=a+10 then you can write a+=10
ii.​ -=
iii.​ *=
iv.​ /=
v.​ //=
vi.​ %=
vii.​ **=
​ Calculate then store in the same variable
​ a=10
​ a+=10
​ ⇒ a=a+10
​ RHS​
​ → substituting value of a in RHS
​ ⇒ 10+10
​ ⇒ 20
​ Assign to the variable in LHS
​ ⇒ a=20

​ Example
​ a=5
​ b=7
​ a*=(b**2)
​ ⇒ a=a*(b**2)
​ RHS
​ ​ 5*(7**2)
​ ​ 5*49
​ ​ 245
​ Assign the value to LHS

​ Statement​​ Equivalent statement in Augmented Assignment


​ a=a+1​ ​ a+=1
​ a=a*3​ ​ a*=3
​ b=b/2​ ​ b/=2
​ c=c-10​ ​ c-=10
​ a=a//10​ ​ a//=10
​ a=a%2​ ​ a%=2
​ a=a**3​ ​ a**=3

​ Note: Augmented assignment can be used if and only you have
same variable in LHS and RHS
​ a=b*2
​ a=(c*d)/2
​ Here you augmented assignment cannot be used

d.​ Relation operator - tells relationship between two


operands, two values or one operand and one value, it is
also called comparison operator, it returns True, False
i.​ > greater than
ii.​ >= greater than or equal to
iii.​ < less than
iv.​ <= less than or equal to
v.​ == exactly equal or equal to
vi.​ != not equal to
​ ​ Example
​ ​ a=10
​ ​ print(a==10)
​ ​ Output
​ ​ True

​ ​ Comparing numeric Values


1.​ 4 with 4.0 Python will treat as same, 4.0 → 4
2.​ Conversion function or typecasting is used to convert then
answer True
3.​ String comparison
3.1.​ You can compare 2 strings
3.2.​ ASCII of lower case is more upper case
3.3.​ Strings said to equal if both value in same case
3.4.​ Python allot memory to space “age “ (with a space) is
different “age” (without a space)
3.5.​ ASCII of A is 65, a is 97 and 0 is 48
4.​ Tuple, list are compared number of elements and the data inside
them
5.​ Boolean True is equal to 1 and Boolean false is 0
6.​ If your Arithmetic operators and relational operator in an
expression then solve arithmetic operator and then
compares the answer
7.​ If brackets are used solve as per the bracket
Example
print(3*4 >5)
Step 1: 3*4=12
Step 2: 12>5 comparison

print(3*(4>5))
Step 1: compare 4>5 → False → 0
Step 2: 3*0
8.​ Arithmetic Expression has relational operators in bracket then
Python will 1 substitute True and 0 in place of False
print(3*4 > 5) print(3*(4>5))
Arithmetic Bracket→ relational
relational Further arithmetic answer of
relational operator will convert
into a number 0 (False) and 1
(True)
print(3*4 >= 6*2) print(3 *(4>=6) *2)
As there is no bracket Solve the bracket first
Arithmetic Because of bracket
Relational relational then arithematic

9.​ Bracket for arithmetic then again arithmetic then relational


print(3*4 > 5*2)
Is same as
print((3*4) > (5*2))

10.​ Floating value expression are compared then you will get False
print(0.1+0.2 == 0.3)
Output
False
x=0.1+0.2
print(x==0.3)
Output
False
When Python solves a floating point expression is solved
0.3 → 0.300000000004
11.​ Avoid relational operators in Floating point in Python
12.​ Value =3 is not same as Value==3 as first is assignment
operator, and second is comparison operator
3.​Identity operator - memory of 2 variables is same, data is
obviously same return True, otherwise return False
is​ True ​​ memory is same ​ id() returns same value
not is​​ True​ memory is different​ id() returns different values

a=1
b=1
print(id(a),id(b))
print (a is b)
True

a=10
b=5*2
print(a is b)
True

How == is different from is operator

== Is operator
Check data Checks data as well as
memory address

String is accepted from the user get new memory


s1="abc"
s2=input("Enter string:")
print(s1==s2) ​ # True
print(s1 is s2)​ #False

2 complex numbers are not given same memory


a=2+3j
b=2+3j
print(a==b)​ ​ #True
print(a is b)​​ #False

Float variables are different memory address


x=7.5
y=7.5
print(x is y) #False

4.​Logical operator

Truth Value testing


There are some values in Python which when used in a logical
expression return False remaining returns True
The values that return False are
●​ None
●​ False
●​ Zero (0) , 0,0.0 ,0.000
●​ Blank quotes “”, ‘’ no spaces in between open quotes and
close quotes
●​ Empty bracket, parentheses sequence (), [] ; Mapping {}
​ Positive or negative numbers return True

​ And operator
-​ Placed between 2 expression
-​ Returns True if both the expressions True
-​ Otherwise returns False
Expression1 and Expression2
True True True
True False False
False False True
False False False
Example
a=1
b=2
c=3
print(a<b and a<c)
True
print(a<b and b>c)
False
print(8>5 and 2<5)
True
print(5>8 and 2<5)
False

If we take integer or string on either of side


Return 0 if zero is on any side of and
expression answer justification
0 and 0 0 O return false and 0
return false
0 and 8 0 O and non zero then
return 0
5 and 8 8 Right hand number is
returned
8 and 5 5
5 and 0.0 0.0 First True, second
False return False
value
“” and “” “” Return blank
“Hello” and “” blank Return False
“A” and “B” B Returns value on the
right side

When Both the side True and operator return the value on right
hand side of and
1 and 5​ → both are True​ →5
“A” and “a”​ ​ → Both are True​ →a
When false on any side return False value
8 and 0​ → 0
0 and 8​ → 0

​ OR operator
-​ Placed between 2 expression
-​ Returns True at least one of the expressions is True
-​ Otherwise returns False
Expression1 or Expression2
True True True
True True False
False True True
False False False
Example
a=1
b=2
c=3
print(a<b or a<c)
True
print(a<b or b>c)
True
print(8>5 or 2<5)
True
print(5>8 or 2<5)
True
print(5>8 or 2>5)
False

If we take integer or string on either of side


Return 0 if zero is on any side of and
expression answer justification
0 or 0 0 O return false and 0
return false
0 or 8 8 Returns non zero
value
5 or 8 5 Left hand number is
returned
8 or 5 8
5 or 0.0 5 Returns non zero
value
“” or “” “” Return blank
“Hello” or “” hello Return non blank
“A” or “B” A Returns value on the
left side

When Both the side True and operator return the value on left
hand side of or
1 and 5​ → both are True​ →1
“A” and “a”​ ​ → Both are True​ →A
When false on any side return True value
8 and 0​ →8
0 and 8​ →8

Not operator
-​ Works on single operand
-​ Complement the expression

not expression
False True
True False

Example
a == 10​ → True when the value of a is 10
not a== 10 → True when the value a is not 10
or
a!=10
not (a>b and a>c)
(a>b and a>c) → a is greater than b a well as c
not (a>b and a>c) → when a is either smaller than b or c or both
or equal

Check
1.​a in range 10 - 50
a>=10 and a<=50
2.​a either less than 10 or greater than 50
a<10 or a>50
not(a>10 and a<50)
3.​The value a is “pen” and “pencil” [one variable can have
only one value and to check values on the same variable
use or]
a==”pen” or a==”pencil”
4.​The value of a is other than “pen” and “pencil”
a!=”pen” and a!=”pencil”
not(a==”pen” or a==”pencil”)
5.​The value of a is not more 50
a<=50
not a>50

Not on integers or Strings​

not 5 False 5 is a non zero value


not 0 True 0 is False and not False is
True
not -4 False -4 is a non zero value
not (5>2) False (5>2) is true, not True is
False
not(5>9) True (5>9) is False, not False is
True
not “” True “” means False
not “hello” False “Hello” means True

5.​Chained comparison operator


10<a<30
Means
a>10 and a<30
30>a >5
Means
a> 5 and a<30
11<13>12
11< 13 and 13>12
Check a is between 10-50
10<=a<-50
6.​Bitwise operators
7.​In operator - to check a list of value
“A” in “ABCDEFGHIJ”
True
“put” in “Computer Science”
True
​ “Put” in “Computer Science”
​ False

String Only 2 Arithmetic operator can work


1.​+ called Concatenation operator fo string for concatenating 2
strings, both side of + should be a string
print(“A”+”B”)
AB

print(“A”+2)
Error
print(2+”A”)
Error
2.​* called repetition operator for string for repetition - repeats a
string, one side should be a number, and the other should be a
string
print(“abc”*2)
abcabc
print(2*”abc”)
abcabc

print(“a”*”b”)
Error
NO OTHER ARITHMETIC OPERATOR WORKS ON A STRING

Conversion in Python
1.​Implicit conversion or Coercion
-​ Converts automatically
-​ Type promotion int→ float

a=7/2
7 → integer
2 → integer
7/2 is 3.5 → a is converted to float
a=7
a/=2
a → <class ‘int’>
7/2 → <class ‘float’>

Example
a=7
print(type(a))
a/=2
print(a,type(a))

Output
<class 'int'>
3.5 <class 'float'>

When this conversion is applied:


-​ One variable or data in the expression is floating point
-​ One variable or data is complex
-​ All are integer but the answer is floating point (divide)
​ (a+b)/c
​ Where a,b,c are integer
​ a+b → integer
​ But (a+b)/c → floating point
​ Final answer will be in floating point
2.​Explicit conversion is also called type casting, when you tell the
python to convert, programmer is changing the type
type(expression)
a=7
a=int(7/2)
c=7/2
print(c,type(c))
b=int(7/2)
print(b,type(b))

Output
3.5 <class 'float'>
3 <class 'int'>

a=float(3)
a → will be assigned 3.0, type is <class ‘float’>
Function for type casting

int() To convert to integer int(7/2)


3
float() To convert to floating point float(3)
3.0
complex() To convert to complex number complex(7,2)
7+2j
complex(7)
7+0j
complex(0,7)
0+7j
str() To convert to string str(234)
“234”

bool() To convert to Boolean bool(0)


False
Returns True in non zero and bool(1)
False in zero True
bool(‘’)
False
bool(“a”)
True

234+123
357
str(234)+str(123)
234123
(concatenation)

str(234+123)
357 → type is <class ‘str’>

-- list(), tuple(), dict() → later

Built-in Modules
-​ No extra file required in the program
-​ Python interpreter has them
-​ print(), input(), int(), float(), len(), range() etc….
-​ Use them
Standard Library module
-​ Created and ready to use
-​ First import library → use the module inside them
-​ Copy of that library is added in your program
-​ advantage→ reusability
How to import these modules in your program
1.​import library
Import entire library in the Python program
To call a module
[Link]
Eg
import math → import all the modules of the library
To user sqrt() → square root
[Link](25)
5
2.​from library import module(s)
Only those module or modules will be imported in the program
Can be called directly ,
No need to mention the library
from math import sqrt()
sqrt(25)

from math import sqrt(), pow()


3.​import library as name
import math as M
Instead of math you can write M
Import the entire library
[Link](25)
4.​from library import *
●​ Here * means all the modules
●​ As from is used, call the modules directly

import math from math import math as from math


import M import *
module(s)
All the modules Only sqrt() All the modules All the modules
will be imported function will be of math library of math library
or included imported or are included are included
included in the
program
Call or invoke Call or invoked To call or To call or
module or module directly invoke Alias invoke module
function, use by its name, no can be used in directly, no
the name of the need give place of library need name of
library before library name name the library
module name

[Link]() module() [Link]() module()

Modules of Math Library


A decimal point number lies between 2 integer
2.1, 2.5,2.9 lies between 2.0 and 3.0

1.​ceil(number) - return upper integer of a decimal point number


2.​floor(number) - return lower integer of a decimal point number
3.​sqrt(number) - return square root of a number
4.​pow(number,power) - return numberpower
print(pow(number,0.5)) → same as sqrt(number)
pow(number,½) → square root of number
pow(number, ⅓ ) → cube root
Power can a decimal point or a negative number
5.​abs() - Returns absolute value
a=[Link](-4) = 4
a=[Link](4) =4
6.​fabs() - absolute value for floating point numbers
A=[Link](-4.5) = 4.5
7.​exp() - Returns natural logarithm e raised to power argument
A=e^2n → e raise to power 2n → a=[Link](2*n)
2n→ 2*n
ab→ a*b
8.​log()
9.​log10()
10.​ sin()
11.​ cos()
12.​ tan() - number must be in radians
a= cos(x)/tan(x)+x
In Python
a=[Link](x)/[Link](x)+x

13.​ degrees() - convert angle x from radians to degree


14.​ radians() - convert angle x from degrees to radians
15.​ pi - [Link]
16.​ e - math.e mathematical constant e

Q convert the following expression to Python expression


1.​Roots of Quadratic equation
x=(-b±√(b^2-4ac))/2a
x= (-b+[Link](b**2-(4*a*c))/(2*a)
Because divide by 2 then Multiply by a
b**2
[Link](b,2)
y= (-[Link](b**2-(4*a*c))/(2*a)
2.​2-ye^2y+4y
A=y*[Link](2*y)+4*y

3.​P/(r+s)^4

A=P/(r+s)**4
A=P/[Link]((r+s),4)
4.​|e^2-x|

W=[Link](math. exp(2)-x)
5.​Area=π x r x r
Area=[Link]*r*r
Area=3.14*r*r
Area=[Link]*[Link](r,2)
Area=3.14*r**2

Random
-​ Generates random number
-​ import random
1.​random() - random number between 0 to 1
0<N<1.0
Random number less 100
A= [Link]()*100

2.​randint(start,stop) - integer
start<=n<=stop
Including start, stop
A=[Link](4,20)
Any number between 4 and 20, including 4 and 20
3.​randrange(start,stop,step)
Start to stop-1
A=[Link](4,20)
Random numbers 4 to 19
A=random randrange(40)
Stop value is 40
Start value will be 0
Number between 0 to 39

A=[Link](4,40,2)
[4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38]
Random number from 4 to 39, gap of 2, all even number
36
A=[Link](1,15,3)
[1,4,7,10,13]
Any number from this list

Statistic module
1.​Mean
2.​Mode
3.​Median
Pass a list of value to module and returns mean,median and mode

Debugging and error


Bug- error in a program
Debugging is process to locate the error, find cause then remove the
error as per requirement of the code.

Types of Error:
1.​Compile time error - Error occurs when we compile the program,
errors which are identified by compiler/ interpreter
a.​Syntax error - syntax is rule of writing statement,
grammatical error
print x
Syntax error because () required after print
if a<b
Syntax error because put colon(:) after conditional
expression

b.​Semantic error- error which is because of a meaningless


less statement, rules are broken
x+y=z

Computer flow of calculation is always Right to Left,


variable to get value in left and expression to give the
value on right

Guitar plays Sita (sentence with no meaning)

z=x+y but x and y are not define or declared


Then Syntax error

x+y=z where x and y already defined then it is semantic


error
c.​ Data type error- conversion from one data type to another
is not possible
s=”hello”
s/=2
2.​Runtime error - error that occurs at the time of execution,
program will stop or terminates abnormally, halts the execution of
program
​ Eg
​ a=5/0
​ Runtime error
​ ZeroDivisionError
3.​Logical Error - programmer’s mistake, not getting expected
answer
Eg
a=10
b=20
c=a+b
print(“product of 10 and 20”,c)
Output:
Product of 10 and 20​ 30
Error user expects that 10x20 whereas your program is 10+20

Identify the type of error


1.​a=2/0​ ​ ​ runtime error
2.​print a*2​ ​ ​ Syntax error
3.​Print(a*2)​ ​ ​ Syntax error
4.​x+y=z​ ​ ​ Semantic Error

You might also like