Python Programming Basics Explained
Python Programming Basics Explained
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
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
234567.956
Exponential form : 2.34567956 x 105
2.3456756E5
0.0345678
Exponential form: 3.45678 x 10-2
3.45678E-2
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 ‘’’
Error
print(‘he said, ‘hello’’)
print(“India won “1 gold medal””)
Correct
print(“he said, ‘hello’”)
print(‘he said, “hello”’)
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
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
print(“ a\2356”)
Python will consider \2 as escape sequence
Rewrite as
print(“a\\2356”)
Output
A\2356
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
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
Syntax:
variable=value
Eg
x=12
name=”Ajay”
marks=90.2
x=10
x=12
Now, value of x 12 it is no more 10
x=12*2
Now, the value x will be 24
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
- 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
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
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=” “)
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)
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
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)
Example
a=5
b=7
a*=(b**2)
⇒ a=a*(b**2)
RHS
5*(7**2)
5*49
245
Assign the value to LHS
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
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
== Is operator
Check data Checks data as well as
memory address
4.Logical operator
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
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
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'>
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
234+123
357
str(234)+str(123)
234123
(concatenation)
str(234+123)
357 → type is <class ‘str’>
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)
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
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