0% found this document useful (0 votes)
21 views43 pages

Python Internal 1

Uploaded by

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

Python Internal 1

Uploaded by

srivigneshgamer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT – 1 BASICS OF PYTHON PROGRAMMING

Features,History and Future of Python

Features of Python

Simple and Easy to Learn

Python's syntax is straightforward and readable, making it an excellent choice for beginners
and experienced developers alike.

Open Source and Community Support

Python is open-source, with an active and vast community contributing to its growth and
libraries.

Interpreted Language

Python executes code line-by-line, allowing easier debugging and dynamic coding.

Dynamic Typed language

No need to declare variable types explicitly; Python infers types at runtime.

Cross-Platform Compatibility

Python runs seamlessly on various operating systems, including Windows, macOS, and
Linux.

Extensive Libraries and Frameworks

Libraries: NumPy, Pandas, Matplotlib, TensorFlow, etc.

Frameworks: Django, Flask, FastAPI, etc.

Versatile Applications

Python is used in web development, data science, artificial intelligence, machine learning,
automation, game development, and more.

Object-Oriented and Functional: Python supports both object-oriented programming (OOP)


and functional programming paradigms.
Rich Ecosystem

Python’s ecosystem provides tools for almost every domain, making it a one-stop solution
for development.

History of Python

Creation

Python was created by Guido van Rossum in 1989 during his time at Centrum Wiskunde &
Informatica (CWI) in the Netherlands.

It was released to the public in 1991 as Python 0.9.0.

Design Philosophy

Guido named it after the comedy series Monty Python's Flying Circus. Python's design
emphasizes readability, simplicity, and explicitness.

Milestones

Python 1.0 (1994): Included core features like exception handling, functions, and modules.

Python 2.0 (2000): Introduced list comprehensions and garbage collection with reference
counting.

Python 3.0 (2008): Major redesign focusing on eliminating inconsistencies (breaking


backward compatibility).

Growth

Over the years, Python gained widespread adoption due to its versatility, simplicity, and
applicability in emerging technologies like AI and machine learning.

Future of Python

Continued Dominance in Data Science and AI

Python is expected to maintain its lead as the go-to language for data analysis, machine
learning, and AI applications.
Improved Performance: Efforts like PyPy (a faster Python interpreter) and Just-In-Time (JIT)
compilation aim to enhance Python's execution speed.

Adoption in Emerging Fields

Quantum computing: Frameworks like Qiskit.

Blockchain and cryptography applications.

IoT development.

Web and App Development

Python frameworks are evolving for better support in web and mobile applications, with
tools like BeeWare gaining traction.

Writing and Executing first python program

Step 1: Install Python

1. Download Python
Visit Python's official website and download the latest version for your operating
system.
2. Install Python
Follow the installation wizard. Ensure to check the box “Add Python to PATH” during
installation.

Step 2: Verify Installation

1. Open a terminal (Command Prompt on Windows, Terminal on macOS/Linux).


2. Type python –version

If Python is installed correctly, it will display the installed version.

Step 3: Write a Python Program

1. Open any text editor (Notepad, VS Code, PyCharm, etc.).


2. Write the following code to print "Hello, World!":
print("Hello, World!")

3. Save the file with the extension .py. For example, hello.py.

Step 4: Execute the Python Program

1. Open a terminal.
2. Navigate to the directory where the file is saved:

cd path/to/your/file

3. Run the program:

python hello.py

You should see the output:


Hello, World!
Example of a Simple Python Program

Program: Add Two Numbers

# This program adds two numbers


num1 = 5
num2 = 7
# Adding numbers
sum = num1 + num2
# Displaying the result
print("The sum of", num1, "and", num2, "is:", sum)

Steps to Execute

1. Save the program as add_numbers.py.


2. Run it in the terminal:

python add_numbers.py
3. Output:

The sum of 5 and 7 is: 12


Constants

A constant in Python is a value that is meant to remain unchanged throughout the program.
While Python does not have built-in support for constants, developers use conventions to
define them

How to Define Constants in Python?

1. Use Uppercase Letters: By convention, constants are written in uppercase letters


with underscores to separate words.
2. Example:

PI = 3.14159 # Constant for Pi


GRAVITY = 9.8 # Constant for gravitational acceleration
MAX_USERS = 100 # Maximum number of users
Example Program Using Constants
# Define constants
PI = 3.14159
GRAVITY = 9.8

# Calculate the area of a circle


radius = 5
area = PI * radius ** 2

# Print the area of the circle


print("The area of the circle is:", area)

# Calculate the weight of an object


mass = 10 # Mass in kilograms
weight = mass * GRAVITY
# Print the weight of the object
print("The weight of the object is:", weight, "N")

Output:
The area of the circle is: 78.53975
The weight of the object is: 98.0 N

Why Use Constants:

 Makes the code easier to read and understand.


 Reduces duplication of values in the code.
 Simplifies maintenance if the value needs to change.

Variables in Python

A variable is a name used to store data that can be changed during the program's execution.
It acts as a container for storing values. In Python, variables are created when you assign a
value to them.

Rules for Naming Variables

1. Start with a letter or an underscore (_).


Example: my_variable, _temp
2. Cannot start with a number.
Example: 1var is invalid.
3. Can only contain letters, numbers, and underscores.
Example: user_name, age2
4. Case-sensitive: Name and name are different variables.
5. No reserved keywords: Avoid names like if, while, True.

Assigning Values to Variables

1. Single Assignment:
python
Copy code
x = 5 # Integer
name = "Alice" # String
pi = 3.14 # Float

2. Multiple Assignments:

python
Copy code
a, b, c = 1, 2, 3 # Assigning multiple values
x = y = z = 10 # Same value to multiple variables

Types of Variables

Python is dynamically typed, so you don't need to declare the type of a variable. It
determines the type based on the value assigned.

1. Integer:

python
Copy code
age = 25

2. Float:

python
Copy code
height = 5.9

3. String:

python
Copy code
name = "Alice"
4. Boolean:

python
Copy code
is_active = True

5. List:

python
Copy code
numbers = [1, 2, 3]
Example Program
# Define variables
name = "John" # String
age = 30 # Integer
height = 5.9 # Float
is_student = False # Boolean

# Display the values


print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is a student:", is_student)

# Update variable values


age = age + 1
print("Updated Age:", age)

Output:

Name: John
Age: 30
Height: 5.9
Is a student: False
Updated Age: 31

Identifiers:

Identifiers are the names used to identify variables, functions, classes, or other objects in
Python. They follow specific rules to ensure clarity and consistency in the code.

Rules for Naming Identifiers

1. Start with a letter (A-Z or a-z) or an underscore (_).


o Examples: name, _value
o Invalid: 1name (cannot start with a number)
2. Followed by letters, digits (0-9), or underscores.
o Examples: data1, my_variable, value_2
o Invalid: data@1 (special characters are not allowed)
3. Cannot use Python's reserved keywords or built-in function names.
o Examples of reserved keywords: if, while, for, True
o Example: for = 10 is invalid because for is a keyword.
4. Case-sensitive.
o Example: Name and name are two different identifiers.

Examples of Valid and Invalid Identifiers

Valid Invalid

name 1name (starts with a number)

_value value@ (contains special character)

Data123 if (reserved keyword)

Example:

name = "Alice"
age = 25

_student_id = 101

PI = 3.14159

print("Name:", name)

print("Age:", age)

print("Student ID:", _student_id)

print("Value of PI:", PI)

Data Types in Python

In Python, data types define the kind of value a variable can hold. They can be categorized
into primitive and non-primitive data types.

1. Primitive Data Types

These are the basic, built-in data types in Python. They represent single values and are
immutable (cannot be changed after creation).

Type Description Example

int Whole numbers 10, -5, 0

float Decimal numbers 3.14, -2.5

complex Numbers with real and imaginary parts 3 + 4j

bool Logical values True, False

str Sequence of characters "Hello", 'Python'

Examples of Primitive Data Types


# Integer
age = 25
print(type(age)) # Output: <class 'int'>

# Float
height = 5.9
print(type(height)) # Output: <class 'float'>

# Complex
num = 3 + 4j
print(type(num)) # Output: <class 'complex'>

# Boolean
is_active = True
print(type(is_active)) # Output: <class 'bool'>

# String
name = "Alice"
print(type(name)) # Output: <class 'str'>

2. Non-Primitive (or Composite) Data Types

These are more complex data types and can hold multiple values or elements.

Type Description Example

list Ordered, mutable collection [1, 2, 3], ["a", "b", "c"]

tuple Ordered, immutable collection (1, 2, 3), ("a", "b", "c")

set Unordered, mutable collection of unique elements {1, 2, 3}, {"a", "b", "c"}

dict Unordered collection of key-value pairs {"name": "Alice", "age": 25}

range Sequence of numbers range(1, 5)


Type Description Example

bytes Immutable sequence of bytes b"hello"

bytearray Mutable sequence of bytes bytearray(5)

NoneType Represents the absence of value None

Examples of Non-Primitive Data Types


# List
fruits = ["apple", "banana", "cherry"]
print(type(fruits)) # Output: <class 'list'>

# Tuple
coordinates = (10, 20, 30)
print(type(coordinates)) # Output: <class 'tuple'>

# Set
unique_numbers = {1, 2, 3, 4}
print(type(unique_numbers)) # Output: <class 'set'>

# Dictionary
person = {"name": "Alice", "age": 25}
print(type(person)) # Output: <class 'dict'>

# NoneType
value = None
print(type(value)) # Output: <class 'NoneType'>
Key Differences Between Primitive and Non-Primitive Data Types

Feature Primitive Non-Primitive

Complexity Simple More complex

Examples int, float, bool list, dict, set

Mutability Immutable Can be mutable or immutable

Usage Store single values Store multiple values

Input Operation in Python

In Python, the input() function is used to take user input from the console.

Example:

# Taking input from the user


name = input("Enter your name: ")
age = int(input("Enter your age: "))

# Displaying the inputs


print("Hello, " + name + "! You are " + str(age) + " years old.")

 input() returns a string by default. You can convert the input to another data type
using functions like int(), float(), etc.
 In the example above, age is converted to an integer using int().

Comments in Python

Comments are used to explain the code or make it more readable. They are ignored during
execution. In Python, comments are created using:

 Single-line comments: Start with #.


 Multi-line comments: You can use triple quotes (''' or """) to comment multiple
lines.

Example:

# This is a single-line comment


name = "Alice" # This is an inline comment

'''This is a multi-line comment


'''

 Single-line comment: # This is a comment.


 Multi-line comment: Use ''' or """ to comment out multiple lines.

Reserved Words (Keywords) in Python

Reserved words are predefined words that cannot be used as variable names, function
names, or identifiers because they have special meanings in Python. These are also known
as keywords.

List of Python reserved keywords:

import keyword
print(keyword.kwlist)

Some common reserved words in Python:

 if, else, for, while, break, continue, def, class, try, except, import, from, and, or, not,
None, True, False, etc.

Example:

# The following will give an error because `if` is a reserved word


# if = "Hello"
# SyntaxError: cannot assign to keyword
Indentation in Python

Indentation is the use of spaces (or tabs) at the beginning of a line of code to define the
scope of loops, functions, conditionals, etc. In Python, indentation is crucial because it
defines the block of code that belongs to a particular statement.

Python uses indentation to differentiate between code blocks, instead of using curly braces
{} like in other programming languages.

Example:

# Indentation example in Python


def greet(name):
if name:
print("Hello, " + name + "!")
else:
print("Hello, Stranger!")

# Correct indentation
greet("Alice")

# IndentationError: expected an indented block


# greet("Alice")
# ^-- This line is not indented correctly

 Indentation level: Each block of code (like the code inside a function or an if block)
must be indented. Python uses 4 spaces per indentation level, but tabs are also
allowed, although spaces are preferred.
Operators in Python

Operators are symbols that perform operations on variables and values. Python has several
types of operators:

a. Arithmetic Operators

These operators are used to perform basic mathematical operations like addition,
subtraction, etc.

Operator Description Example

+ Addition a+b

- Subtraction a-b

* Multiplication a*b

/ Division a/b

// Floor Division a // b

% Modulus (Remainder) a % b

** Exponentiation a ** b

Example:

a = 10
b=3

# Addition
print(a + b) # Output: 13

# Subtraction
print(a - b) # Output: 7
# Multiplication
print(a * b) # Output: 30

# Division
print(a / b) # Output: 3.3333...

# Floor Division
print(a // b) # Output: 3

# Modulus (Remainder)
print(a % b) # Output: 1

# Exponentiation
print(a ** b) # Output: 1000

b. Comparison Operators/Relational Operators

These operators compare two values and return True or False.

Operator Description Example

== Equal to a == b

!= Not equal to a != b

> Greater than a>b

< Less than a<b

>= Greater than or equal to a >= b

<= Less than or equal to a <= b

Example:

a = 10
b=3

# Equal to
print(a == b) # Output: False

# Not equal to
print(a != b) # Output: True

# Greater than
print(a > b) # Output: True

# Less than
print(a < b) # Output: False

# Greater than or equal to


print(a >= b) # Output: True

# Less than or equal to


print(a <= b) # Output: False

c. Logical Operators

These operators are used to combine conditional statements.

Operator Description Example

and Returns True if both conditions are true a > 10 and b < 5

or Returns True if at least one condition is true a > 10 or b < 5

not Reverses the result (True becomes False, False becomes True) not(a > 10)

Example:
a = 10

b=3

# AND operator
print(a > 5 and b < 5) # Output: True

# OR operator
print(a > 15 or b < 5) # Output: True

# NOT operator
print(not(a > 10)) # Output: False

d. Assignment Operators

These operators are used to assign values to variables.

Operator Description Example

= Assign value a = 10

+= Add and assign a += 5

-= Subtract and assign a -= 5

*= Multiply and assign a *= 5

/= Divide and assign a /= 5

//= Floor divide and assign a //= 5

%= Modulus and assign a %= 5

** Exponentiate and assign a **= 5

a = 10
# Add and assign
a += 5 # a = a + 5
print(a) # Output: 15

# Subtract and assign


a -= 3 # a = a - 3
print(a) # Output: 12

e. Bitwise Operators

These operators are used to perform bit-level operations.

Operator Description Example

& Bitwise AND a & b

` Bitwise OR

^ Bitwise XOR a ^ b

~ Bitwise NOT ~a

<< Left shift a << 2

>> Right shift a >> 2

Example:

a = 10 # 1010 in binary
b = 4 # 0100 in binary

# Bitwise AND
print(a & b) # Output: 0 (0000 in binary)

# Bitwise OR
print(a | b) # Output: 14 (1110 in binary)
# Bitwise XOR
print(a ^ b) # Output: 14 (1110 in binary)

# Bitwise NOT
print(~a) # Output: -11 (inverts all bits)

# Left shift
print(a << 2) # Output: 40 (101000 in binary)

# Right shift
print(a >> 2) # Output: 2 (0010 in binary)

Expressions in Python

An expression in Python is a combination of values, variables, operators, and function calls


that evaluates to a value.

Examples of Expressions:

1. Simple Expressions:

x = 10
y=5
result = x + y # expression is x + y
print(result) # Output: 15

2. Compound Expressions:

x = 10
y=5
z=2
result = (x + y) * z # expression is (x + y) * z
print(result) # Output: 30

3. Using Functions in Expressions:

def add(a, b):


return a + b

x = 10
y=5
result = add(x, y) # expression is add(x, y)
print(result) # Output: 15

Operations on strings:

In Python, strings are sequences of characters, and they support a variety of operations.
Below are the most common operations on strings in Python, along with examples.

1. String Concatenation

Concatenation means joining two or more strings together using the + operator.

Example:

str1 = "Hello"
str2 = "World"

2. Concatenating strings
result = str1 + " " + str2 # Adds a space between the two strings
print(result) # Output: Hello World
2. String Repetition

You can repeat a string multiple times using the * operator.


Example:

str1 = "Hello"
result = str1 * 3 # Repeats the string 3 times
print(result) # Output: HelloHelloHello

3. String Indexing

You can access individual characters in a string using indexing. Indexing starts from 0.

Example:

str1 = "Hello"
# Accessing individual characters
print(str1[0]) # Output: H (First character)
print(str1[1]) # Output: e (Second character)

Negative indexing can be used to start counting from the end of the string.

print(str1[-1]) # Output: o (Last character)


print(str1[-2]) # Output: l (Second to last character)

4. String Slicing

Slicing is used to extract a substring from the string. You can specify a start, end, and step.

Example:

str1 = "Hello, World!"

# Slicing from index 0 to 5


print(str1[0:5]) # Output: Hello

# Slicing with step (every 2nd character)


print(str1[0:10:2]) # Output: HooW
# Slicing with negative index (starting from the end)
print(str1[-6:-1]) # Output: World

5. String Length

The len() function is used to get the length (number of characters) of a string.

Example:

str1 = "Hello, World!"


print(len(str1)) # Output: 13

6. String Case Conversion

You can convert the case of the string using several built-in methods:

 upper(): Converts to uppercase


 lower(): Converts to lowercase
 capitalize(): Converts the first character to uppercase and the rest to lowercase
 title(): Capitalizes the first letter of each word

Example:

str1 = "hello, world!"

# Convert to uppercase
print(str1.upper()) # Output: HELLO, WORLD!

# Convert to lowercase
print(str1.lower()) # Output: hello, world!

# Capitalize the first letter


print(str1.capitalize()) # Output: Hello, world!
# Capitalize the first letter of each word
print(str1.title()) # Output: Hello, World

7. String Searching

You can search for a substring within a string using:

 in: Checks if a substring exists.


 find(): Returns the index of the first occurrence of a substring (or -1 if not found).
 index(): Similar to find(), but raises a ValueError if the substring is not found.

Example:

str1 = "Hello, World!"

# Using `in`
print("World" in str1) # Output: True

# Using `find()`
print(str1.find("World")) # Output: 7 (index of the substring)

# Using `index()` (will raise an error if substring is not found)


try:
print(str1.index("Python")) # This will raise ValueError
except ValueError:
print("Substring not found")

8. String Replacement

You can replace a substring in a string using the replace() method.

Example:
str1 = "Hello, World!"
# Replacing "World" with "Python"
result = str1.replace("World", "Python")
print(result) # Output: Hello, Python!

9. String Trimming (Whitespace Removal)

You can remove leading and trailing whitespace from a string using:

 strip(): Removes spaces from both ends


 lstrip(): Removes spaces from the left
 rstrip(): Removes spaces from the right

Example:

str1 = " Hello, World! "


print(str1.strip()) # Output: "Hello, World!"
print(str1.lstrip()) # Output: "Hello, World! "
print(str1.rstrip()) # Output: " Hello, World!"

10. String Splitting

You can split a string into a list of substrings using the split() method. By default, it splits by
spaces.

Example:

str1 = "Hello, World!"


# Splitting by space
result = str1.split()
print(result) # Output: ['Hello,', 'World!']

# Splitting by a comma
result = str1.split(",")
print(result) # Output: ['Hello', ' World!']

Type Conversions in Python

In Python, type conversion refers to converting one data type into another. There are two
types of type conversions:

1. Implicit Type Conversion (Automatic Type Conversion)


2. Explicit Type Conversion (Manual Type Conversion)

1. Implicit Type Conversion

Implicit type conversion is performed by Python automatically when an operation involves


mixing different data types. Python promotes the lower data type to a higher one (for
example, from int to float) to avoid data loss.

Example of Implicit Type Conversion:

# Implicit Type Conversion

x=5 # Integer

y = 2.5 # Float

result = x + y # Python converts x (int) to float before adding

print(result) # Output: 7.5 (float)

2. Explicit Type Conversion

Explicit type conversion, also known as type casting, is performed manually by the user
using built-in Python functions. Python provides several functions to explicitly convert one
type into another.

Common Functions for Type Conversion:


 int(): Converts to integer
 float(): Converts to floating-point number
 str(): Converts to string
 bool(): Converts to boolean
 list(): Converts to a list
 tuple(): Converts to a tuple
 set(): Converts to a set
 dict(): Converts to a dictionary (only works with key-value pairs)

Converting float to integer using int():

# Explicit Type Conversion


num1 = 7.8
result1 = int(num1) # Converts float to integer by removing the decimal part
print(result1) # Output: 7

Converting integer to float using float():

num2 = 5
result2 = float(num2) # Converts integer to float
print(result2) # Output: 5.0

Converting integer to string using str():

num3 = 100
result3 = str(num3) # Converts integer to string
print(result3) # Output: "100"

Converting string to integer using int():

str_num = "42"
result4 = int(str_num) # Converts string to integer
print(result4) # Output: 42
Converting to Boolean Example:
num = 0
result = bool(num) # 0 is considered as False
print(result) # Output: False

str_value = "Hello"
result2 = bool(str_value) # Non-empty string is considered as True
print(result2) # Output: True

Converting a String to List Example:


# Converting string to list using list()
word = "Python"
result = list(word) # Converts the string to a list of characters
print(result) # Output: ['P', 'y', 't', 'h', 'o', 'n']

Converting List to Tuple Example:


# Converting list to tuple using tuple()
numbers = [1, 2, 3, 4]
result = tuple(numbers) # Converts list to tuple
print(result) # Output: (1, 2, 3, 4)

Decision Control Statements in Python

Decision control statements in Python allow the program to take different actions based on
certain conditions. The primary types of decision control statements are:

1. Selection Statements
2. Loop Structures
3. Nested Loops
4. break, continue, pass statements
5. else Statements

1. Selection Statements

Selection statements are used to make decisions in the program. These statements execute
certain blocks of code depending on whether a condition is True or False.

if Statement

The if statement is used to check a condition and execute the code block if the condition is
True.

# Example of if statement
num = 10

if num > 5:
print("Number is greater than 5") # Output: Number is greater than 5

Explanation:
Here, the condition num > 5 is True, so the block of code inside the if statement is executed.

if-else Statement

The if-else statement allows you to specify two branches: one if the condition is True, and
the other if the condition is False.

# Example of if-else statement


num = 3

if num > 5:
print("Number is greater than 5")
else:
print("Number is less than or equal to 5") # Output: Number is less than or equal to 5

Explanation:
Since the condition num > 5 is False, the code inside the else block is executed.

if-elif-else Statement

The if-elif-else statement allows checking multiple conditions.

# Example of if-elif-else statement


num = 5

if num > 10:


print("Number is greater than 10")
elif num == 5:
print("Number is 5") # Output: Number is 5
else:
print("Number is less than 5")

Explanation:
Here, the condition num == 5 is True, so the block inside the elif is executed.

2. Loop Structures

Loops are used to repeat a block of code multiple times. Python provides two main types of
loops: for and while.

for Loop

The for loop is used for iterating over a sequence (like a list, tuple, or string).

# Example of for loop


for i in range(1, 5): # Loops from 1 to 4
print(i) # Output: 1 2 3 4
Explanation:
The for loop iterates through the numbers from 1 to 4 (since range(1, 5) generates numbers
from 1 to 4).

while Loop

The while loop executes a block of code as long as a condition is True.

# Example of while loop


num = 1

while num <= 4:


print(num) # Output: 1 2 3 4
num += 1

Explanation:
The while loop runs as long as num <= 4. After each iteration, num is incremented by 1.

3.Nested Loops

A nested loop is a loop inside another loop. In this case, the inner loop runs for each
iteration of the outer loop.

# Example of nested loops


for i in range(1, 3): # Outer loop
for j in range(1, 3): # Inner loop
print(f"i={i}, j={j}")

Output:

css
Copy code
i=1, j=1
i=1, j=2
i=2, j=1
i=2, j=2

Explanation:
The outer loop runs for two values of i (1 and 2). For each value of i, the inner loop runs for
two values of j (1 and 2).

4. break, continue, and pass Statements

These are control flow statements used within loops to modify their behavior.

break Statement

The break statement is used to exit a loop prematurely.

# Example of break statement


for i in range(1, 6):
if i == 4:
break # Exit the loop when i equals 4
print(i) # Output: 1 2 3

Explanation:
When i equals 4, the break statement terminates the loop.

continue Statement

The continue statement is used to skip the current iteration and move to the next iteration
in a loop.

# Example of continue statement


for i in range(1, 6):
if i == 3:
continue # Skip printing 3
print(i) # Output: 1 2 4 5
Explanation:
When i equals 3, the continue statement skips the print statement for that iteration and
moves to the next iteration.

pass Statement

The pass statement is used as a placeholder for code that will be implemented later. It does
nothing when executed.

# Example of pass statement


for i in range(1, 4):
if i == 2:
pass # Do nothing when i equals 2
print(i) # Output: 1 2 3

Explanation:
When i equals 2, the pass statement is executed, but it does nothing. The loop continues as
usual.

5. else Statement

The else statement can be used in loops to execute a block of code after the loop has
completed, but only if the loop was not terminated by a break.

# Example of else in loop


for i in range(1, 5):
print(i)
else:
print("Loop completed!") # Output: Loop completed!

Explanation:
The else block is executed after the loop finishes, because the loop was not interrupted by a
break.

Using else with break Statement


Example of else with break statement

for i in range(1, 6):


if i == 3:
print("Breaking the loop!")
break
else:
print("Loop completed!") # This won't be executed

Explanation:
Since the loop is terminated by the break statement, the else block is not executed.
UNIT -2 FUNCTIONS,MODULES,DATA STRUCTURES

Functions in Python

A function is a block of code that only runs when it is called. Functions allow us to organize
our code into reusable blocks.

1. Function Introduction

A function is defined using the def keyword in Python, followed by the function name and
parentheses ().

2. Function Definition

To define a function, we use the def keyword followed by the function name and a pair of
parentheses that may contain parameters.

# Function definition
def greet():
print("Hello, World!")

# Function call
greet() # Output: Hello, World!

Explanation:
In the above example, the function greet is defined without parameters. When we call
greet(), it prints "Hello, World!".

3. Function Call

A function call is used to invoke the function and execute its code.

# Function definition

def greet(name):
print(f"Hello, {name}!")
# Function call with argument
greet("Alice") # Output: Hello, Alice!

Explanation:
Here, the function greet accepts a parameter name. When we call greet("Alice"), it prints
the greeting with the name "Alice".

4. Variable Scope and Lifetime

 Scope: The region of the program where a variable is accessible.


 Lifetime: The duration for which a variable exists in memory.

In Python, variables defined inside a function have local scope, meaning they are only
accessible within that function. Variables defined outside of any function have global scope
and can be accessed throughout the program.

# Global variable
x = 10

def my_function():
# Local variable
y = 20
print("Inside function, x =", x) # x is accessible as it is global
print("Inside function, y =", y) # y is accessible within this function

my_function()
# Output:
# Inside function, x = 10
# Inside function, y = 20

# print(x) # Will work


# print(y) # Will give an error because y is local to my_function
Explanation:

 The variable x is global and can be accessed from anywhere in the program.
 The variable y is local to my_function() and cannot be accessed outside it.

5. Return Statement

The return statement is used to exit a function and return a value to the caller.

# Function with return statement


def add(a, b):
return a + b

result = add(3, 4) # Function call


print(result) # Output: 7

Explanation:
The function add(a, b) returns the sum of a and b, and the result is printed outside the
function.

6. Defining Functions with Parameters

Functions can take parameters (inputs) which can be used inside the function.

# Function with parameters


def multiply(a, b):
return a * b

result = multiply(5, 6) # Function call with arguments


print(result) # Output: 30

Explanation:
The function multiply(a, b) takes two parameters and returns their product.
7. Lambda Functions (Anonymous Functions)

Lambda functions are small, unnamed functions defined using the lambda keyword. They
are often used for short, throwaway functions.

# Lambda function to add two numbers


add = lambda a, b: a + b
result = add(2, 3)
print(result) # Output: 5

Explanation:
Here, lambda a, b: a + b is a lambda function that takes two arguments (a and b) and returns
their sum. The function is assigned to the variable add, which is then called with 2 and 3.

8. Document Strings (Docstrings)

A docstring is a string literal that is used to describe a function, class, or module. It is placed
right after the def line.

# Function with a docstring


def greet(name):
"""
This function greets the person passed in the parameter.
"""
print(f"Hello, {name}!")

# Calling the function


greet("Alice") # Output: Hello, Alice!

# Accessing the docstring


print(greet.__doc__) # Output: This function greets the person passed in the parameter.
Explanation:
The docstring """This function greets the person passed in the parameter.""" is used to
describe the function's purpose. It can be accessed using the __doc__ attribute.

9. Recursive Functions

A recursive function is a function that calls itself in order to solve a problem. Recursion is
typically used for problems that can be broken down into smaller, similar sub-problems.

# Recursive function to calculate factorial


def factorial(n):
if n == 1: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive call

result = factorial(5)
print(result) # Output: 120

Explanation:
The factorial() function calculates the factorial of a number by calling itself recursively until
it reaches the base case (n == 1). For factorial(5), it calculates 5 * 4 * 3 * 2 * 1, resulting in
120.

Argument Types in Python

Arguments in Python can be classified based on how they are passed into functions. Python
provides different types of arguments to be passed into a function, which can be
categorized into Positional Arguments, Keyword Arguments, Default Arguments, Variable-
length Arguments, and Keyword-only Arguments.
1. Positional Arguments

Positional arguments are the most common type of arguments in Python. These arguments
are passed to a function in the order in which they appear in the function call.

# Function definition with positional arguments


def greet(name, age):
print(f"Hello {name}, you are {age} years old.")

# Function call with positional arguments


greet("Alice", 25) # Output: Hello Alice, you are 25 years old.

Explanation:
In the above example, name and age are positional arguments. The values are passed to the
function in the order they appear in the function definition.

2. Keyword Arguments

Keyword arguments are arguments that are passed to a function by explicitly specifying the
parameter name along with the value.

# Function definition with keyword arguments


def greet(name, age):
print(f"Hello {name}, you are {age} years old.")

# Function call with keyword arguments


greet(age=25, name="Bob") # Output: Hello Bob, you are 25 years old.

Explanation:
In this case, we passed the arguments by specifying the parameter names (name and age)
along with their values. The order of the arguments doesn't matter when using keyword
arguments.
3. Default Arguments

Default arguments allow you to provide default values for parameters in case the caller does
not pass any value for those arguments. The default value is used if the argument is not
provided.

# Function definition with default argument


def greet(name, age=30):
print(f"Hello {name}, you are {age} years old.")

# Function call with default argument


greet("Alice") # Output: Hello Alice, you are 30 years old.
greet("Bob", 40) # Output: Hello Bob, you are 40 years old.

Explanation:
In the function greet(name, age=30), the parameter age has a default value of 30. If the
caller does not provide an age, the default value is used.

4.Variable-length Arguments (*args)

Definition:
*args allows a function to accept a variable number of non-keyword arguments. The
arguments are received as a tuple.

Example:

def print_numbers(*args):
for number in args:
print(number)

# Function call with variable-length arguments


print_numbers(1, 2, 3, 4)

Output:

Copy code
1
2
3
4

Explanation:
In the function print_numbers(*args), the *args collects all the arguments passed into the
function as a tuple. In this example, the function prints each number passed to it (1, 2, 3, 4).

You might also like