Python Session
Python Session
Software Development
Game Development
Artificial Intelligence
Advantages
Python is simple to use, offering much more structure and support
for large programs than shell scripts or batch files can offer.
Python allows you to split your program into modules that can
be reused in other Python programs.
The normal mode is the mode where the scripted and finished .py files are
run in the Python interpreter.
Python Keywords
Keywords are the reserved words in Python.
All the keywords except True, False and None are in lowercase and they
must be written as they are. The list of all the keywords is given below .
Python Identifiers
An identifier is a name given to entities like class, functions,
variables, etc. It helps to differentiate one entity from another.
Python Statement
Instructions that a Python interpreter can execute are called statements.
For example, a = 1 is an assignment statement. if statement, for
statement, while statement, etc. are other kinds of statements.
PYTHON DATA TYPES
Every value in Python has a datatype. Since everything is an object in
Python programming, data types are actually classes and variables are
instance (object) of these classes.
Numbers
Integers, floating point numbers and complex numbers fall under Python
numbers category. They are defined as int, float and complex classes in
Python.
We can use the type() function to know which class a variable or a value
belongs to.
PROGRAM
a=5
a = 2.0
a = 1+2j
Complex numbers are written in the form, x + yj, where x is the real
part and y is the imaginary part. Here are some examples.
char = "P"
OUTPUT
Single Line: Welcome to Inspire Solutions
s1='Welcome'
Indexing 0 1 2 3 4 5 6
String – s1 W E L C O M E
-ve Index -7 -6 -5 -4 -3 -2 -1
List
List is an ordered sequence of items. It is one of the most used
datatype in Python and is very flexible. All the items in a list do not
need to be of the same type.
0 1 2 3 4 Positive Indexing
99 98 96 95 100 marks
-5 -4 -3 -2 -1 Negative Indexing
PROGRAM
student= [101, 'RAM', 100.5, 'CSE']
print(student[0])
print(student[1])
print(student[2])
print(student[3])
print(student[-1])
print(student[-2])
print(student[-3])
print(student[-4])
print(student)
OUTPUT
101
RAM
100.5
CSE
CSE
100.5
RAM
101
PROGRAM
student[1] = ‘RAJ’
print(student)
OUTPUT
Tuple
Tuple is an ordered sequence of items same as a list. The only
difference is that tuples are immutable. Tuples once created cannot be
modified.
Tuples are used to write-protect data and are usually faster than lists as
they cannot change dynamically.
PROGRAM
print(student[0])
print(student[1])
print(student[2])
print(student[3])
print(student[-1])
print(student[-2])
print(student[-3])
print(student[-4])
OUTPUT
101
RAM
100.5
CSE
CSE
100.5
RAM
101
student[1]='RAJ'
print(student)
Set
Set is an unordered collection of unique items. Set is defined by
values separated by comma inside braces { }. Items in a set are not
ordered.
set1 = {1, 3, 6, 7, 9}
print(set1)
Since, set are unordered collection, indexing has no meaning. Hence, the
slicing operator [ ] does not work.
Dictionary
Dictionary is an unordered collection of key-value pairs.
In Python, dictionaries are defined within braces { } with each item being
a pair in the form key:value. Key and value can be of any type.
PROGRAM
print(student['name'])
OUTPUT
RAM
Output formatting
Sometimes we would like to format our output to make it look attractive.
This can be done by using the str.format( ) method. This method is
visible to any string object.
x = 5; y = 10
OUTPUT
PROGRAM
x = 5; y = 10
OUTPUT
To allow flexibility, we might want to take the input from the user. In
Python, we have the input() function to allow this. The syntax
for input() is:
input([prompt])
Example
num=input(‘Enter a Number’)
OUTPUT
Check the type of the variable, Do you think the type will be float since
the value given is 10.5?
PROGRAM
num=input('Enter a Number')
print(type(num))
OUTPUT
Enter a Number10.5
<class 'str'>
Output formatting
Sometimes we would like to format our output to make it look attractive.
This can be done by using the str.format( ) method. This method is
visible to any string object.
x = 5; y = 10
OUTPUT
PROGRAM
x = 5; y = 10
OUTPUT
Input Statement
Till now, our programs were static. The value of variables was defined or
hard coded into the source code.
To allow flexibility, we might want to take the input from the user. In
Python, we have the input() function to allow this. The syntax
for input() is:
input([prompt])
Example
num=input(‘Enter a Number’)
OUTPUT
Check the type of the variable, Do you think the type will be float since
the value given is 10.5?
PROGRAM
num=input('Enter a Number')
print(type(num))
OUTPUT
Enter a Number10.5
<class 'str'>
Operators
Operators are special symbols in Python that carry out arithmetic or
logical computation. The value that the operator operates on is called
the operand.
z=x+y
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication, etc.
Operat
Meaning Example
or
x % y
Modulus - remainder of the division of
% (remainder of
left operand by the right
x/y)
Operat Exampl
Meaning
or e
Logical operators
Logical operators are the and, or, not operators.
Operat Examp
Meaning
or le
Assignment operators
Assignment operators are used in Python to assign values to variables.
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
Special operators
Python language offers some special types of operators like the identity
operator and the membership operator . They are described below
with examples.
Membership operators
in and not in are the membership operators. These are used to test
whether the given element is present in the given sequence or not
PROGRAM
marks=[99,98,97,93,88,91]
OUTPUT
True
False
PROGRAM
print('to' in s)
print('is' in s)
print('to' not in s)
print('is' not in s)
OUTPUT
True
False
False
True
Identity operators
is and is not are the identity operators in Python. They are used to check
if two values (or variables) are located on the same part of the memory.
Two variables that are equal does not imply that they are identical.
Operat
Meaning Example
or
Example
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
# Output: False
# Output: True
print(x2 is y2)
# Output: False
print(x3 is y3)
PROGRAM
x = [1,2,3]
y = [1,2,3]
z=x
if (x == y):
print("True")
else:
print("False")
if (x is y):
print("True")
else:
print("False")
if (x is z):
print("True")
else:
print("False")
OUTPUT
True
False
True
Operator Precedence
The combination of values, variables, operators, and function calls is
termed as an expression. The Python interpreter can evaluate a valid
expression.
x = 10 + 2 * 3
x = 36 or 16 ?
The answer is 16 why because in the above operation we have more than
one operations ( i.e + and *) out of which * has the highest priority.
Operator Description
~+- Complement, unary plus and minus (method names for the last
two are +@ and -@)
if test_expression:
statement(s)
if Statement
# If the number is positive, we print an appropriate message
num = 13
if num > 0:
print(num, "is a positive number.")
print("I am out of If Statement")
num = -13
if num < 0:
print(num, "is a Negative number.")
print("I am out of If Statement")
OUTPUT
13 is a positive number.
I am out of If Statement
I am out of If Statement
if...else Statement
Syntax of if...else
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute the
body of if only when the test condition is True.
Example1
num = 13
if num > 0:
else:
OUTPUT
13 is a positive number.
I am out of If Statement
Example 2
if num > 0:
else:
OUTPUT
Enter a Number-12
I am out of If Statement
if...elif...else Statement
Syntax of if...elif...else
if test expression:
Body of if
else:
Body of else
The elif is short for else if. It allows us to check for multiple
expressions.
If the condition for if is False, it checks the condition of the next elif block
and so on.
The if block can have only one else block. But it can have
multiple elif blocks.
Flowchart of if...elif...else
EXAMPLE
if num > 0:
else:
OUTPUT
Enter a Number0
0 is zero
I am out of If Statement
Nested if statements
We can have a if...elif...else statement inside another if...elif...else
statement. This is called nesting in computer programming.
Example
if num > 0:
else:
if(num<0):
else:
OUTPUT
Enter a Number0
0 is zero
I am out of If Statement
Enter a Number 12
12 is a positive number.
I am out of If Statement
I am out of If Statement
LOOPING Statement / Iterative Statement
The for loop in Python is used to iterate over a sequence / iterator
(list, tuple, string) or other iterable objects. Iterating over a sequence is
called traversal.
Here, val is the variable that takes the value of the item inside the
sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of
for loop is separated from the rest of the code using indentation
Example
str="Welcome"
for i in str:
print(i)
OUTPUT
e
l
for i in lst:
print(i)
OUTPUT
raja
9.5
s={3,7,19,12} #Set
for i in s:
print(i)
OUTPUT
19
12
t=(3,7,19,12) #Tuple
for i in t:
print(i)
OUTPUT
7
19
12
di={"rollno":101,"name":"DEV","mark":100} #Dictionary
for i in di:
print(i)
OUTPUT
rollno
name
mark
di={"rollno":101,"name":"DEV","mark":100} #Dictionary
for i in di:
print(di[i])
OUTPUT
101
DEV
100
We can also use a range() function in for loop to iterate over numbers
defined by range().
for i in range(1,11):
print(i)
for i in range(10,101,5):
print(i)
for i in range(100,4,-5):
print(i)
sum=0
for i in range(1,21):
sum+=i
print("Sum is:",sum)
for i in range(1,13):
print("{} x {} = {}".format(num,i,num*i))
break Statement
The break statement is used for premature termination of the current
loop. After abandoning the loop, execution at the next statement is
resumed, just like the traditional break statement in C.
for i in range(10):
if i==5:
break
print(i)
OUTPUT
0
continue Statement
The continue statement continues with the next iteration of the
loop:
for i in range(10):
if i==5:
continue
print(i)
4
6
for i in range(10):
print(i)
else:
OUTPUT
3
4
for i in range(10):
if i==5:
break
print(i)
else:
OUTPUT
num=[23,55,66,22,43]
i=0
while(i<len(num)):
print(num[i])
i+=1
OUTPUT
23
55
66
22
43