0% found this document useful (0 votes)
16 views45 pages

Python Note Book

Uploaded by

Jk nayak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views45 pages

Python Note Book

Uploaded by

Jk nayak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Why is Python so popular?

 Python is popular for several reasons. Here's a deeper look at what makes it versatile and
easy for coders to use.
 It has a simple syntax that mimics natural language, so it’s easier to read and understand.
This makes it quicker to build projects and faster to improve on them.
 It’s versatile. Python can be used for many different tasks, from web development to
machine learning.
 It’s beginner friendly, making it popular for entry-level coders.
 It’s open source, which means it’s free to use and distribute, even for commercial
purposes.
 Python’s archive of modules and libraries—bundles of code that third-party users have
created to expand Python’s capabilities—is vast and growing.

Python Syntax compared to other programming languages

 Python was designed for readability, and has some similarities to the English language
with influence from mathematics.
 Python uses new lines to complete a command, as opposed to other programming
languages, which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets for
this purpose.

Differences between Python 2 and 3

 Unicode. By default, Python 3 encodes strings using Unicode rather than ASCII.
 Range functions. Python 3’s range() function replaced Python 2’s xrange()
function, improving performance when iterating over sequences.
 Exception handling. Python 3’s exceptions are enclosed in parentheses, while Python
2’s exceptions are enclosed in notations.
 Integer division. In Python 3, the result of an integer division is a float value. In Python
2, the decimals are truncated.
 Annotations. Python 3 supports type annotations, whereas Python 2 does not. This
feature can help with reading and maintaining code.
 Print statement. Python 3 replaces the print statement with a print() function.
 Syntax. Python 3’s syntax is considered easier to understand and more readable than
Python 2’s, which uses more complex syntax.
 Backward compatibility. Python 3 is not backward compatible with Python 2, whereas
Python 2 is backward compatible with previous versions of Python.
Install Python

Step 1

 Go to the official Python download page for Windows.


 Find a stable Python 3 release. This tutorial was tested with Python version 3.11.8.
 Click the appropriate link for your system to download the executable file:
Windows installer (64-bit) or Windows installer (32-bit)

Step 2

 After the installer is downloaded, double-click the .exe file (e.g., python-3.11.8-
amd64.exe) to run the Python installer.
 Select the Install launcher for all users checkbox.
 Select the Add python.exe to PATH checkbox.

Step 3

 Add Python to environment variable.

Pythonpath environment variable in Python allows you to include paths to other Python
files in your scripts and Python's import mechanism to determine where to search for
modules and files that use it. This is useful to avoid typing out full paths every time.

 https://www.digitalocean.com/community/tutorials/install-python-windows-10

Installation of Jupyter Notebook

 Download Anaconda from Google.


 Install it in the system.
 Select Jupyter Notebook from options and launch.

Python Syntax

 Indentation refers to the spaces at the beginning of a code line.


 In Python, indentation is very important and not just for readability.
 Python uses indentation to indicate a block of code.
 Python is an interpreted programming language:
You write .py files in a text editor and execute them using the Python interpreter.
Example:
Nginx CopyEdit

python test.py

Variables

 Variables are containers for storing data values.


Python CopyEdit

x = 50

y = "Learntek"

print(x)

print(y)

 Multiple variables can be used to store multiple values simultaneously:


Python CopiedEdit

x, y, z = 23, 43, 'ABC'


Jupyter Notebook Example

# Loop printing numbers 1 through 10


for i in range(1, 11):
print(i)
1,2,3,4,5,6,7,8,9,10
# Swapping variables
x = 15 y = 20
x, y = y, x
x # Output: 20
y # Output: 15
Variable names

A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for Python 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 and underscores (A-z, 0-9,
and _)
 Variable names are case-sensitive (age, Age, and AGE are three different variables)
 A variable name cannot be any of the Python keywords

Examples:

myvar = "Learntek"
my_var = "Learntek"
_my_var = "Learntek"
myVar = "Learntek"
MYVAR = "Learntek"
myvar2 = "Learntek"

Here's the textual content extracted from your images:

Global Variable

 Variables that are created outside of a function (as in all of the examples above) are
known as global variables.
 Global variables can be used by everyone, both inside of functions and outside.

x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()
Python Datatypes

 Text Type: str


 Numeric Types: int, float, complex
 Sequence Types: list, tuple, range
 Mapping Type: dict
 Set Types: set, frozenset
 Boolean Type: bool
 Binary Types: bytes, bytearray, memoryview
 None Type: NoneType

Numeric Datatype

X = 3
Y = 56.3
Z = 23 + 65j

print(type(X)) # <class 'int'>


print(type(Y)) # <class 'float'>
print(type(Z)) # <class 'complex'>
a = 18
print(a) # 18
print(type(a)) # <class 'int'>
print(type(18 / 2)) # <class 'float'>
22 / 3 # 7.333333333333333
22 // 3 # 7

String Datatype

print("Hello")
print('Python 3.0')

 To represent multi-line strings, we use triple quotes (""" """):

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
Slicing String

 You can return a range of characters by using the slice syntax.


 Specify the start index and the end index, separated by a colon, to return a part of the
string.

b = "Hello, World!"
print(b[2:5]) # "llo"

print(b[:5]) # Slice from start of string — "Hello"


print(b[3:]) # Get characters from position 3 to end — "lo,
World!"

b = "Lets Learn Python!"


print(b[-5:-2]) # "tho"

Jupyter Notebook Examples

s = 'lets learn databricks with Python'


for i in range(10):
print(i)

s[0] # 'l'
s[0:5] # 'lets '
s[11:21] # 'databricks'
s[-1] # 'n'
s[-6:] # 'Python'
s[-6:][2] # 't'

s.split('databricks')
# ['lets learn ', ' with Python']

'|'.join(s.split())
# 'lets|learn|databricks|with|Python'

Here’s the textual content extracted from your slides and screenshots:

Interview Questions

 How to split a string.


 s = "apple,banana,orange"
 s.split(",") # Output: ['apple', 'banana', 'orange']
 How to extract last 3 elements from a string
 s = "databricks with Python"
 s[-3:] # Output: 'hon'

Methods to Modify String

a = " Hi, Let's learn python "


print(a.strip()) # Output: "Hi, Let's learn python"

Format String

age = 30
txt = "My name is Jiten, My age is " + str(age)
print(txt)

Or using .format() and f-strings:

txt = "My name is Jiten, My age is {}"


print(txt.format(age))

# Using f-string
print(f"My name is Jiten, My age is {age}")

Using format() in loops

age = 30
name = "FGS"
for age in range(30, 40):
txt = "my name is {} and my age is {}"
print(txt.format(name, age))

Using f-strings in loops

age = 30
name = "FGS"
for age in range(30, 40):
txt = f"my name is {name} and my age is {age}"
print(txt)

Here is the text content extracted and organized from the provided images:

Interview Questions
 How to split a string
 string.split()

 How to extract last 3 elements from a string


 string[-3:]

Methods to Modify String

a = " Hi, Let's learn python "


print(a.strip())

Format String

# Using concatenation (not recommended with integers directly)


age = 30
txt = "My name is Jiten, My age is " + str(age)
print(txt)

# Using .format()
txt = "My name is Jiten, My age is {}"
print(txt.format(age))

# Using f-string
print(f"My name is Jiten, My age is {age}")
Example in Loop:
age = 30
name = 'FGS5'
for age in range(30, 40):
txt = 'my name is {} and my age is {}'
print(txt.format(name, age))
for age in range(30, 40):
txt = f'my name is {name} and my age is {age}'
print(txt)
Python Operators

 = : Assignment
 += : Add and assign
 -= : Subtract and assign
 / : Division
 // : Floor division
 % : Modulus
 * : Multiplication
 ** : Exponentiation

Example:
age = 49
age += 10 # 59
59 % 5 # 4
2 ** 4 # 16

List

 Lists are used to store multiple items in a single variable.


 Created using square brackets: []
 Dynamic and mutable.

L1 = [23, 34, 54, 'ABC']

 Items are:
o Ordered
o Changeable
o Allow duplicate values
 Indexed (starting from 0)

List Example in Code

l = [4, 6, 8, 'x', 'u', 90, 'AS']


type(l) # Output: <class 'list'>
Change List Items

l2 = [10, 40, "cherry", 87, "Lassi", " ABCC", 64]

print(l2[-1]) # Last item


print(l2[2:5]) # Slice from index 2 to 4
l2[-3:] # Last 3 items
l2[1] = 70 # Update index 1 to 70

Here is the text summary from the screenshots you shared regarding Python Lists and their
methods, as well as list copying concepts:

✅ List Basics

 Lists in Python can hold multiple data types:


 l = [4, 6, 8, 'X', 'U', 90, 8, 'AS', True]
 Accessing elements:
 l[0] # Access first element
 l[-1] # Access last element
 l[1:2] = 18 # Replace element at index 1

✅ List Methods Demonstrated

1. append()
Adds a single element at the end of the list.
2. l.append(False)
3. extend()
Adds elements of an iterable to the end of the list.
Note: Extending with an integer like l.extend(12) causes an error because integers
are not iterable.
4. insert(index, element)
Inserts an element at a specific position.
5. l.insert(5, 80)
6. pop(index)
Removes and returns element at the specified index.
7. l.pop() # Removes last element
8. remove(element)
Removes the first matching element.
9. l.remove([25,26]) # Works if such a sublist exists in `l`
10. clear()
Removes all elements from the list.
11. sort()
Sorts the list in place. Works only if elements are of the same type.
12. reverse()
Reverses the list in place.
13. Copying a list using copy()
14. l2 = l.copy() # deep copy

✅ Interview Question: Reverse a list without inbuilt function

Using slicing:

reversed_list = l[::-1]

Or using a loop:

new_list = []
for i in range(len(l)-1, -1, -1):
new_list.append(l[i])

✅ Deep Copy vs Shallow Copy

 Shallow Copy: Copying a list such that changes in the new list affect the original list.
 Deep Copy: Copying a list so that changes in the new list do not affect the original.

Using copy() creates a shallow copy for top-level elements but behaves like deep copy for
primitive data types. Use copy.deepcopy() from copy module for nested structures.

Would you like all of this in a downloadable .txt or .pdf format too?

Here is the text content from the screenshot you provided:

In [32]: l1 = l

In [33]: l
Out[33]: [25, 8, 90, 80, 'X', 18, 6, 4]

In [34]: l1
Out[34]: [25, 8, 90, 80, 'X', 18, 6, 4]

In [35]: l1[4] = 16

In [36]: l1
Out[36]: [25, 8, 90, 80, 16, 18, 6, 4]

In [37]: l
Out[37]: [25, 8, 90, 80, 16, 18, 6, 4]

In [39]: l2 = l.copy() # deep copy

In [40]: l.insert(5, 10)


Out[40]: [25, 8, 90, 80, 16, 10, 18, 6, 4]

In [41]: l2
Out[41]: [25, 8, 90, 80, 16, 18, 6, 4]

✅ Explanation

 l1 = l → l1 is now a reference to l (both point to the same object).


 Modifying l1[4] = 16 also updates l because they refer to the same list.
 l2 = l.copy() creates a shallow copy of l (new list object).
 Inserting 10 into l at index 5 does not affect l2, proving that l2 is a copy.

Here is the extracted text content from the images you provided:

List Comprehension

 List comprehension offers a shorter syntax when you want to create a new list based on
the values of an existing list.
 Based on a list of fruits, you want a new list, containing only the fruits with the letter "a"
in the name.
 Without list comprehension you will have to write a for statement with a conditional test
inside.
 Example: [i**2 for i in range(10)]

Code Example:
l3 = []
for i in range(10):
l3.append(i**2)
print(l3)
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

With list comprehension and a condition:

[i**2 for i in range(10) if i%2==0]


# Output: [0, 4, 16, 36, 64]
Tuple

 Tuples are used to store multiple items in a single variable just like LIST.
 Tuple is one of 4 built-in data types in Python used to store collections of data.
 A tuple is a collection which is ordered and unchangeable.
 Tuples are written with round brackets.

Unpack a Tuple

 In Python, we are also allowed to extract the values back into variables. This is called
"unpacking".

Example:
F = ("A", "B", "C")
(x, y, z) = F

print(x)
print(y)
print(z)

Code Example of Tuple Unpacking

# Tuple
t = (1, 2, 3, 4)
type(t)
# Output: <class 'tuple'>

a1, a2, a3, a4 = t

Here is the extracted text content from the images you've provided:

List Comprehension

 List comprehension offers a shorter syntax when you want to create a new list based on
the values of an existing list.
 Based on a list of fruits, you want a new list, containing only the fruits with the letter "a"
in the name.
 Without list comprehension, you will have to write a for statement with a conditional
test inside.
 Example: [i**2 for i in range(10)]

Code Example:
l3 = []
for i in range(10):
l3.append(i**2)
print(l3) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

[i**2 for i in range(10) if i%2==0] # Output: [0, 4, 16, 36, 64]

Tuple

 Tuples are used to store multiple items in a single variable just like LIST.
 Tuple is one of 4 built-in data types in Python used to store collections of data.
 A tuple is a collection which is ordered and unchangeable.
 Tuples are written with round brackets.

Unpack a Tuple

 In Python, we are also allowed to extract the values back into variables. This is called
"unpacking".

Example:

F = ("A", "B", "C")


(x, y, z) = F
print(x) # A
print(y) # B
print(z) # C

Code Example:

t = (1, 2, 3, 4)
type(t) # tuple

a1, a2, a3, a4 = t

Methods in Tuple

T = tuple()
T.index()
T.count()

Difference Between List and Tuple (interview question)


1. List is represented by [] whereas tuple is represented by ().
2. List is mutable whereas Tuple is immutable.
3. Tuple is faster than list.
4. WHY tuple is faster compared to list?
5. Tuples are allocated large blocks of memory with lower overhead than lists because they
are immutable. Whereas for lists, small memory blocks are allocated. Thus, tuples tend to
be faster than lists when there are a large number of elements.

Questions

T = (2, 4, 1, 2, 3, 2, [6, 78])

1. T[3] = 34 → Error (tuples are immutable)


2. T[-1][-1] → 78
3. Convert tuple to list: list(T)
4. Program to find all even elements from 1 to 100:
[i for i in range(1, 101) if i % 2 == 0]
5. Program to find all numbers divisible by 5 from 1 to 50:
[i for i in range(1, 51) if i % 5 == 0]

Extra List Questions

 How to join a list into a string?


 ''.join(['A', 'B', 'C']) # 'ABC'
 How to extract only numbers and characters from a list of alphanumeric strings?
 import re
 lst = ['ABC56D', 'MN78', 'HJU', 'KL90', '234']
 chars = [re.sub(r'\d', '', s) for s in lst]
 nums = [re.sub(r'\D', '', s) for s in lst]

Set

 Set is one kind of sequence datatype which is used to store multiple elements.
 A set is a collection which is unordered, unchangeable*, and unindexed.
 It is represented by curly braces {}.

Properties of SET
 Unordered:
o The items in a set do not have a defined order.
o Set items can appear in a different order each time you use them, and cannot be
referred to by index or key.
 Unchangeable:
o Set items are unchangeable, meaning that we cannot change the items after the set
has been created (we can add and remove elements but can’t change them).
 Duplicates Not Allowed:
o Sets cannot have two items with the same value.

Example of Set in Python:

st = {89, 67, 12, 9, 32, 9}


print(st)
# Output: {9, 12, 32, 67, 89}

Note: Duplicate 9 is removed automatically, and items are unordered.

Methods of SET

 add()
 clear()
 copy()
 difference()
 symmetric_difference()
 intersection()
 pop()
 remove()
 union()
 update()

Examples Using Set Methods


# Initial sets
st1 = {89, 67, 12, 9, 32, 89, 9}
st1.add(56) # Adds 56 to the set

st2 = {839, 167, 112, 9, 32, 89, 19}

st1.difference(st2)
# Output: {12, 67}

st1.symmetric_difference(st2)
# Output: {12, 19, 67, 112, 167, 839}

st1.update(st2)
# st1 now includes all elements from st2, merged uniquely

st1.union(st2)
# Output: merged set, like update, but doesn’t modify st1

# Using frozenset
f1 = frozenset(st1)
f1[3] = 54 # Error: 'frozenset' object does not support item
assignment

Dictionary in Python

 Dictionaries store data values in key:value pairs.


 A dictionary is a collection which is:
o Ordered
o Changeable
o Does not allow duplicates
 Represented by {} but in key:value format.

Example:
dic = {'A': 123, 'B': 'MNP'}
D = dict(A=123, B='MNP')

# Accessing elements
dic['A'] # Output: 123

Access Dictionary Elements


 To access keys:
 dic.keys()
 To access values:
 dic.values()
 To access a particular key:
 dic.get('key1')

Example Dictionary Usage

d = dict(A=[3,2,6,1], B=['x','y','z','R'])

 Accessing the dictionary:


 d
 # Output: {'A': [3, 2, 6, 1], 'B': ['x', 'y', 'z', 'R']}
 Accessing a value by key:
 d['A']
 # Output: [3, 2, 6, 1]
 Accessing keys and values:
 d.keys()
 d.values()
 Using get():
 d.get('B')
 # Output: ['x', 'y', 'z', 'R']

Add and Remove Dictionary Elements

 Add/update elements:
 D = {'A': 987, 'B': 783, 'C': 'ASJGDK'}
 D['B'] = 387
 D.update({'B': 387})
 Remove elements:
 D.pop('key1') # Removes the specified key
 D.popitem() # Removes the last inserted key-value
pair

Dictionary Comprehension

 Basic format:
 {dic[j]: i for i, j in dic.items()}
 Comprehensions using keys or values:
 {i for i in dic.keys()}
 {j for j in dic.values()}

Comprehension Examples
 Extract values from dictionary:
 [i for i in d.values()]
 Reorder or extract data:
 [j*2 for i, j in d.items()]

Certainly! Here's the full Python code along with the corresponding output from the images
you provided:

1. Dictionary Creation

d = dict(A=[3,2,6,1], B=['x','y','z','R'])

Output:

{'A': [3, 2, 6, 1], 'B': ['x', 'y', 'z', 'R']}

2. Accessing Dictionary Elements

d['A']

Output:

[3, 2, 6, 1]
d.keys(), d.values()

Output:

(dict_keys(['A', 'B']), dict_values([[3, 2, 6, 1], ['x', 'y',


'z', 'R']]))
d.get('B')

Output:

['x', 'y', 'z', 'R']

3. Adding Elements

d1 = {'C':[30,23,16,51], 'D':['xx','yy','zz','RR'], 'A':


[3,20,6,1]}
d.update(d1)
d

Output:

{'A': [3, 20, 6, 1],


'B': ['x', 'y', 'z', 'R'],
'C': [30, 23, 16, 51],
'D': ['xx', 'yy', 'zz', 'RR']}

4. Removing Elements

d.pop('D')

Output:

['xx', 'yy', 'zz', 'RR']


d

Output:

{'A': [3, 20, 6, 1],


'B': ['x', 'y', 'z', 'R'],
'C': [30, 23, 16, 51]}
d.popitem()

Output:

('C', [30, 23, 16, 51])

5. Dictionary Comprehension

[i for i in d.values()]

Output:

[['x', 'y', 'z', 'R'], [3, 20, 6, 1]]


[j*2 for i,j in d.items()]

Output:
[['x', 'y', 'z', 'R', 'x', 'y', 'z', 'R'], [3, 20, 6, 1, 3, 20,
6, 1]]

Here is the text extracted from the images along with the outputs explained:

1. What is ZIP and Enumerate? (Interview question)

Explanation:

 The enumerate() function returns indexes of all items in iterables (lists, dictionaries,
sets, etc.).
 The zip() function is used to aggregate or combine multiple iterables.

Example usages:

 Zip(l1, l2)
 Enumerate(l1)

2. Example of zip and enumerate with output

key = ['NAME', 'ID', 'AGE']


val = ['XYZ', 123, 29]

# Using zip in a loop


for i, j in zip(key, val):
print(i, j)

Output:

NAME XYZ
ID 123
AGE 29

# Creating dictionary using zip


dict(zip(key, val))

Output:

{'NAME': 'XYZ', 'ID': 123, 'AGE': 29}

# Using enumerate on val


list(enumerate(val))

Output:

[(0, 'XYZ'), (1, 123), (2, 29)]

3. Python questions with expected outputs

Q1:

a = [1,2,3,4,5,6,7,8,9]
a[::2] = 10, 20, 30, 40, 50
print(a)

Output:

[10, 2, 20, 4, 30, 6, 40, 8, 50]

Explanation:
Assigns values to every second element starting from index 0.

Q2:

a = [1,2,3,4,5]
print(a[3:0:-1])

Output:

[4, 3, 2]

Explanation:
Slice from index 3 to 1 (excluding 0), stepping backwards.

Q3:

A = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]


# Write a code to print 8
print(A[1][1][1])
Output: 8
Q4:
a = (2)
print(type(a))
print(a * 7)

Output:

<class 'int'>
14

Explanation:
a is an integer, not a tuple.

Q5:

b = (3,)
print(type(b))
print(b * 3)

Output:

<class 'tuple'>
(3, 3, 3)

Explanation:
b is a tuple of one element, repeated 3 times.

Q6:

print(list(range(10)))

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Q7:

a = {(1, 2): 1, (2, 3): 2}


print(a[1, 2])

Output:

Q8:
my_dict = {}
my_dict[1] = 1
my_dict['1'] = 2
my_dict[1.0] = 4

print(my_dict)

Output: {1: 4, '1': 2}

Explanation:
1 and 1.0 are considered the same key in dictionary, so the value is overwritten.

Here is the extracted text and output from the images you shared:

1. Dictionary comprehension example

Input:

d1 = {3:'1.0', 2:'1', 1:1}


{j:i for i,j in d1.items()}

Output:

{1: 1, 2: '1', 3: '1.0'}

2. What is Control Flow

Python program control flow is regulated by various types of conditional statements, loops, and
function calls. By default, the instructions in a computer program are executed in a sequential
manner, from top to bottom, or from start to end. However, such sequentially executing
programs can perform only simplistic tasks. We would like the program to have a decision-
making ability, so that it performs different steps depending on different conditions.

3. IF statement
 It is helpful when we need some conditional workflow or execution.

Example:

l = input('enter a number')
if l % 3 == 0:
print('divisible by 3')

4. IF statement example with output

a = input('enter a number : ')


if int(a) % 5 == 0:
print(f'{a} is divisible by 5')

Output:

enter a number : 30
30 is divisible by 5

5. Control Flow Diagram (If Condition)

 If condition is true -> execute conditional code


 If condition is false -> skip conditional code

6. If Else statement

 Along with the if statement, else keyword can also be optionally used. Python if else
statement provides an alternate block of statements to be executed if the boolean
expression (in if statement) is not true.

Syntax:

if expression True:
print()
else:
print()

7. If Else example

a = int(input('enter a number : '))


if a % 3:
print(f'{a} is divisible by 3')
else:
print(f'{a*3} is not divisible by 3')

Output:

enter a number : 15
45 is not divisible by 3
a = int(input('enter a number : '))
if a:
print(f'{a} is not zero')
else:
print(f'{a} is zero')

Output:

enter a number : 0
0 is zero

8. Explanation comments

# when output of if condition is non zero then condition is true


and if statement will be executed
# when output of else condition is zero then condition is false
and else statement will be executed

9. Nested if

 If we add multiple if statements in a use case then it is called a nested if statement.


 We need it when we don’t have only 2 cases.

Syntax:

if condition:
print()
elif condition:
print()
else:
print()

10. Nested if example with error (incorrect indentation)

num = int(input('enter a number :'))


if num == 0:
pass
elif num > 0:
print(num ** 2)
elif num < 0:
print('num is negative')

Error:

IndentationError: expected an indented block

11. Nested if example corrected

num = int(input('enter a number :'))


if num == 0:
pass
if num > 0:
print(num ** 2)
if num < 0:
print('num is negative')

Sure! Here's the text extracted from the images you uploaded, along with the relevant code
outputs:

Match Case

It is similar to case statement in SQL.

Syntax:

match variable:
case var1: return 0
case var2: return 1

Example:

def check_number(x):
match x:
case 10:
print("It's 10")
case 20:
print("It's 20")
case _:
print("It's neither 10 nor 20")

check_number(10)

Output:

It's 10

Loop

Python loops allow us to execute a statement or group of statements multiple times.

Types:

 While loop
 For loop
 Nested loop

Example of a while loop:

n = 15
while n > 10:
print(n*10)
n = n - 1

Output:

150
140
130
120
110

Example of creating a list using range:

l = list(range(1, 11))
print(l)
Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Control Statements

Control
Sr.No Description
Statement
break Terminates the loop statement and transfers execution to the statement
1
statement immediately following the loop.
continue Causes the loop to skip the remainder of its body and immediately retest
2
statement its condition prior to reiterating.
The pass statement in Python is used when a statement is required
3 pass statement
syntactically but you do not want any command or code to execute.

Examples

Break Statement

l1 = [3, 4, 5, 32, 4]
for i in l1:
print(i)
if i == 5:
break

Output:

3
4
5

Continue Statement

l1 = [3, 4, 5, 32, 4]
for i in l1:
print(i)
if i < 10:
continue
else:
break
print(i)

Output:
3
4
5
32

Pass Statement

if year:
df = df.filter(df.year > year)
else:
pass

(No output, pass just acts as a placeholder.)

Python
s1=['ABHD', 'JAG', 'ASSwx', 'TEW', 'AUYR', 'KUG']
l2=[]
for ele in s1:
if ele.startswith('A'):
l2.append(ele)
else:
continue
l2

Output 1:

['ABHD', 'ASSwx', 'AUYR']

Image 2:

Python
s1=['ABHD', 'JAG', 'ASSwx', 'TEW', 'AUYR', 'KUG']
l2=[]
for index in range(len(s1)):
if s1[index].startswith('A'):
l2.append(s1[index])
else:
continue
l2

Output 2:

['ABHD', 'ASSwx', 'AUYR']


Python
s2 = 'AHSUNUIEGJXKWSDYOGHjsgtw'
for j in s2:
if j in ('A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'):
print(j)
else:
continue

Output 2 (from the second code block):

A
U
U
I
E
O

Image 3:

Python
s2 = 'AHSUNUIEGJXKWSDYOGHjsgtw'
for j in s2:
if j not in ('A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o',
'u'):
print(j)
else:
continue

Output 3:

H
S
N
G
J
X
K
W
S
D
Y
G
H
j
s
g
t
w

Image 4:
This image describes a nested loop and provides an example:

Python
for i in range(0,100,3):
for j in range(i+1):
print(i+j)

This code would produce a long sequence of numbers, starting with: 1 3 4 6 7 8 ... and so on.

Image 5:

Python
for i in range(1,10,3): # i -> 1, 4, 7
for j in range(i):
print(i,j)
print(i+j)

Output 5:

1 0
1
4 0
4 1
4 2
4 3
4
7 0
7 1
7 2
7 3
7 4
7 5
7 6
7

What is a Function
1. A Python function is a block of organized, reusable code that is used to perform a single,
related action. Functions provide better modularity for your application and a high degree
of code reusing.
2. A top-down approach towards building the processing logic involves defining blocks of
independent reusable functions. A Python function may be invoked from any other
function by passing required data (called parameters or arguments). The called function
returns its result back to the calling environment.

Python
In [21]: def string_match(s1):
l2=[]
for index in range(len(s1)):
if s1[index].startswith('A'):
l2.append(s1[index])
else:
continue
return l2

Python
def sum_1(l):
sum_1 = sum(l)
return sum_1

def mul(l):
l2=[]
for j in l:
l2.append(j**2)
return l2

Python
In [35]: from sum_list import mul

def function1():
...
function2()
...
return

def function2():
...
function1()
...
Return

Python
In [39]: def rev_string(s1):
return s1[::-1]

rev_string('JITEN')

Out[39]:

'NETIJ'

Image 2:

Python
In [47]: n1=[123,637,973]
[int(str(ele)[::-1]) for ele in n1 ]

Out[47]:

[321, 736, 379]

Image 3:

Calling a Python Function

• Defining a function only gives it a name, specifies the


parameters that are to be included in the function and
structures the blocks of code.
• Once the basic structure of a function is finalized, you
can execute it by calling it from another function or
directly from the Python prompt.

Function_1(param1,param2)

Image 4:

Python
In [41]: def rev_string(s1):
return s1[::-1]

rev_string('JITEN')

Out[41]:

'ET'

Image 5:
Pass by value vs Pass by reference

• Call by Value means passing values as copies to the function,


so that
the original data is preserved and any changes made inside the
function are not reflected in the original data, whereas Call
by
Reference means passing references to the memory locations of
variables , hence changes made inside the function are directly
modified in the original values. The choice between the two
completely depends on the particular requirements and
considerations of a program.

Image 6:

Python
Function

In [1]: def add_num(n1,n2):


return n1+n2

add_num(12,32)

Out[1]:

44
Python
In [3]: def add_num(n1,n2):
n1 = n1+2
n2 = n2+5
return n1+n2

x1=23
x2=73
add_num(x1,x2)

Out[3]:

103
Python
In [6]: add_num(x1,x2)

Out[6]: 103

7:

Python
In [9]: def add_num(n1,n2):
n1 = n1+2
n2 = n2+5
return n1+n2

x1=int(input('enter num1 : '))


x2=int(input('enter num2 : '))
add_num(n2=x2,n1=x1)
enter num1 : 12
enter num2 : 87

Out[9]:

106

8:

Types of Arguments in Python

• Default Arguments
• Keyword Arguments
• Arbitrary Arguments
• Required Arguments

9:

Python
In [21]: def add_num(n1,n2):
n1 = n1+2
n2 = n2+5
return n1+n2

x2=74
add_num(n1=12,n2=x2)

Out[21]:

93

10:

Python
In [44]: def add_num(n1=0,n2=34,n3=78):
return n1+n2+n3

n2=30
n1=20
n3=13
#x1=int(input('enter num1 : '))
add_num(n1,n2,n3)

Out[44]:

63
Types of Arguments in Python

• Default Arguments
• Keyword Arguments
• Arbitrary Arguments
• Required Arguments

2:

Python
In [54]: def add_num(n1,n2,n3,n4):
x = n1+n2
y = n3+n4
return x/y

n1,n2,n3,n4 = 23,534,12,78
n = n1,n2,n3,n4
add_num(*n)

Out[54]:

*args vs **kwargs
The special syntax *args in function definitions in Python is
used to pass a variable number of
arguments to a function. It is used to pass a non-keyworded,
variable-length argument list.
• The syntax is to use the symbol * to take in a variable number
of arguments; by convention, it is
often used with the word args.
• What *args allows you to do is take in more arguments than the
number of formal arguments
that you previously defined. With *args, any number of extra
arguments can be tacked on to your
current formal parameters (including zero extra arguments).
• For example, we want to make a multiply function that takes any
number of arguments and is
able to multiply them all together. It can be done using *args.
• Using the *, the variable that we associate with the * becomes
iterable meaning you can do things
like iterate over it, run some higher-order functions such as
map and filter, etc.
The special syntax **kwargs in function definitions in Python is
used to pass a keyworded, variable-
length argument list. We use the name kwargs with the double
star. The reason is that the double
star allows us to pass through keyword arguments (and any number
of them).

4:

Python
In [61]: def add_num(**y):
x = y['n1']
z = y['n2']
return x/z

x1=129
x2=43
add_num(n1=x1,n2=x2)

Out[61]:

3.0

5:

• def ABV(*a):
• if x>10:
• return x*=2
• else:
• return x*y
• print
• x=4
• y=8
• a = (x,y)
• ABV(*a)
• def abc(**a):
• for i,j in a.items():
• print(a[i])

• abc(x=11,y=12)

Image 2:

Anonymous function

Function doesnot have any name is known as Anonymous function.


Basically we consider lambda function in this category.
Lambda function is faster and can be able to execute single
expression.

Lambda x: x*2, [2,4,1,5]

Image 3:

Python
lambda function

In [67]: list(map(lambda x : x**2, range(3,10)))

Out[67]:

[9, 16, 25, 36, 49, 64, 81]

Map vs Filter vs reduce


➢ Map, Filter, and Reduce are paradigms of functional
programming.
They allow the programmer (you) to write simpler, shorter code,
without neccessarily needing to bother about intricacies like
loops
and branching.

➢ Essentially, these three functions allow you to apply a


function
across a number of iterables. map and filter come built-in with
Python (in the __builtins__ module) and require no
importing. reduce, however, needs to be imported as it resides
in
the functools module

Image 5:

Python
x=[3,2,1,3]
list(map(lambda x: x*2,x))

x=[30,12,41,73]
list(filter(lambda x: x%2==0,x))

x=[3,2,1,3]
reduce(lambda x,y: x+y,x)

Image 6:

Python
x=[3,2,1,3]
list(map(lambda x: x*2,x))

x=[30,12,41,73]
list(filter(lambda x: x%2==0,x))

x=[3,2,1,3]
reduce(lambda x,y: x+y,x)

Python
map filter reduce

In [4]: s = ['ABC', 'TYY', 'RWQ']


list(map(lambda x : x[1]+'Z', s))
Out[4]:

['BZ', 'YZ', 'WZ']


Python
In [6]: [x[1]+'Z' for x in s]

Out[6]:

['BZ', 'YZ', 'WZ']

Image 8:

Python
In [13]: s = ['ABC', 'TYY', 'RWQ', 'AYTEI']
list(filter(lambda x : x[0]=='A', s))

Out[13]:

['ABC', 'AYTEI']
Python
In [12]: s = ['ABC', 'TYY', 'RWQ', 'AUTRI']
list(map(lambda x : x[0]=='A', s))

Out[12]:

[True, False, False, True]

Image 9:

Python
In [16]: s = ['ABC', 'TYY', 'RWQ', 'AUTRI']
list(map(lambda x : x if x[0]=='A' else 'XXXX', s))

Out[16]:

['ABC', 'XXXX', 'XXXX', 'AUTRI']

Python
In [18]: from functools import reduce

In [19]: reduce(lambda x,y: x+y, s)

Out[19]:
'ABCTYYRWQAUTRI'
Python
In [ ]: x = 'ABC'
y = x + y #'ABC'
y = 'ABC'
Python
x=[3,2,1,3]
list(map(lambda x: x*2,x))

x=[30,12,41,73]
list(filter(lambda x: x%2==0,x))

x=[3,2,1,3]
reduce(lambda x,y: x+y,x)

Image 2:

List Comprehension and Dict comprehension

• [i+5 for i in range(1,20,2)]


• question 1 : ls =
['MANAS2032','SANDEEP2002','SAKSHI1998','RAKESH2001']
extract all numbers which are greater than 1 from each
element of list.
• question 2 : ls =
['MANAS2012','SANDEEP2002','SAKSHI1998','RAKESH2001']
extract the age from each element where age is greater than 20.
qusetion 3:
ls = ['MANAS2012','SANDEEP2002','SAKSHI1998','RAKESH2001']
extract all people name whise age is >20

Nested Function
A function that is defined inside another function is known as a
nested
function. Nested functions are able to access variables of the
enclosing scope.
In Python, these non-local variables can be accessed only within
their
scope and not outside their scope.

def outerFunction(str1):
def innerFunction():
print(str1)
innerFunction()

OuterFunction('AJSJHD')

Image 4:

Python
nested function

In [25]: def outer_function(s1,s2):


def inner():
s = s1*s2
return s
return inner()

outer_function('jbef',2)

Out[25]:

'jbefjbef'
Python
In [35]: def outer_function(s1):
def inner(s2):
s = s1*s2
return s
return inner

o = outer_function('jbef')
o(2)

Out[35]:

'jbefjbef'
Closure function
• A Closure in Python is a function object that remembers values
in
enclosing scopes(outer function) even if they are not present
in
memory.
• It is a record that stores a function together with an
environment: a
mapping associating each free variable of the function
(variables that
are used locally but defined in an enclosing scope) with the
value or
reference to which the name was bound when the closure was
created.
• A closure—unlike a plain function—allows the function to access
those captured variables through the closure's copies of their
values
or references, even when the function is invoked outside their
scope.

Image 6:

Python
Example

def num_add(num1):
def num_sub(num2):
return num1+num2
return num_sub

a=input('num1')
b=input('num2')
num_add(a)(b)

Decorator Function

• Decorators are a very powerful and useful tool in Python since


it
allows programmers to modify the behaviour of a function or
class.
• Decorators allow us to wrap another function in order to extend
the
behaviour of the wrapped function, without permanently
modifying
it.
• It pass the function as a argument.

Image 8:

Python
decorator function

In [58]: def outer(func):


def inner(x):
s = func(x)
if s%2==0:
return 'EVEN'
else:
return 'ODD'
return inner

In [59]: def add_list(x):


return sum(x)

In [60]: x = [2,3,4,5]
outer(add_list)(x)

Out[60]:

'EVEN'

Image 9:

Python
In [61]: @outer
def add_list(x):
return sum(x)

add_list(x)

Out[61]:

'EVEN'

You might also like