0% found this document useful (0 votes)
20 views

Python

The document provides an overview of Python programming, covering its features, syntax, data types, and key concepts such as variables, functions, lists, tuples, and sets. It highlights Python's simplicity, ease of learning, and object-oriented approach, while also detailing how to perform various operations on data types. Additionally, it explains the importance of indentation, comments, and the use of built-in functions for output and data manipulation.

Uploaded by

224g1a0284
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Python

The document provides an overview of Python programming, covering its features, syntax, data types, and key concepts such as variables, functions, lists, tuples, and sets. It highlights Python's simplicity, ease of learning, and object-oriented approach, while also detailing how to perform various operations on data types. Additionally, it explains the importance of indentation, comments, and the use of built-in functions for output and data manipulation.

Uploaded by

224g1a0284
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 119

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”)

• Concatenating String & integer literal


print(“Hello”, 10)

• Concatenating two stings


print(“Hello”, “World”)
print()
• Concatenating String & variable
i=100
print(i + “smallest 3 digit number ”)

• 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))

print('We are interested in {0} which is currently


trading at {1}'.format(stock_ticker, price))

print('We are interested in {} which is currently


trading at {}'.format(stock_ticker, price))
• Integers – This value is represented by int class. It
contains positive or negative whole numbers.
• Float – It is specifi ed by a decimal point. Optionally,
the character e or E followed by a positive or
negative integer may be appended to specify
scientifi c notation.
• Complex Numbers – A complex number is
represented by a complex class. It is specifi ed as
(real part) + (imaginary part)j.
Ex: – 2+3j
Booleans: What are they?
• If you are watching a weather forecast, the
answer for the question, that is the weather
forecast is correct or not can possibly be true
or false.
• A variable whose value could be either True or
False is called a boolean type variable.
• Remember, True or False starts with capital
letter in python.
Strings
• When the value of a variable contains text,
i.e one or more words is called Strings.
• Anything written between “double quotes“
and ‘single quotes’ is a string in python.
Ex: myVar1=”Lily”
• Here, myVar1 is a string with value “Lily”.
• ‘Hi3’, ‘3929’, “48Number ” are some
examples of strings in python.
Operations on Strings
a=”Hello”
• upper() - It returns the upper case
• lower() - It returns the lower case
• strip() - It returns a string with whitespace
removed from the start and end
• isalpha() - It returns the boolean value True if
all characters in a string are letters, False
otherwise
• isdigit() - It returns the boolean value True if
all characters in a string are digits, False
• startswith(argument) - It returns the boolean value
True if the fi rst character of a string starts with the
character provided as an argument, False
otherwise.
• endswith(argument) - It returns the boolean value
True if the last character of a string ends with the
character provided as an argument, False
otherwise.
• fi nd(sub, start, end) - It returns the lowest index in
a string where substring sub is found within the
slice [start:end]. Here, arguments start and end are
optional. It returns -1 if sub is not found.
• split(delim) - It is used to split a string into
multiple strings based on the delim argument.
• index(character) - It returns the index of the fi rst
occurrence of the character.
• capitalize() - It returns a capitalized version of the
string.
• count(character) - It returns a count of an argu?
ment provided by character.
List
Lists are just like arrays, declared in other
languages which is an ordered collection of data. It
is very fl exible as the items in a list do not need to
be of the same type. Duplicates are allowed.
• List is a sequence data type.
• It is a dynamically sized array.
• It is a mutable data type.
Creating a List in Python
Lists in Python can be created by just placing the
sequence inside the square brackets[].
Ex: list1=[1, 2, “Lily”, 39.29, True]
A list can also have another list as an item. This is
called nested list.
a=[1,2,3[4,5],6,7]
Printing and Accessing the list:
print(list1)
• Using index, we can access the elements in the
list.
print(list1[3]) #39.29
print(list1[6]) #list index out of
range
• Negative indexing is also allowed.
print(list1[-1]) #True
Slicing of List
• print(list1[0:4]) #[1, 2, “Lily”, 39.29, True]
• print(list1[:]) #[1, 2, “Lily”, 39.29,
True]
• print(list1[1:3]) #[2, “Lily”]
• print(list1[1:]) #[2, “Lily”, 39.29,
True]
• print(list1[:4]) #[1, 2, “Lily”, 39.29]

• thislist = ["apple", "banana", "cherry", "orange",


"kiwi", "melon", "mango"]
• print(thislist[-4:-1])
Check if Item Exists

To determine if a specifi ed item is present in a list


use the “in” keyword:
Example
Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Python - Change List Items

To change the value of a specifi c item, refer to


the index number:
Example
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
Change a Range of Item Values

To change the value of items within a specifi c range,


defi ne a list with the new values, and refer to the range
of index numbers where you want to insert the new
values:

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

To insert a new list item, without replacing any of the


existing values, we can use the insert() method.
The insert() method inserts an item at the specifi ed
index:
Example
Insert "watermelon" as the third item:
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist) #['apple', 'banana', 'watermelon',
'cherry']
Python - Add List 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.

Access Tuple Items


You can access tuple items by referring to the index
number, inside square brackets:

Example
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
Negative Indexing

Negative indexing means start from the end.


-1 refers to the last item, -2 refers to the second last
item etc.

Example
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Range of Indexes

You can specify a range of indexes by specifying where


to start and where to end the range.
When specifying a range, the return value will be a new
tuple with the specifi ed items.
Example
Return the third, fourth, and fi fth item:
thistuple = ("apple", "banana", "cherry", "orange",
"kiwi", "melon", "mango")
print(thistuple[2:5])
• The search will start at index 2 (included) and end at
index 5 (not included).
print(thistuple[:4])
#('apple', 'banana', 'cherry', 'orange')
print(thistuple[2:])
#('cherry', 'orange', 'kiwi', 'melon', 'mango')
print(thistuple[-4:-1])
#('orange', 'kiwi', 'melon')
Check if Item Exists
To determine if a specifi ed item is present in a tuple use
the in keyword:
Example
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
A tuple can also be created without using the brackets.
a=1,2,3
type(a) - tuple

We can repeat a value multiple times within a tuple.


a=(2,)*5 - (2,2,2,2,2)
Change Tuple Values

Once a tuple is created, you cannot change its values.


Tuples are unchangeable, or immutable as it also is called.
But there is a workaround. You can convert the tuple into
a list, change the list, and convert the list back into a
tuple.

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

Since tuples are immutable, they do not have a built-in


append() method, but there are other ways to add items
to a tuple.
1. Convert into a list: Just like the workaround for
changing a tuple, you can convert it into a list, add your
item(s), and convert it back into a tuple.

Example
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
Add Items

2. Add tuple to a tuple: You are allowed to add tuples to


tuples, so if you want to add one item, (or many), create a
new tuple with the item(s), and add it to the existing
tuple:
Example
Create a new tuple with the value "orange", and add that
tuple:
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
• When creating a tuple with only one item, remember to
Remove Items
• You cannot remove items in a tuple.
• Tuples are unchangeable, so you cannot remove items
from it, but you can use the same workaround as we
used for changing and adding tuple 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

When we create a tuple, we normally assign values to it.


This is called "packing" a tuple.
But, in Python, we are also allowed to extract the values
back into variables. This is called "unpacking":
Example
Unpacking a tuple:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
Using Asterisk*

If the number of variables is less than the number of


values, you can add an * to the variable name and the
values will be assigned to the variable as a list:

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

The object in the update() method does not have to be a set,


it can be any iterable object (tuples, lists, dictionaries etc.).

Example
Add elements of a list to at set:
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)
Remove Item

• The del keyword will delete the set completely


• To remove an item in a set, use the remove(), or the
discard() method.
Example
Remove "banana" by using the remove() method:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
• If the item to remove does not exist, remove() will raise an
error.
Remove Item
Remove "banana" by using the discard() method:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
• If the item to remove does not exist, discard() will NOT
raise an error.
• You can also use the pop() method to remove an item, but
this method will remove a random item, so you cannot be
sure what item that gets removed.
• The return value of the pop() method is the removed item.
Dictionary
A dictionary in Python is an unordered collection of
data values, used to store data values like a map,
unlike other Data Types that hold only a single value
as an element, it holds a key: value pair. Key-value is
provided in the dictionary to make it more optimized.
Each key-value pair in a Dictionary is separated by a
colon : , whereas each key is separated by a
‘comma’.
In a dictionary, pairs of keys and values are specifi ed
within curly brackets {} using the following notation:
dictionary = {key1 : value1, key2 : value2, key3 :
Creating Dictionary
A dictionary can be created either using the curly
brackets {} or the method dict().

Creating an empty dictionary


a={}
a=dict()

Creating dictionary with values


a= {1: ‘CSE’, 2: ‘CSM’ ,3: ‘CSD’}

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’

Duplicates Not Allowed


Dictionaries cannot have two items with the same
key
clear()
a= {1: ‘CSE’, 2: ‘CSM’ ,3: ‘CSD’}
a.clear()

keys() & values()


a= {1: ‘CSE’, 2: ‘CSM’ ,3: ‘CSD’}
a.keys()
a.values()

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(This is the year ' + str(2019))


print(fl oat(4)) - 4.0
print(int(4.2)) - 4
print(bool(1011)) - True
print(int(True)) - 1
Operators
Arithmetic
Arithmetic
Floor Division:
// - integer division operator.
It returns an integer value i.e. without any
fractional parts.

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

A call to the round function will return a value


numerically closer to the argument
round(5.98765,2) - 5.99
round(5.98765,1) - 6.0
Problems on Operators
Addition of Variables - http://tinyurl.com/yckd2xn4
Arithmetic operators - http://tinyurl.com/mrx3ch6t
Math - http://tinyurl.com/2hpua4dd
Area of Rectangle - http://tinyurl.com/e4ss6m9c
Chef and Instant Noodles - http://tinyurl.com/2wh3yb92
CodeChef Learn Problem Solving - http://tinyurl.com/4xyyje5h
Fitness - http://tinyurl.com/y7b92axy
Chef and Chocolates - http://tinyurl.com/2rpy98jm
Relation Operators - http://tinyurl.com/mu4jur5h
Logical Operators - http://tinyurl.com/498k7dhh
Assignment Operators - http://tinyurl.com/578shxkf
Problems on Operators
Make Avg - http://tinyurl.com/3533jjfs
Candy Store - http://tinyurl.com/5ks8mmer
Problems - http://tinyurl.com/mpwrs6mt
Scalene Triangle - http://tinyurl.com/mezuu5v3
Favorite Numbers - http://tinyurl.com/yekrup5u
7 Rings - http://tinyurl.com/mvscbhjc
Problem (Make Avg) - Solve sub-components -
http://tinyurl.com/met9by5z
Number Logic
Concept
For finding the digit count
•Division Operator(/) – it returns the quotient.
•Modulus Operator(%) – it returns the
remainder.
Basic Programs
Count the digits in a number.-
http://tinyurl.com/bdfzz6xv
Reverse of a number. - http://tinyurl.com/5dxe6k8t
Palindrome of a number. - http://tinyurl.com/ytvauyyx
Print all divisors. - http://tinyurl.com/bdfs62c6
Armstrong number. - http://tinyurl.com/yj6f6fjb
Prime number. - http://tinyurl.com/3c8mata2
GCD or HCF - http://tinyurl.com/yu9tf5ra
Factorial of a given number-
http://tinyurl.com/p43k7a5y
Fibonacci Sequence - http://tinyurl.com/yu9erje7
Palindrome checker. - http://tinyurl.com/54w7um74
Problems on Operators
Make Avg - http://tinyurl.com/3533jjfs
Candy Store - http://tinyurl.com/5ks8mmer
Problems - http://tinyurl.com/mpwrs6mt
Scalene Triangle - http://tinyurl.com/mezuu5v3
Favorite Numbers - http://tinyurl.com/yekrup5u
7 Rings - http://tinyurl.com/mvscbhjc
Problem (Make Avg) - Solve sub-components -
http://tinyurl.com/met9by5z
Conditional Statements
if
The code within the if block will be executed if
and only if the logical conditions are held true.
We use a comparison operator to check the
truthfulness of the condition. The if statement
evaluates the output of any logical condition
to be either True or False
a = 33
b = 200
if b > a:
print("b is greater than a")
elif
The elif keyword is Python's way of saying "if
the previous conditions were not true, then try
this condition".
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else
The else clause can be thought of as the last part of
conditional statements. It does not evaluate any
conditions. When defi ned it just executes the code
within its block if all conditions defi ned by the if and
elif statements are false.
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
While
The while statement in Python is used to
repeat execution of code or block of code that
is controlled by a conditional expression.
Syntax:
while conditional expression:
code statement 1
code statement 2
.
.
code statement n
data_points = 6
count = 0
while count != data_points:
print(count)
count += 1
for
The for statement in Python is another looping
technique which iterates over a sequence of
objects.
Syntax:
for item in sequence:
code statement 1
code statement 2
.
.
code statement n
range()
The range() function returns a sequence of
numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a
specifi ed number.
for i in range(5):
print(i)
for x in range(2, 6):
print(x)
for x in range(2, 30, 3):
print(x)
break()
The break keyword is used to break the
execution fl ow of a loop. When used inside a
loop, this keyword stops executing the loop
and the execution control shifts to the fi rst
statement outside the loop.
for letter in 'abcdefshse':
if letter == 'e' or letter == 's':
break
print('Current Letter :', letter)
continue()
The continue keyword which will skip the
current iteration and continue with the next
iteration.
for letter in 'abcdefshse':
if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)
pass()
The pass keyword is not used to alter the
execution fl ow, but rather it is used merely as a
placeholder. It is a null statement. The only
diff erence between a comment and a pass
statement in Python is that the interpreter will
entirely ignore the comment whereas a pass
statement is not ignored.
for letter in 'abcdefghijk':
pass
print('Last Letter :', letter)
List comprehensions
List comprehension is an elegant way to defi ne
and create a list in Python. It is used to create a
new list from another sequence, just like a
mathematical set notation in a single line.

[i**3 for i in range(0,10)]

[str(i)+': Even' if i%2==0 else str(i)+': Odd' for i


in range(0,6)]
Functions
Functions
A function is a block of code that performs a specifi c task)
which runs only when it is called.
From the defi nition, it can be inferred that writing such
block of codes, i.e. functions, provides benefi ts such as
• Reusability: Code written within a function can be called
as and when needed. Hence, the same code can be reused
thereby reducing the overall number of lines of code.
• Modular Approach: Writing a function implicitly follows a
modular approach. We can break down the entire problem
that we are trying to solve into smaller chunks, and each
chunk, in turn, is implemented via a function.
Types of Functions
There are three types of functions in Python:
• Built-in functions such as print to print on the
standard output device, type to check data type of an
object, etc. These are the functions that Python
provides to accomplish common tasks.
• User-Defi ned functions: As the name suggests these
are custom functions to help/resolve/achieve a
particular task.
• Anonymous functions: also known as lambda
functions are custom made without having any name
identifi er
Built-in
Functions
They can be directly used within our code without
importing any module and are always available to use.
• type(object) is used to check the data type of an
object.
• fl oat([value]) returns a fl oating point number
constructed from a number or string value.
• int([value]) returns an integer object constructed
from a fl oat or string value, or return 0 if no
arguments are given.
• round(number[,ndigits]) is used to round a fl oat
number up to dig?its specifi ed by ndigits.
User defined
Functions
Functions that the programmer creates are known as
User-Defi ned functions or “tailor-made functions”.
User-defi ned functions can be improved and modifi ed
according to the need of the programmer. Whenever
we write a function that is case-specifi c and is not
defi ned in any header fi le, we need to declare and
defi ne our own functions according to the syntax.
whereas user-defi ned functions must be declared
and defi ned before being used.
User defined
Functions
Functions are defi ned using the def keyword, followed
by an identifi er name along with the parentheses, and
by the fi nal colon that ends the line. The User defi ned
functions block of statements which forms the body of
the function follows the function defi nition. Here’s a
simple example.
def greet():
"""Block of statement.
or Body of function. """
print(' Hello from inside the function!') .
# Calling the function
Lambda
Function
A lambda function is a small anonymous function.
A lambda function can take any number of arguments,
but can only have one expression.

Syntax:
lambda arguments: expression

Firstly, the syntax shows that there is no function


name. Secondly, arguments refers to parameters, and
fi nally, expression depicts the function body
Let us create a function square which squares the
argument provided to it and returns the result. We
create this function using the def keyword.
def square(arg):
result = arg * arg
return result
print(square(3)) # Output 9

The function square defi ned above can be re-written in a


single line using the lambda keyword as shown below: #
Creating a lambda function and assigning it to square

square = lambda arg: arg * arg


print(square(3))
map()
Function
The map function takes two arguments: a function and
a sequence such as a list. This function makes an
iterator that applies the function to each el?ement of a
sequence. We can pass lambda function to this map
function without even naming it.

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.

booleans = [False, True, True, False, True]


print(list(fi lter(None, booleans))) - [True, True, True]

strings = ['one', 'two', 'three', 'four', 'fi ve', 'six']


fi ltered_strings = fi lter(lambda string: len(string) > 3,
strings) print(list(fi ltered_strings)) - ['three', 'four', 'fi ve']
Arrays
Traversing an array in Python typically
involves iterating over each element of the
array. Here's a simple example of how you can
traverse an array in Python:

# 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)

• Alternatively, if you want to reverse the array in-


place (i.e., modify the original array), you can
use the reverse() method
search for an element in an array
You can search for an element in an array in Python using
various methods.
1.Using the in operator:
This is a simple and straightforward way to check if an
element exists in an array.
# Defi ne an array
my_array = [1, 2, 3, 4, 5]
# Search for an element
element_to_search = 3
if element_to_search in my_array:
print("Element found")
else:
print("Element not found")
2.Using the index() method
The index() method returns the index of the fi rst
occurrence of a specifi ed element in the array.

# Defi ne an array
my_array = [1, 2, 3, 4, 5]

# Search for an element


element_to_search = 3
try:
index = my_array.index(element_to_search)
print(f"Element found at index {index}")
except ValueError:
print("Element not found")
3.Using a loop:
You can iterate over the array and manually check each
element.
# Defi ne an array
my_array = [1, 2, 3, 4, 5]
# Search for an element
element_to_search = 3
found = False
for element in my_array:
if element == element_to_search:
found = True
break
if found:
print("Element found")
else:
# Check if the array is sorted in ascending order
def is_sorted(arr):
ascending = all(arr[i] <= arr[i+1] for i in range(len(arr)-
1))
descending = all(arr[i] >= arr[i+1] for i in range(len(arr)-
1))
return ascending or descending
arr = input("Enter the elements of the array separated by
space: ").split()
arr = [int(x) for x in arr]
if is_sorted(arr):
print("The array is sorted.")
else:
print("The array is not sorted.")
Count of negative, postive and zero
def main():
positive = 0, negative = 0, zero = 0
n = int(input("Enter the size of the array: "))
arr = []
print("Enter", n, "elements:")
for _ in range(n):
arr.append(int(input()))
for num in arr:
if num > 0:
positive += 1
elif num < 0:
negative += 1
else:
zero += 1
print("Positive:", positive, ", Negative:", negative, ", Zero:", zero)
if __name__ == "__main__":
main()
Sum of array elements
# Take user input for the array
arr = input("Enter the elements of the array separated by
space: ").split()
arr = [int(x) for x in arr] # Convert input elements to
integers

# Calculate the sum of elements in the array


array_sum = 0
for element in arr:
array_sum += element

# Print the sum


print("Sum of elements in the array:", array_sum)
Largest of array elements

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():

matrix rows = int(input("Enter the number of rows: "))


cols = int(input("Enter the number of columns: "))
matrix = []
print("Enter the elements of the matrix:")
for i in range(rows):
row = []
for j in range(cols):
element = int(input(f"Enter element at position
({i+1},{j+1}): "))
row.append(element)
matrix.append(row)
print("Matrix:")
display_matrix(matrix)
if __name__ == "__main__":
Problems on Arrays
http://tinyurl.com/mvhd8x9y - Contains Duplicate
http://tinyurl.com/5n7c8tuc - Contains Duplicate II
http://tinyurl.com/3w4rcj37 - Find the Duplicate Number
http://tinyurl.com/rwj9yp4c - Arithmetic Progression
http://tinyurl.com/mshndu4k - Left Rotation
http://tinyurl.com/2w9ta85b - Penalty Shots
http://tinyurl.com/3jexjcsz - Non-Negative Product
http://tinyurl.com/3hmvjuzd - Simple Encoded Array
http://tinyurl.com/bdahxcsr - Decreasing Sequence
http://tinyurl.com/yc8ep8rk - Most Frequently Occurring Digit
Problems on Strings
Insert Character/Word in Any Desired Location in a String
https://www.sanfoundry.com/c-program-insert-word-desired-locati
on/
Delete All Repeated Words in String
https://www.sanfoundry.com/c-program-delete-repeated-words-st
ring/
Remove Given Word from a String
https://www.sanfoundry.com/c-program-remove-word-from-string
/
Read a String and Find the Sum of all Digits in the String
https://www.sanfoundry.com/c-program-sum-all-digits-string/
Find the Most and Least Repeated Character in the String
https://www.sanfoundry.com/c-program-most-least-character-string
/
Count Binary Substrings-
https://leetcode.com/problems/count-binary-substrings/description/
Valid Palindrome -
https://leetcode.com/problems/valid-palindrome/description/
Word Pattern - https://leetcode.com/problems/word
pattern/description/
Return second word in Uppercase-
https://slaystudy.com/c-program-to-return-second-word-of-a-string-i
n-uppercase/
Highest Frequency Character in a String
Thank you
very much!

You might also like