Introduction to Python
Features of Python :
Structure of a Python program :
Components of a basic Python program :
⮚Comments
⮚Statements
⮚Expressions
⮚Function
⮚Blocks
Variables & Data Types :
Complex
Tuples
Dynamic Typing Feature :
X = 20
print (x)
X = “Computer Science”
print (x)
X = 3.256
print (x)
Output:
20
Computer Science
3.256
Keywords :
Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Python Arithmetic Operators
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Python Assignment Operators
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
Python Relational/Comparison Operators
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal x >= y
to
<= Less than or equal to x <= y
Python Logical Operators
Operator Description Example
and Returns True if both x < 5 and x < 10
statements are true
or Returns True if one of the x < 5 or x < 4
statements is true
not Reverse the result, not(x < 5 and x < 10)
returns False if the result
is true
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Operator Description Example
is Returns True if both x is y
variables are the same
object
is not Returns True if both x is not y
variables are not the same
object
Python Membership Operators
Membership operators are used to test if a sequence is presented in an
object:
Operator Description Example
in Returns True if x in y
a sequence
with the
specified value
is present in
the object
not in Returns True if x not in y
a sequence
with the
specified value
is not present
in the object
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
~ NOT Inverts all the bits
Python’s Built-in Functions :
Input Function :
Print Function :
>>> x = “Hello”
>>> y = “Python”
>>> print (x,y)
Hello Python
>>> print ( ) # displays a blank line
>>>
Flow of Execution :
⮚ Sequential Statements
⮚Selection / Conditional Statements
⮚Iteration / Looping Constructs
• The list() function
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
We use the list function to convert the range
object into a list object.
Calling it with two arguments creates a sequence
of numbers from the first to the second.
>>> list(range(2,7))
[2, 3, 4, 5, 6]
Iterating on lists or similar constructs
• You aren’t bound to use the range() function, though. You can use
the loop to iterate on a list or a similar construct.
>>> for a in [1,2,3]:
print(a)
1
2
3
>>> for i in {2,3,3,4}:
print(i)
2
3
4
You can also iterate on a string.
>>> for i in 'wisdom':
print(i)
w
i
s
d
o
m
The else statement for for-loop
Like a while loop, a for-loop may also have an else statement after it. When
the loop is exhausted, the block under the else statement executes.
>>> for i in range(10):
print(i)
else:
print("Reached else")
0
1
2
3
4
5
6
7
8
9
Reached else
Like in the while loop, it doesn’t execute if you break out of the
loop or if an exception is raised.
>>> for i in range(10):
print(i)
if(i==7): break
else: print("Reached else")
0
1
2
3
4
5
6
7
Nested for Loops Python
You can also nest a loop inside another. You can put a for loop
inside a while, or a while inside a for, or a for inside a for, or a
while inside a while. Or you can put a loop inside a loop inside a
loop. You can go as far as you want.
>>> for i in range(1,6):
for j in range(i):
print("*",end=' ')
print()
*
**
***
****
*****
In python, string is a sequence of characters
enclosed within quotes.
How to access characters in a string?
• We can access individual characters using indexing and a range of
characters using slicing. Index starts from 0.
• Python allows negative indexing for its sequences.
String Operations:
String Membership Test
We can test if a substring exists within a string or not,
using the keyword in.
>>> 'a' in 'program’
True
>>> 'at' not in 'battle’
False
String Slicing:
Built in string methods:
Method Description
capitalize() Converts the first character to upper
case
casefold() Converts string into lower case
lower() Converts a string into lower case
upper() Converts a string into upper case
islower() Returns True if all characters in the
string are lower case
isupper() Returns True if all characters in the
string are upper case
Method Description
isalnum() Returns True if all characters in the string
are alphanumeric
isalpha() Returns True if all characters in the string
are in the alphabet
isdigit() Returns True if all characters in the string
are digits
lstrip() Returns a left trim version of the string
rstrip() Returns a right trim version of the string
find() Searches the string for a specified value
and returns the position of where it was
found
isspace() Returns True if all characters in the
string are whitespaces
istitle() Returns True if the string follows the
rules of a title
swapcase() Swaps cases, lower case becomes
upper case and vice versa
Programs :
• 1. Write a program that reads a line and prints its statistics like :
Number of uppercase characters
Number of lowercase characters
Number of alphabates
Number of digits
2.
• Python Lists
• The list is a most versatile datatype available in Python which can be
written as a list of comma-separated values (items) between square
brackets. Important thing about a list is that items in a list need not
be of the same type.
• Creating a list is as simple as putting different comma-separated
values between square brackets. For example −
• list1 = [ ]
• list2 = [1, 2, 3, 4, 5 ]
• list3 = ["a", "b", "c", "d"]
• list4=['physics', 'chemistry', 1997, 2000];
• list5 = ['physics', 'chemistry', 'maths','computer science']
List Operations :
Creating a list
Creating Empty list
Creating list from existing sequences
Creating list from keyboard input
Traversing a list
Joining lists
Repeating/Replicating lists
Slicing lists
List Manipulation
Append
Update
Delete
Creating Copy of a list
List Functions/Methods.....
1. List.index(<item>)
2. List.append(<item>)
3. List.extend(<list>)
4. List.insert(<pos>,<item>)
5. List.pop(<index>).....index is optional
6. List.remove(<value>)
7. List.clear()
8. List.count(<item>)
9. List.reverse()
10. List.sort()
11. List.copy()
Adding elements in List :
1. append( ) 2. insert( ) 3. extend()
>>> nums=[1,2,3]
>>>
>>> nums=[1,2,3] >>> nums=[1,2,3]
nums.extend([[4,5],(7,8),9])
>>> nums.append(4) >>> >>> nums
---> [1,2,3,4] nums.insert(2,4) Output:
>>>nums.append([5,6]) >>> nums [1, 2, 3, [4, 5], (7, 8), 9]
----> [1, 2, 3, 4, [5, 6]] Output: >>>L1=[10,20,30]
>>>nums.append((7,8)) >>> L1.extend(nums)
>>>nums Output:
[1, 2, 4, 3]
Output: [10,20,30,1, 2, 3, [4, 5], (7, 8),
9]
[1, 2, 3, 4, [5, 6], (7, 8)]
Deleting elements in List :
4. remove( ) 5. pop( ) 6. clear( )
>>> >>> >>>
nums=[1,2,3,2,4,5,3,6,7 nums=[1,2,3,2,4,5,8] nums=[1,2,3,2,4,5,
,8] >>> nums.pop() 8]
>>> nums.remove(2) 8 >>> nums.clear()
>>> nums >>> nums >>> nums
Output: [1,2,3,2,4,5] []
>>>nums.pop(3)
[1, 3, 2, 4, 5, 3, 6, 7, 8] 2
7. index( ) 8. count( ) 9. sort( )
>>> >>> >>>
nums=[1,2,3,4,5,8] nums=[1,2,3,4,5,3, nums=[10,2,3,14,5,3,8]
>>> 8] >>> nums.sort()
nums.index(3) >>> >>>num
2 nums.count(3) [2,3,3,8,10,14]
2
10. reverse( ) 11. copy( ) 12. len( )
>>> >>> nums=[1,2,3,4,5] >>>
nums=[10,2,3,14,5,3,8] >>> num2=nums num=[1,2,3,4]
>>> nums.reverse() >>>num2 >>> num.len()
[1,2,3,4,5] 4
>>>num
>>>num3=nums[:]
[8,3,5,14,3,2,10]
>>>num4=list(num2)
>>>num5=nums.copy()
List Vs Strings :
Similarities
Differences
A tuple is an immutable sequence of Python
objects.
Tuples are sequences, just like lists.
The differences between tuples and lists are,
the tuples cannot be changed unlike lists and
tuples use parentheses, whereas lists use square
brackets.
tting different comma-separat
Creating Tuples
• tup1 = ()
• tup2 = (1, 2, 3, 4, 5 )
• tup3 = ("a", "b", "c", "d")
• tup4=('physics', 'chemistry', 1997, 2000)
• tup5 = ('physics', 'chemistry', 'maths','computer science')
Creating a tuple
Creating Empty tuple
Creating SIngle element tuple
Creating tuple from existing sequences
Creating tuple from keyboard input
Tuple Operations :
Traversing a Tuple
Joining Tuples
Repeating/Replicating lists
Slicing Tuples
Tuples packing & unpacking
Tuple functions :
List Vs Tuples :
Similarities
Differences
• 1. Program to find the sum of 'n' natural numbers
• (for loop implementation)
• 2. Program to calculate bill amount inclusive of GST.
• (total =total+(item_price + (item_price*gst)/100)
• 3. Program to find maximum, minimum and mean value
• from the list (user input).
• 4. Program to find maximum length substring in an inputted string.