008 Features of Python 2024-25
008 Features of Python 2024-25
Keywords
Identifiers(Name)
Literals
Operators
Punctuators
KEYWORDS
Keywords are the reserved words and have special
meaning for python interpreter. Every keyword is
assigned specific work and it can be used only for that
purpose.
A partial list of keywords in Python is
IDENTIFIERS
Are the names given to different parts of program like variables,
objects, classes, functions etc.
Identifier forming rules of Python are :
🞑 Boolean Literals
🞑 Literal Collections
String Literals
It isa collection of character(s) enclosed in a double or
single quotes
Examples of String literals
🞑 “Python”
🞑 “Mogambo”
🞑 „123456‟
🞑 „Hello How are your‟
🞑 „$‟, „4‟,”@@”
In Python both single character or multiple characters
enclosed in quotes such as “kv”, „kv‟,‟*‟,”+” are treated
as same
Non-Graphic (Escape) characters
They are the special characters which cannot be
type directly from keyboard like backspace, tabs,
enter etc. When the characters are typed they
perform some action. These are represented by
escape characters. Escape characters are always
begins from backslash(\) character.
List of Escape characters
Escape Sequence What it does Escape Sequence What it does
\\ Backslash \r Carriage return
\‟ Single quotes \t Horizontal tab
\” Double quotes \uxxxx Hexadecim
al value(16
bit)
\a ASCII bell \Uxxxx Hexadecim
al value(32
bit)
\b Back Space \v vertical tab
\n New line \ooo Octal value
String Size
„\\‟ 1
„abc‟ 3
„\ab‟ 2
“Meera\‟s Toy” 11
“Vicky‟s” 7
You can check these size using len() function of Python. For example
>>>len(„abc‟) and press enter, it will show the size as 3
Size of String
For multiline strings created with triple quotes : while calculating size
the EOL character as the end of line is also counted in the size. For
example, if you have created String Address as:
>>> Address="""Civil lines
Kanpur"""
>>> len(Address)
18
For multiline string created with single/double quotes the EOL is not
counted.
>>> data="ab\
bc\
cd"
>>> len(data)
6
Numeric Literals
The numeric literals in Python can belong to any of
the following numerical types:
1)Integer Literals: it contain at least one digit and must
not contain decimal point. It may contain (+) or (-) sign.
🞑 Typesof Integer Literals:
a) Decimal : 1234, -50, +100
b)Octal : it starts from symbol 0o (zero followed by
letter ‘o’)
For e.g. 0o10 represent decimal 8
Numeric Literals
>>> num = 0o10
>>> print(num)
It will print the value 8
>>> isMarried=True
>>> type(isMarried)
<class 'bool'>
Special Literals None
Python has one special literal, which is None. It indicate absence
of value. In other languages it is knows as NULL. It is also used
to indicate the end of lists in Python.
>>> salary=None
>>> type(salary)
<class 'NoneType'>
Complex Numbers
Complex: Complex number in python is made up of two floating point values,
one each for real and imaginary part. For accessing different parts of
variable (object) x; we will use x.real and x.image. Imaginary part of the
number is represented by “j” instead of “I”, so 1+0j denotes zero imaginary.
part.
Example
>>> x = 1+0j
>>> print x.real,x.imag
1.0 0.0
Example
>>> y = 9-5j
>>> print y.real, y.imag
9.0 -5.0
Conversion from one type to another
Python allows converting value of one data type to another data
type. If it is done by the programmer then it will be known as type
conversion or type casting and if it is done by compiler automatically
then it will be known as implicit type conversion.
Example of Implicit type conversion
>>> x = 100
>>> type(x)
<type 'int'>
>>> y = 12.5
>>> type(y)
<type 'float'>
>>> x=y
>>> type(x)
<type 'float'> # Here x is automatically converted to float
Conversion from one type to another
Explicit type conversion
Toperform explicit type conversion Python provide functions like
int(), float(), str(), bool()
>>> a=50.25
>>> b=int(a)
>>> print b
50
Here 50.25 is converted to int value 50
>>>a=25
>>>y=float(a)
>>>print y
25.0
Simple Input and Output
In python we can take input from user using the built-in function
input().
Syntax
variable = input(<message to display>)
Note: value taken by input() function will always be of String type, so by
default you will not be able to perform any arithmetic operation on variable.
>>> marks=input("Enter your marks ")
Enter your marks 100
>>> type(marks)
<class 'str'>
Hereyoucanseeevenwe are enteringvalue100 butit will be treated as
string and will not allow any arithmetic operation
Simple Input and Output
>>> salary=input("Enter your salary ")
Enter your salary 5000
>>> bonus= salary*20/100
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'
Reading / Input of Numbers
Now we are aware that input() function value will
always be of string type, but what to do if we want
number to be entered. The solution to this problem is
to convert values ofinput() to numeric type usingint()
or float() function.
Possible chances of error while taking
input as numbers
1. Entering float value while converting to int
>>> num1=int(input("Enter marks "))
Enter marks 100.5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '100.5‘
Example 2
>>> percentage=float(input("Enter percentage "))
Enter percentage 100 percent
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: „100 percent'
Program 1
Open a new script file and type the following code:
Operator Purpose
+ Unary plus
- Unary minus
~ Bitwise
complement
Not Logical negation
Types of Operators
Binary Operators: are those operators that require two
operand to operate upon. Following are some Binary
operators:
1. Arithmetic Operators
Operator Action
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
** Exponent
// Floor division
Example
>>> num1=20
>>> num2=7
>>> val = num1 % num2
>>> print(val)
6
>>> val = 2**4
>>> print(val)
16
>>> val = num1 / num2
>>> print(val)
2.857142857142857
>>> val = num1 / / num2
>>> print(val)
2
Bitwise operator
Operator Purpose Action
Bitwise operator works
& Bitwise AND Return 1 if both on the binary value of
inputs are 1 number not on the actual
^ Bitwise XOR Return 1, if value. For example if 5
the number is passed to these
of 1 in input operator it will work on
101 not on 5. Binary of
is in odd
5 is 101, and return the
| Bitwise OR Return 1 if result in decimal not in
any input is binary.
1
Example
Binary of 12 is 1100 and 7 is 0111, so applying &
1100
0111
-------
Guess the output with
0100 Which is equal to decimal value 4
| and ^ ?
Let us see one practical example, To check whether entered number is divisible of 2 (or in
a power of 2 or not) like 2, 4, 8, 16, 32 and so on
Tocheck this, no need of loop, simplyfind the bitwise & ofnand n-1, if the result is0 it
meansit is in power of 2 otherwise not
Identity Operators
Operators Purpose
is Is the Identity same?
is not Is the identity not same?
Relational Operators
Operators Purpose
< Less than
> Greater than
<= Less than or Equal to
>= Greater than or Equal to
== Equal to
!= Not equal to
Logical Operators
Operators Purpose
and Logical AND
or Logical OR
not Logical NOT
Assignment Operators
Operators Purpose
= Assignment
/= Assign quotient
+= Assign sum
-= Assign difference
*= Assign product
**= Assign Exponent
//= Assign Floor division
Membership Operators
Operators Purpose
in Whether variable in
sequence
not in Whether variable not in
sequence
Punctuators
Punctuators are symbols that are used in programming
languages to organize sentence structure, and indicate
the rhythm and emphasisof expressions, statements,
and program structure.
Common punctuators are: „“ # $ @ []{}=:;(),.
Barebones of Python Program
It means basic structure of a Python program
Take a look of following code:
Expressions
Inline Comment
if(C>=100) #checking condition
print(“Value is equals or more than 100”)
ts
else:
print(“Value is less than 100”) Block
Indentation
print(“Welcome to python”)
Theabove statement call print function
When an expression is evaluated a statement is executed
i.e. some action takes place.
a=100
b = b + 20
Comments
Comments are additional information written in a
program which is not executed by interpreter i.e.
ignored by Interpreter. Comment contains information
regarding statements used, program flow, etc.
Comments in Python begins from #
Example
area = length*breadth # calculating area of rectangle
Multiline comment
Example 1 (using #)
# Program name: area of
circle # Date: 20/07/18
#Language : Python
Comments
Multiline comment (using “ “ “) triple quotes
Example
“““
Program name : swapping of two number
Date : 20/07/18
Logic : by using third variable
FFF
Functions
Function is a block of code that has name and can be
reused by specifying its name in the program where
needed. It is created with def keyword.
Example
def drawline():
print(“======================“)
print(“Welcome to
PythonF) drawline()
print(“Designed by Class XIF)
drawline()
Block and Indentation
Group of statement is known as block like function,
conditions or loop etc.
For e.g.
def area():
a = 10
b= 5
c= a * b
Indentation means extra space before writing any
statement. Generally four space together marks the next
indent level.
Variables
Variables are named temporary location used to store
values which can be further used in calculations, printing
result etc. Every variable must have its own Identity, type
and value. Variable in python is created by simply
assigning value of desired type to them.
For e.g
Num = 100
Name=“JamesF
Variables
Note: Python variables are not storage containers like other
programming language. Let usanalyze by example.
In C++, if we declare a variable radius:
radius= 100
[suppose memory addressis41260]
Now we again assign new value to radius
radius= 500
Now the memory address will be still same only value
will change
Variables
Now let ustake example of Python:
radius = 100 [memory address3568]
Now you can see that In python, each time you assign new
value to variable it will not use the same memory address
and new memory will be assigned to variable. In python the
location they refer to changes every time their value
change.(This rule isnot for all types of variables)
Lvalues and Rvalues
Lvalue : expression that comes on the Left hand Side of
Assignment.
Rvalue : expression that comes on the Right hand Side of
Assignment
Examples:
Multiple Assignments
x,y,z = 10,20,30 #Statement 1
z,y,x = x+1,z+10,y-10 #Statement 2
print(x,y,z)
Output will be
10 40 11
Now guess the output of following code fragment
x,y = 7,9
y,z = x-2, x+10
print(x,y,z)
Multiple Assignments
Let us take another example
y, y = 10, 20
print(x)
Python will show an error „x‟ not defined
So to correct the above code:
x=0
print(x) #now it will show no error
Dynamic Typing
In Python, a variable declared as numeric type can be
further used to store string type or another.
Dynamic typing means a variable pointing to a value of
certain type can be made to point to value/object of
different type.
Lets us understand with example
x = 100 # numeric type
print(x)
x=“KVians” # now x point to string type
print(x)
Dynamic Typing
string:KVians
Caution with Dynamic Typing
Always ensure correct operation during dynamic typing.
If types are not used correctly Python may raise an
error.
Take an example
x = 100
y=0
y= x/ 2
print(y)
x='Exam'
y = x / 2 # Error, you cannot divide string
Determining type of variable
Python provides type() function to check the datatype of
variables.
>>> salary=100
>>> type(salary)
<class 'int'>
>>> salary=2000.50
>>> type(salary)
<class 'float'>
>>> name="raka"
>>> type(name)
<class 'str'>
Output through print()
print(“Name is “, name)
Suggest a solution
Just a minute…
Name="James"
Salary=20000
Dept="IT"
print("Name is ",Name,end='@')
print(Dept)
print("Salary is ",Salary)
Just a minute…