Python
Python
programmin
g
Contents
• Introduction
• Syntax and Comments
• Keywords
• Data Types
• Functions and Recursion
• Arrays and Strings
What is
Python?
• Python is a high-level programming
language that uses instructions to teach the
computer how to perform a task. It was
developed by Guido Van Rossum and was
released in 1991.
• A language which is closer to human
language (like English).
• Python provides an easy approach to object-
oriented programming.
Why Python?
• Simple
• Easy to learn
• Free & Open Source
• High-Level
• Platform Independent
• Interpreted
• Dynamically Typed
Keywords
lambda
The lambda keyword is used to create a small
anonymous function in Python. It can take multiple
arguments but accepts only a single expression.
a=lambda x,y:x+y
a(10,11)
Syntax and Indentation
• Indentation refers to the spaces and tabs used at
the beginning of the statement.
• The statements with same indentation belong to
the same group called a suite.
• Thus, it is used to create or represent a block of
code.
• print() function is used to write output on the
screen.
Example:
print(“SRIT”)
Comments
• Single Line comments
Comments starts with a ‘#’
• Multiline Comments
"""
This is a comment
written in
more than just one line
"""
Variables
• A variable name must start with a letter or the
underscore character.
• A variable name cannot start with a number.
• A variable name can only contain alpha-numeric
characters(A-Z, a-z, 0-9) and underscores( _ ).
• A variable name cannot contain whitespace and
signs such as +, -, etc.
• Variable names are case-sensitive.
• Python keywords cannot be used as a variable
name.
Storing values in
variables
• The variable name, value and assignment
operator (=) are the three things required to
store values in a variable.
Ex: myVar=3929
• Here, myVar is the variable name and it is
assigned a value of 3929 using assignment
operator (=).
print()
• Simple
print(“Hello”)
• f-strings
print(f’{i} smallest 3 digit number’)
• %-formatting strings
i=100.34566
print(“ %.2f smallest 3 digit number ”%(i))
print()
• format()
stock_ticker = 'AAPL'
price = 226.41
print('We are interested in {x} which is currently
trading at {y}'.format(x=stock_ticker, y=price))
Example
Change the values "banana" and "cherry" with the
values "blackcurrant" and "watermelon":
thislist = ["apple", "banana", "cherry", "orange", "kiwi",
"mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
Note: The length of the list will change when the number
of items inserted does not match the number of items
replaced.
If you insert less items than you replace, the new items
will be inserted where you specifi ed, and the remaining
items will move accordingly:
Example
Change the second and third value by replacing it with
one value:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
Insert Items
• Append Items
To add an item to the end of the list, use the append()
method:
Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Python - Add List Items
• Extend List
To append elements from another list to the current list, use
the extend() method.
Example
Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
• The extend() method does not have to append lists, you
can add any iterable object (tuples, sets, dictionaries
Tuple
Just like a list, a tuple is also an ordered collection of
Python objects. The only diff erence between a tuple and a
list is that tuples are immutable i.e. tuples cannot be
modifi ed after it is created. It is represented by a tuple
class.
Example
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
Negative Indexing
Example
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Range of Indexes
Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
Add Items
Example
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
Add Items
Example
Convert the tuple into a list, remove "apple", and convert
it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
you can delete the tuple completely:
Example
The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple)
#this will raise an error because the tuple no longer exists
Unpacking a Tuple
Example
Assign the rest of the values as a list called "red":
fruits = ("apple", "banana", "cherry", "strawberry",
"raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
Set
Set is an unordered collection of data types that is
iterable, mutable, and has no duplicate elements.
A set is represented by { }.
Create a Set
Sets can be created by using the built-in set() function
with an iterable object or a sequence by placing the
sequence inside curly braces, separated by a
‘comma’. The type of elements in a set need not be
the same, various mixed-up data type values can also
be passed to the set.
You cannot access items in a set by referring to an index or a key.
But you can loop through the set items using a for loop, or ask if a
specified value is present in a set, by using the in keyword.
Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Example
Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
Add Items
Once a set is created, you cannot change its items, but you
can add new items.
To add one item to a set use the add() method.
Example
Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
Add Sets
To add items from another set into the current set, use the
update() method.
Example
Add elements from tropical into thisset:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
Add Any Iterable
Example
Add elements of a list to at set:
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)
Remove Item
Nested dictionary
a= {1: ‘CSE’, 2: {’J’:1011,’K’:4205} ,3: ‘CSD’}
Accessing Key-value in Dictionary
In order to access the items of a dictionary refer to
its key name. Key can be used inside square
brackets. There is also a method called get() that
will also help in accessing the element from a
dictionary.
a= {1: ‘CSE’, 2: ‘CSM’ ,3: ‘CSD’}
print(a[1])
print(a.get(3))
Deleting Elements using ‘del’ Keyword
a= {1: ‘CSE’, 2: ‘CSM’ ,3: ‘CSD’}
del(a[1])
Changeable
we can change, add or remove items after the
dictionary has been created.
a= {1: ‘CSE’, 2: ‘CSM’ ,3: ‘CSD’}
a[3]=’ECE’
update()
a= {1: ‘CSE’, 2: ‘CSM’ ,3: ‘CSD’}
b= {1: ‘ECE’ ,3: ‘EEE’}
a.update(b)
user input in python
• To as for any information or input from the
user in Python, we just need to use the input()
function.
Ex: name = input("What is your name? ")
• Thus, the above code, will take the name of
the ser as input.
Processing input()
• Python treats user input as a string value, for
other data types, we explicitly mention that
data type.
Type Conversion
Implicit Conversion:
This is an automatic type conversion and the
Python interpreter handles this on the fl y for us.
We need not to specify any command or function
for same.
print(8/2) - 4.0
Explicit Conversion:
This type of conversion is user-defi ned. We need
to explicitly change the data type for certain
literals to make it compatible for data operations.
print(15//2) - 7
print(15/2) - 7.5
Arithmetic
Exponential:
It returns the square root of a value.
print(5**2) - 25
Comparison
Assignment
Logical
Bitwise
Identity
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
x=[10,11]
z=x
print(x is z) - True
Membership
Membership operators are used to test if a sequence is
presented in an object
x=[10,11,42,5]
print(10 in x) - True
print(100 in x) - False
Ternary operator
a=2
b = 330
print("A") if a > b else print("B")
a = 330
b = 330
print("A") if a > b else print("=") if a == b else
print("B")
Operator Precedence
type
The command type(x) returns the type of x.
type() is a built-in function in Python.
We can call a function with a specifi c
argument in order to obtain a return value.
type(5) - int
type(5.0) - fl oat
type(int(5.9)) - int
round
A fl oating point conversion by rounding up an
integer.
round(10.1) - 10
round(10.9) - 11
Syntax:
lambda arguments: expression
nums = [1, 2, 3, 4, 5]
squares = map(lambda num: num ** 2, nums)
print(squares) - <map object at 0x00074Ead68>
print(list(squares)) - [1, 4, 9, 16, 25]
filter()
The fi lter function takes two arguments: a function or
None and a sequence.Function
This function off ers a way to fi lter
out elements from a list that don’t satisfy certain criteria.
# Defi ne an array
my_array = [1, 2, 3, 4, 5]
# Traverse the array using a for loop
for element in my_array:
print(element)
reverse an array in Python using slicing
# Defi ne an array
my_array = [1, 2, 3, 4, 5]
# Reverse the array using slicing
reversed_array = my_array[::-1]
# Print the reversed array
print(reversed_array)
# Defi ne an array
my_array = [1, 2, 3, 4, 5]
nums = [5, 8, 2, 7, 1]
# Calculate the length of the array
length = len(nums)
# Initialize max to the fi rst element of the array
max_num = nums[0]
# Iterate through the array to fi nd the largest element
for i in range(1, length):
if nums[i] > max_num:
max_num = nums[i]
# Print the largest element
print("Largest element in the array:", max_num)
def display_matrix(matrix):
for row in matrix:
for element in row:
creating and print(element, end=" ")
displaying print() # Move to the next line after printing each row
def main():