0% found this document useful (0 votes)
387 views30 pages

Sec Total Python III Sem

The document outlines a Python programming course for the academic year 2019-2020, covering fundamental concepts such as input, processing, output, decision structures, loops, functions, and file handling. It details the program development cycle, including problem definition, analysis, algorithm development, coding, testing, and maintenance. Additionally, it discusses best practices for variable naming, reading user input, and handling data types in Python.
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)
387 views30 pages

Sec Total Python III Sem

The document outlines a Python programming course for the academic year 2019-2020, covering fundamental concepts such as input, processing, output, decision structures, loops, functions, and file handling. It details the program development cycle, including problem definition, analysis, algorithm development, coding, testing, and maintenance. Additionally, it discusses best practices for variable naming, reading user input, and handling data types in Python.
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
You are on page 1/ 30

With Effect from the Academic Year 2019–2020

Sec-1 Python-1 BS301

Theory 2Hours/Week 2 credits

Unit – I
Introduction to Python Programming: How a Program Works, Using Python, Program Development Cycle,
Input, Processing, and Output, Displaying Output with the Print Function, Comments, Variables, Reading Input
from the Keyboard,Performing Calculations (Operators. Type conversions, Expressions), More about Data Output.
Decision Structures and Boolean Logic: if, if-else, if-elif-else Statements, Nested Decision Structures,
Comparing Strings, Logical Operators, Boolean Variables.
Repetition Structures: Introduction, while loop, for loop, Calculating a Running Total, Input Validation Loops,
Nested Loops.

Unit – II
Functions: Introduction, Defining and Calling a Void Function, Designing a Program to Use Functions, Local
Variables, Passing Arguments to Functions, Global Variables and Global Constants, Value-Returning Functions-
Generating Random Numbers, Writing Our Own Value-Returning Functions, The math Module, Storing Functions
inModules.
File and Exceptions: Introduction to File Input and Output, Using Loops to Process Files, Processing Records,
Exceptions.

Text Tony Gaddis, Starting Out With Python(3e)

References

1. Kenneth A. Lambert, Fundamentals ofPython

2. Clinton W. Brownley, Foundations for Analytics withPython

3. JamesPayne,BeginningPythonusingPython2.6andPython3

4. Charles Dierach, Introduction to Computer Science usingPython

5. PaulGries,PracticalProgramming:AnIntroductiontoComputerScienceusingPython3
Basics of Programming :-
Algorithm: It is a finite number of clearly described, unambiguous “doable” steps that
can be systematically followed to produce a desired result for given input in a finite amount
of time
There are two main ways thatt algorithms can be represented,
1. Pseudo code
2. Flowcharts
1. Pseudo code:
Pseudo:- Imitation.
code:-Instructions
Instructions written in a programming language
Pseudo code will be a representation that almost looks like a code written in a programming language. It is also
called Program Design Language (PDL). There are several formats which are used to write pseudo-codes
pseudo and
most of them take down the structures from languages such as C, Lisp, FORTRAN, etc. It allows you to include
several control structures such as
s While, If-then-else,
If Repeat-until,
until, for and case, which is present in many high-
high
level languages It should be concise and the keyword should be in capital letter
2. Flowchart :
It is the graphical or pictorial representation of an algorithm.
How a Program Works ?
A Python program works through a series of steps that convert your written code into actions that the computer
can understand and execute. Here’s an overview of how a Python program works:
1. Writing the Code (Source Code)
 Input: You write your Python code using a text editor or an IDE (Integrated Development Environment).
Python programs are written in human-readable
human readable text using the Python language's syntax and rules.
2. Compilation (Bytecode Generation)
 Python is an interpreted language aning it doesn’t compile the entire program into machine code at
language, meaning
once, like C or C++.
 When you run a Python program, Python compiles the source code into bytecode
bytecode. Bytecode is a lower-
level, platform-independent
independent representation of the code.
 This step speeds up execution in future runs since Python can reuse the bytecode instead of reinterpreting
the entire source code.
 Bytecode files typically have a .pyc extension and are stored in a __pycache__ folder.
3. Interpretation (Execution by Python Virtual Machine)
Machine
 The bytecode is then passed to the Python Virtual Machine (PVM),, an interpreter that runs the bytecode
instructions line by line.
 The PVM translates these bytecode instructions into machine code that your computer’s hardware can
understand.
4. Handling Errors
 Python programs may encounter syntax errors (problems with the structure of the code) or runtime
errors (issues during execution like division by zero).
 Python provides detailed error messages that help you debug the program.
5. Using Libraries
 Python
n has a vast ecosystem of built-in
built in libraries (standard libraries) and external libraries (packages) that
you can import into your program to add functionality without writing the code from scratch.

Program Development Cycle (Summary in 3 Lines per Phase)


Phase
1. Problem Definition

 Define the program's purpose and objectives.


 Identify user needs and expected outcomes.
 Set boundaries and constraints for the project.
 Engage stakeholders to clarify requirements.
 Produce a clear problem statement.

2. Problem Analysis

 Analyze functional and non-functional


functional requirements.
 Determine data needs: inputs, outputs, processing.
 Conduct feasibility assessment within constraints.
 Outline a high-level
level solution approach.
 Document findings in a requirements specification.
3. Algorithm Development

 Design a step-by-step solution plan.


 Use flowcharts or pseudocode for clarity.
 Ensure the algorithm covers all scenarios.
 Confirm logic sequence is efficient and accurate.
 Finalize algorithm for the coding phase.

4. Coding and Documentation

 Translate the algorithm into code.


 Write structured, commented code for readability.
 Create user and technical documentation.
 Verify code matches planned functionality.
 Produce a working, well-documented program.

5. Testing and Debugging

 Run tests to verify program functionality.


 Conduct unit, integration, and user testing.
 Identify and fix errors found during testing.
 Ensure program meets quality standards.
 Finalize program for deployment.

6. Maintenance

 Monitor and update the program post-release.


 Fix bugs and optimize performance as needed.
 Add features or improvements over time.
 Adapt to user feedback and environment changes.
 Ensure program remains functional and relevant.

Input, Processing, and Output

1. Input
Python uses the input() function to capture data from the user.
python
Ex:-
name = input("Enter your name: ") # Takes user input and stores it in the variable 'name'
2. Processing
Processing involves manipulating or transforming the input data. This can be any operation like calculations, data
transformation, or logical decisions.
python
Ex. :-
age = int(input("Enter your age: ")) # Takes age as input and converts it to an integer
years_to_100 = 100 - age # Calculates the number of years to reach age 100
3. Output
Python uses the print() function to display the result of the processing to the user.
python
Ex. :-
print(f"{name}, you will turn 100 years old in {years_to_100} years!") # Outputs the final message
Full Example
python
Ex. :-
# Input
name = input("Enter your name: ")
age = int(input("Enter your age: "))
# Processing
years_to_100 = 100 - age
# Output
print(f"{name}, you will turn 100 years old in {years_to_100} years!")
This example demonstrates the basic Input-Processing-Output structure in a Python program.
Identifiers:-
An identifier is a name given to a variable, function, class or module. Identifiers may be one or more
characters in the following format:

Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or


an underscore (_).
Ex: Names like myCountry, other_1 and good_ morning, all are valid examples.
 A Python identifier can begin with an alphabet (A – Z and a – z and _)
 An identifier cannot start with a digit but is allowed every where else. 1plus is invalid, but plus1 is
perfectly.
 Keywords cannot be used as identifiers.
 One cannot use spaces and special symbols like !, @, #, $, % etc. as identifiers.
 Identifier can be of any length.

Keywords :-
Keywords are a list of reserved words that have
predefined meaning. Keywords are special
vocabulary and cannot be used by programmers
as identifiers for variables, functions, constants or
with any identifier name. Attempting to use a
keyword as an identifier name will cause an error.
The following TABLE shows the Python keywords.
Displaying Output with the Print Function:-
1. Basic Usage
The print() function outputs strings or values to the console. You simply pass what you want to display as an
argument, like print("Hello, World!").
print("Hello, World!")
Output:
Hello, World!
2. Printing Variables
You can print the values stored in variables directly by passing them as arguments to print(), such as
print(variable_name).
name = "Alice"
print(name)
Output:
Alice
3. Formatting Output
Concatenation and f-strings are common ways to format printed output. For example, print("Hello, " + name) or
print(f"Hello, {name}").
age = 25
print("Age: " + str(age)) # Using concatenation
print(f"Age: {age}") # Using f-string
Output:
Age: 25
Age: 25
4. Printing with Newlines and Tabs
Use \n for newlines and \t for tabs to control spacing within the printed output. For instance, print("Hello\nWorld")
prints on two lines.
print("Hello\nWorld") # Newline
print("Hello\tWorld") # Tab space
Output:
Hello
World
Hello World
5. Suppressing the Newline
By default, print() adds a newline at the end. You can change this by using the end parameter, like print("Hello",
end=" ").
print("Hello", end=" ")
print("World")
Output:
Hello World
Printing Special Characters
Use escape sequences (e.g., \" or \\) to include special characters in strings, such as print("She said, \"Hello!\"").
print("She said, \"Hello!\"")
print("Path: C:\\Program Files")
Output:
She said, "Hello!"
Path: C:\Program Files
Printing Multiple Lines
Triple quotes ("""...""") allow multi-line string printing, useful for displaying text that spans several lines.
print("""
This is a multi-line string.
It spans multiple lines.
""")
Output:-
This is a multi-line string.
It spans multiple lines.

Comments :-

Single-line Comments

Single-line comments start with a # symbol and extend to the end of the line. They are used to explain
code or add notes.

# This is a single-line comment


print("Hello, World!") # This prints "Hello, World!"

Multi-line Comments

Python does not have a specific multi-line comment syntax, but you can use multiple # symbols or a string literal
(e.g., triple quotes) to simulate multi-line comments.

# This is a multi-line comment


# that spans multiple lines.
print("Python!")

"""
This is another way to add multi-line comments,
often used for documentation or explanations.
"""

print("Multi-line comments can use triple quotes.")

Note: Triple-quoted strings are not true comments but are often used for multi-line documentation. They are
ignored if not assigned to a variable or used as a docstring.
Variables:-
Variable is a named placeholder to hold any type of data which the program can use to assign and modify during
the course of execution. In Python, there is no need to declare a variable explicitly by specifying whether the
variable is an integer or a float or any other type. To define a new variable in Python, we simply assign a value to
a name.
Variables in Python are used to store data values. They act as containers for storing information that can be
referenced and manipulated in a program.

Key Points About Variables

1. Dynamic Typing: Python variables do not require an explicit declaration to reserve memory space. The
assignment happens when a value is assigned to a variable.

x=5 # An integer value


name = "John" # A string value
2. Naming Rules:
o Must start with a letter (a-z, A-Z) or an underscore _.
o Cannot start with a digit (e.g., 1variable is invalid).
o Can only contain alphanumeric characters and underscores (e.g., variable_name, var123).
o Case-sensitive (e.g., myVar and myvar are different).
3. Types of Variables: Python automatically infers the type of variable based on the value assigned to it.

age = 30 # Integer
height = 5.9 # Float
is_student = True # Boolean
4. Reassigning Variables: Variables can be reassigned to different data types.

x = 10 # Initially an integer
x = "Python" # Reassigned as a string
5. Multiple Assignments: You can assign values to multiple variables in a single line.

a, b, c = 1, 2, "Hello"
6. Constants: Python does not have a built-in constant type, but you can use variable naming conventions
(e.g., uppercase letters) to indicate that a variable should not be changed.

PI = 3.14159 # Convention to indicate a constant


Examples

# Assigning values to variables


name = "Alice"
age = 25
height = 5.4
is_active = True
# Printing variables
print(name) # Output: Alice
print(age) # Output: 25
# Multiple assignments
x, y, z = 10, 20, "Python"
print(x, y, z) # Output: 10 20 Python
Best Practices

 Use meaningful variable names that make the code more readable.
 Follow naming conventions like snake_case for variables (e.g., user_name, total_score).

Reading Input from the Keyboard:-


Reading input from the keyboard in Python can be done using the input() function. This function prompts
the user for input and reads it as a string.
1. Basic Usage
The input() function reads a line of text from the user and returns it as a string.
Example Run:
user_input = input("Enter your name: ")
print("Hello, " + user_input + "!")
Enter your name: Alice
Hello, Alice!

2. Converting Input Types


Since input() returns data as a string, you may need to convert it to other types like integers or floats.
Example Run:
age = input("Enter your age: ") # This returns a string
age = int(age) # Convert the string to an integer
print("You are", age, "years old.")
Enter your age: 25
You are 25 years old.

3. Direct Type Conversion


To simplify type conversion, you can wrap input() with the type you need.
Example Run:
height = float(input("Enter your height in meters: "))
print("Your height is", height, "meters.")
Enter your height in meters: 1.75
Your height is 1.75 meters.

4. Handling Multiple Inputs


To take multiple inputs on a single line, you can use split() to parse them.
Example Run:
x, y = input("Enter two numbers separated by space: ").split()
x = int(x)
y = int(y)
print("Sum:", x + y)
Best Practices for taking input from the users
 Always validate and sanitize user input, especially for critical applications.
 Consider using try and except to handle conversion errors.
try:
num = int(input("Enter a number: "))
print("You entered:", num)
except ValueError:
print("Invalid input. Please enter a valid number.")
Data type in Python
1. Numeric Types

 Integer (int): Whole numbers, positive or negative, without decimals.

num = 10
print(type(num)) # Output: <class 'int'>
 Float (float): Numbers with a decimal point.

num = 3.14
print(type(num)) # Output: <class 'float'>
 Complex (complex): Numbers with a real and imaginary part.

num = 2 + 3j
print(type(num)) # Output: <class 'complex'>
2. String (str)

Used for storing text. Strings are enclosed in single, double, or triple quotes.

text = "Hello, World!"


print(type(text)) # Output: <class 'str'>
3. Boolean (bool)

Represents one of two values: True or False.

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

4. Sequence Types

 List (list): An ordered, mutable collection of items, which can be of different types.

fruits = ["apple", "banana", "cherry"]


print(type(fruits)) # Output: <class 'list'>
 Tuple (tuple): An ordered, immutable collection of items.

coordinates = (10, 20)


print(type(coordinates)) # Output: <class 'tuple'>
 Range (range): Represents a sequence of numbers.

numbers = range(5)
print(type(numbers)) # Output: <class 'range'>
5. Mapping Type

 Dictionary (dict): A collection of key-value pairs, unordered and mutable.

person = {"name": "Alice", "age": 25}


print(type(person)) # Output: <class 'dict'>

6. None Type

 NoneType: Represents the absence of a value.

value = None
print(type(value)) # Output: <class 'NoneType'>

Decision Structures and Boolean Logic:


The if statement in Python is used for conditional execution. It evaluates a condition and, if the condition is True,
executes a block of code.

1. if Statement:

 The if statement is used to test a condition. If


the condition evaluates to True, the block of
code under the if statement runs. If it is False,
the code block is skipped.
 Definition: A conditional statement that runs a
block of code only if the condition is True.

Example:

if 5 > 3:
print("5 is greater than 3")

Output:

5 is greater than 3

2. if-else Statement:

 The if-else statement is used when you need to


choose between two blocks of code based on a
condition. If the condition is True, the if block runs.
If False, the else block runs.
 Definition: A conditional structure that runs one
block of code if the condition is True and an
alternate block if the condition is False.
Example:

num = 10
if num > 15:
print("Number is greater than 15")
else:
print("Number is 15 or less")
Output:

Number is 15 or less

3. if-elif-else Statement:
 The if-elif-else statement allows for multiple
conditions to be checked in sequence. The if block is
checked first; if it evaluates to False, the elif blocks
are checked in order. If none of the conditions are
True, the else block is executed.
 Definition: A conditional structure that checks
multiple conditions sequentially, running the block of
code for the first True condition and falling back to
else if none are True.

Example:

num = 8
if num > 10:
print("Number is greater than 10")
elif num > 5:
print("Number is greater than 5 but not greater than 10")
else:
print("Number is 5 or less")

Output:

Number is greater than 5 but not greater than 10

Indentation

Python relies on indentation (usually 4 spaces) to define the block of code under an if statement. Indentation is
mandatory, and incorrect indentation will result in an Indentation Error.

Example of Indentation :-
number = 7

if number > 5:
print("Number is greater than 5.") # Correct indentation
# print("Outside block") # This line is outside the `if` block
Nested Decision Structures
A nested decision structure in Python occurs when an if statement is placed inside another if statement. This
allows for more complex decision-making processes where a condition can be evaluated only after another
condition is met.

Definition

 Nested decision structures are conditional statements that are nested within other conditional
statements. They enable checking for further conditions only if a previous condition is True.

How Nested if Statements Work

1. The outer if statement is evaluated first.


2. If the outer condition is True, the inner if (or nested) statement is evaluated.
3. The nested if can also have its own else or elif blocks for further logic.

Example of a Nested if Structure

age = 20
has_ID = True

if age >= 18:


if has_ID:
print("You are allowed entry.")
else:
print("You need an ID for verification.")
else:
print("You are not old enough to enter.")

Output:

You are allowed entry.

Example with if-elif-else Nesting

score = 85

if score >= 60:


print("You passed!")
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")
else:
print("You failed.")

Output:

You passed!
Grade: B
Key Points to Remember:

 Proper indentation is crucial for readability and correct execution.


 Nested decision structures should be used judiciously, as they can make the code more complex and harder
to read.

Comparing Strings
Common Comparison Operators

Operators like ==, !=, <, >, <=, and >= are used to compare strings, returning True or False.

 ==: Checks if two strings are equal.


 !=: Checks if two strings are not equal.
 <: Checks if the first string is lexicographically less than the second.
 >: Checks if the first string is lexicographically greater than the second.
 <=: Checks if the first string is less than or equal to the second.
 >=: Checks if the first string is greater than or equal to the second.

Example:

print("apple" == "apple") # True


print("apple" != "banana") # True

1. Case-Sensitivity in String Comparison

String comparison in Python is case-sensitive, treating uppercase and lowercase characters differently.

Example:

print("Apple" == "apple") # Output:- False

2. Equality (==)

Checks if two strings are exactly the same.

Example:

print("hello" == "hello") # Output:-True

3. Inequality (!=)

Checks if two strings are different.

Example:

print("hello" != "world") # Output:- True


4. Lexicographical Comparison (<, >)

Compares strings based on Unicode values, determining their order.

Example:

print("apple" < "banana") # Output:-True


print("apple" > "Apple") # Output:-True (lowercase 'a' > uppercase 'A')

5. Case-Sensitivity Example

Strings with different cases, such as apple and Apple, have different Unicode values.

Example:

print("apple" > "Apple") # Output:- True

6. Ignoring Case in Comparisons

Use .lower() or .upper() to convert strings to the same case before comparing.

Example:

print("Hello".lower() == "hello".lower()) # Output:-True

7. Using in for Substring Checks

Checks if one string is a substring of another.

Example:

print("Python" in "Python programming") # Output:- True

Logical Operators in Python:-


Logical operators in Python are used to combine conditional statements and evaluate expressions. They return
True or False based on the conditions provided.

Types of Logical Operators

1. and: Returns True if both statements are True.


2. or: Returns True if at least one statement is True.
3. not: Returns True if the statement is False (reverses the result).

Examples and Explanations

1. and Operator
Definition: Combines two conditions and returns True only if both conditions are True.
Example:
x=5
y = 10
print(x > 2 and y < 15) # True, because both conditions are True
print(x > 2 and y > 15) # False, because the second condition is False
2. or Operator
Definition: Combines two conditions and returns True if at least one condition is True.
Example:
x=5
y = 10
print(x > 2 or y > 15) # True, because the first condition is True
print(x < 2 or y < 15) # True, because the second condition is True
print(x < 2 or y > 15) # False, because both conditions are False
3. not Operator
Definition: Reverses the result of the condition; True becomes False, and False becomes True.
Example:
x=5
print(not x > 2) # False, because x > 2 is True, and `not` reverses it
print(not x < 2) # True, because x < 2 is False, and `not` reverses it

Repetition Structures:

Repetition Structures in Python

Repetition structures, also known as loops, are used to execute a block of code multiple times. Python supports two
main types of loops: for loops and while loops.

1. for Loop

Definition: Used to iterate over a sequence (e.g., a list, tuple, dictionary, set, or string) or a range of numbers.

Example:

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

Output:

0
1
2
3
4

Explanation: The loop runs 5 times, printing numbers from 0 to 4.

2. while Loop

 Definition: Repeats a block of code as long as a specified condition is True.

Example:

count = 0
while count < 5:
print(count)
count += 1

Output:

0
1
2
3
4

Explanation: The while loop checks the condition (count < 5) before each iteration and stops when the
condition becomes False.

Infinite Loops

 Definition: Occurs when the loop's condition never becomes False, causing the loop to run indefinitely.

Example:

while True:
print("This will run forever")

 Note: Always ensure loops have a clear exit condition to avoid infinite loops.

Loop Control Statements

1. break Statement:
o Used to exit the loop prematurely when a certain condition is met.

Example:

for i in range(10):
if i == 5:
break
print(i)

Output:

0
1
2
3
4

2. continue Statement:
o Skips the current iteration and moves to the next one.

Example:

for i in range(5):
if i == 3:
continue
print(i)

Output:
0
1
2
4

3. pass Statement:
o A placeholder that does nothing and is used when a statement is syntactically required.

Example:

for i in range(5):
if i == 2:
pass # Does nothing
else:
print(i)

Output:

Copy code
0
1
3
4

Nested Loops

 Definition: A loop inside another loop, allowing for more complex repetition structures.

Example:

for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")

Output:

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

Key Points:

 for loops are great for iterating over sequences or a range of values.
 while loops are better for conditions that need to be checked before each iteration.
 Control statements like break, continue, and pass help modify loop behavior.
Steps to Calculate Running Total Using an Array and a While Loop:

Step-1 :- Define the Array: Create an array (list) of numbers that you want to calculate the running total for.

Step-2 :- Initialize the Running Total: Start with a variable to store the cumulative sum (initialize it to 0).

Step-3:- Use a while Loop to Iterate: Use a while loop to iterate through the array, updating the running total.

Step-4:- Update the Running Total: On each iteration, add the current element in the array to the running total.

Step-5 :- Print or Store the Running Total: Optionally print the running total after each update.

Code Example:
numbers = [10, 20, 30, 40, 50] # Step 1: Define an array (list) of numbers

running_total = 0 # Step 2: Initialize the running total

i=0 # Step 3: Use a while loop to iterate through the array


while i < len(numbers):
running_total += numbers[i] # Step 4: Add the current number to the running total
print(f"Added {numbers[i]}, running total is now {running_total}") # Step 5: Print the current number
. and the running total
i += 1 # Increment the index to move to the next number

Nested Loops

Nested Loops Definition:

A nested loop is a loop inside another loop, where the inner loop runs completely every time the outer loop runs
once. Nested loops are used when you need to perform repetitive tasks within a set of tasks. The outer loop controls
the number of times the inner loop executes.

Example: Output:

for i in range(3): # Outer loop i = 0, j = 0


for j in range(2): # Inner loop i = 0, j = 1
print(f"i = {i}, j = {j}") i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
Explanation: i = 2, j = 1

 The outer loop (for i in range(3)) runs 3 times.


 The inner loop (for j in range(2)) runs 2 times for each iteration of the outer loop.
 This results in a total of 6 iterations, as each inner loop executes fully for every outer loop iteration.
Unit – II

Functions: Introduction, Defining and Calling a Void Function, Designing a Program to Use Functions, Local Variables,
Passing Arguments to Functions, Global Variables and Global Constants, Value-Returning Functions- Generating Random
Numbers, Writing Our Own Value-Returning Functions, The math Module, Storing Functions inModules.

File and Exceptions: Introduction to File Input and Output, Using Loops to Process Files, Processing Records, Exceptions.

____________________________________________________________________________________________

Functions:-
Designing a program that effectively uses functions can help structure your code and improve readability and reusability.
1. Defining a Function
You define a function using the def keyword, followed by the function name and parentheses containing any parameters.
Here’s a simple example:
def greet(name):
print(f"Hello, {name}!")
2. Calling a Function
After defining a function, you can call it by using its name and passing the required arguments:
greet("Alice") # Output: Hello, Alice!
3. Parameters and Arguments
 Parameters are the variables listed inside the parentheses in the function definition.
 Arguments are the values you pass to the function when calling it.
You can define functions with multiple parameters:
def add(x, y):
return x + y
result = add(5, 3) # result will be 8
4. Return Statement
Functions can return values using the return statement. If no return statement is provided, the function returns None by
default.
def square(number):
return number * number
print(square(4)) # Output: 16

Calling a Void Function:-


You call a void function just like any other function, by using its name followed by parentheses containing any
required arguments:
greet("Alice") # Output: Hello, Alice!
Example of a Void Function
def add_and_print(x, y):
sum_value = x + y
print(f"The sum of {x} and {y} is {sum_value}.")
# Calling the void function
add_and_print(5, 7) # Output: The sum of 5 and 7 is 12.
Key Points
 No Return Value: Since it doesn't return a value, calling a void function will not provide a result that can be
assigned to a variable or used in an expression.
 Side Effects: Void functions often produce side effects, such as printing to the console, modifying data structures, or
changing global variables.
Designing a Program to Use Functions:-
Designing a program that effectively uses functions can help structure your code and improve readability and
reusability. Let’s create a simple program for a basic calculator that can perform addition, subtraction,
multiplication, and division. This example will illustrate how to define and use multiple functions.
Program Structure
1. Define functions for each operation:
o add()
o subtract()
2. Display a menu for user choices.
3. Get user input and call the appropriate function.
4. Handle invalid input gracefully.
Complete Program Example
def add(x, y):
"""Return the sum of x and y."""
return x + y
def subtract(x, y):
"""Return the difference of x and y."""
return x - y

def calculator():
"""Main function to run the calculator."""
print("Welcome to the Simple Calculator!")
print("Select an operation:")
print("1. Add")
print("2. Subtract")

while True:
choice = input("Enter choice (1/2) or 'q' to quit: ")

if choice == 'q':
print("Goodbye!")
break

if choice in ('1', '2'):


try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
except ValueError:
print("Invalid input! Please enter numeric values.")
else:
print("Invalid choice! Please select a valid operation.")

# Run the calculator program


calculator()
Local Variables :-
In Python, local variables are variables that are defined within a function and can only be accessed from within that function.
They are created when the function is called and are destroyed once the function execution is completed.
Key Characteristics of Local Variables
1. Scope: Local variables have a scope limited to the function in which they are defined. They cannot be accessed
outside of that function.
2. Lifetime: The lifetime of a local variable begins when the function is called and ends when the function returns.
3. Naming Conflicts: Local variables can have the same name as variables defined in a broader scope (like global
variables) without causing conflicts. Inside the function, the local variable will take precedence.
Example of Local Variables
Here's a simple example to illustrate local variables:
def calculate_area(length, width):
area = length * width # 'area' is a local variable
return area

# Calling the function


result = calculate_area(5, 3)
print(f"The area is: {result}") # Output: The area is: 15

Passing Arguments to Functions:-


Passing arguments to functions is a fundamental concept in Python that allows you to send data into functions for processing.
You can pass different types of arguments, including positional, keyword, default, and variable-length arguments.
Simple Addition Example
def add(x, y):
"""Add two numbers and return the result."""
return x + y

# Calling the function with positional arguments


result = add(5, 3)
print(f"The sum of 5 and 3 is: {result}") # Output: The sum of 5 and 3 is: 8
Explanation
1. Function Definition:
o The function add takes two parameters, x and y.
2. Function Call:
o We call the function with the arguments 5 and 3. These are positional arguments, meaning the first value (5)
is assigned to x and the second value (3) is assigned to y.
3. Return Value:
o The function computes the sum and returns it.
4. Output:
o The result is printed to the console.
Global Variables and Global Constants :-
In Python, global variables are variables that are defined outside of any function and can be accessed from anywhere in the
code, including inside functions. Global constants, on the other hand, are global variables that are intended to remain
unchanged throughout the program.
Global Variables:-
1. Definition: A global variable is declared outside any function and can be modified from within functions using the
global keyword.
Example:
# Global variable
count = 0

def increment():
global count # Declare count as a global variable
count += 1 # Modify the global variable

increment()
increment()
print(f"Count after incrementing: {count}") # Output: Count after incrementing: 2
Global Constants:-
Definition: Global constants are typically defined using uppercase letters to indicate that they should not change. While
Python does not enforce constants, this naming convention signals to other developers that the variable is intended to be
constant.
Example:
# Global constant
PI = 3.14159

def calculate_area(radius):
return PI * radius * radius

area = calculate_area(5)
print(f"Area of the circle with radius 5: {area}") # Output: Area of the circle with radius 5: 78.53975
Key Points
 Global Variable: Can be modified from within functions using the global keyword.
 Global Constant: Typically defined in uppercase, signaling that it should remain unchanged, but there is
no strict enforcement.
Value-Returning Functions :-
Value-returning functions in Python are functions that return a result back to the caller using the return statement. This is
useful when you want to compute a value and use it later in your program.
Let’s look at a simple example using an add function that returns the sum of two numbers.
Example: Value-Returning Add Function
def add(x, y):
"""Add two numbers and return the result."""
return x + y # Return the sum of x and y

# Calling the add function and storing the result


result = add(5, 3)
# Printing the result
print(f"The sum of 5 and 3 is: {result}") # Output: The sum of 5 and 3 is: 8
Explanation
1. Function Definition:
o The add function takes two parameters, x and y.
o It computes the sum of these two parameters and returns the result using the return statement.
2. Function Call:
o When you call add(5, 3), the function executes and calculates 5 + 3, which equals 8.
3. Returning Value:
o The result (8) is returned to the caller and can be stored in a variable (result in this case).
4. Output:
o Finally, we print the result to the console.
Generating Random Numbers :-
Generating random numbers in Python is easy thanks to the built-in random module. This module provides various
functions to generate random numbers, including integers, floats, and even choices from a sequence. Here’s an overview of
how to use it.
Importing the Random Module
Before using the functions from the random module, you need to import it:
import random
Generating Random Numbers
Here are some common methods for generating random numbers:
1. Random Float Between 0 and 1
To generate a random float in the range [0.0, 1.0):
random_float = [Link]()
print(f"Random float: {random_float}")
2. Random Float in a Specified Range
To generate a random float in a specified range, you can use uniform(a, b):
random_float_range = [Link](1, 10) # Random float between 1 and 10
print(f"Random float between 1 and 10: {random_float_range}")
3. Random Integer
To generate a random integer within a specified range, use randint(a, b):
random_int = [Link](1, 100) # Random integer between 1 and 100
print(f"Random integer between 1 and 100: {random_int}")
Writing Our Own Value-Returning Functions in python
Creating your own value-returning functions in Python allows you to encapsulate logic and reuse code throughout your
program. Let’s go through the steps to write a simple value-returning function, including defining the function, performing
some calculations, and returning a result.
Steps to Create a Value-Returning Function
1. Define the Function: Use the def keyword to define your function.
2. Parameters: Specify any parameters the function needs.
3. Perform Calculations: Inside the function, write the logic to perform calculations or processing.
4. Return a Value: Use the return statement to send a result back to the caller.
Example: Function to Calculate the Area of a Rectangle
Let’s create a function that calculates the area of a rectangle.
Step 1: Define the Function
def calculate_area(length, width):
"""Calculate the area of a rectangle."""
area = length * width # Perform the calculation
return area # Return the calculated area
Step 2: Using the Function
Now we can call this function with different lengths and widths to compute the area.
# Calling the function
area1 = calculate_area(5, 3) # Length = 5, Width = 3
print(f"Area of rectangle 1: {area1}") # Output: Area of rectangle 1: 15
area2 = calculate_area(10, 4) # Length = 10, Width = 4
print(f"Area of rectangle 2: {area2}") # Output: Area of rectangle 2: 40
The math module in Python:-
The math module in Python provides a wide range of mathematical functions and constants. It’s a built-in module, so you
don’t need to install anything extra—just import it to use its features. Below are some key functions and constants available
in the math module, along with short examples for each.
Importing the Math Module
To use the functions from the math module, you need to import it:
import math
Common Functions and Constants
1. Constants: [Link] and math.e
These constants represent the mathematical constants π (pi) and e (Euler's number).
import math
print(f"Value of pi: {[Link]}") # Output: Value of pi: 3.141592653589793
print(f"Value of e: {math.e}") # Output: Value of e: 2.718281828459045
2. Square Root: [Link]()
Calculates the square root of a number.
number = 16
sqrt_value = [Link](number)
print(f"Square root of {number}: {sqrt_value}") # Output: Square root of 16: 4.0
3. Power: [Link]()
Raises a number to a given power.
base = 2
exponent = 3
power_value = [Link](base, exponent)
print(f"{base} raised to the power of {exponent}: {power_value}") # Output: 2 raised to the power of 3: 8.0
4. Trigonometric Functions: [Link](), [Link](), [Link]()
Calculate the sine, cosine, and tangent of an angle (in radians).
angle = [Link] / 4 # 45 degrees in radians
sin_value = [Link](angle)
cos_value = [Link](angle)
tan_value = [Link](angle)
print(f"sin(45°): {sin_value}") # Output: sin(45°): 0.7071067811865475
print(f"cos(45°): {cos_value}") # Output: cos(45°): 0.7071067811865476
print(f"tan(45°): {tan_value}") # Output: tan(45°): 1.0
5. Rounding: [Link]() and [Link]()
Rounds numbers up or down to the nearest integer.
number = 3.7
ceil_value = [Link](number)
floor_value = [Link](number)
print(f"Ceiling of {number}: {ceil_value}") # Output: Ceiling of 3.7: 4
print(f"Floor of {number}: {floor_value}") # Output: Floor of 3.7: 3
6. Factorial: [Link]()
Calculates the factorial of a non-negative integer.
n = 5
factorial_value = [Link](n)
print(f"Factorial of {n}: {factorial_value}") # Output: Factorial of 5: 120
File Input and Output :-
File input and output (I/O) in Python allows you to read data from files and write data to files, enabling you to manage data
persistence and perform operations on data stored outside your program. This is essential for many applications, such as
logging, data processing, and configuration management.
Basic Concepts of File I/O
1. File Modes: When opening a file, you specify a mode that determines how the file will be used:
o 'r': Read (default mode). Opens a file for reading.
o 'w': Write. Opens a file for writing (creates a new file or truncates an existing file).
o 'a': Append. Opens a file for appending (writes data to the end of the file).
o 'b': Binary mode. Used with other modes to handle binary files.
o 't': Text mode (default). Used for handling text files.
2. File Object: When you open a file, you get a file object that you can use to read from or write to the file.
3. Closing Files: Always close files after you're done using them to free up system resources. You can do this using the
close() method or by using a context manager (with statement).
Basic File Operations
1. Writing to a File
Here’s how to create a new file and write data to it:
# Writing to a file
with open('[Link]', 'w') as file:
[Link]("Hello, World!\n")
[Link]("This is a file I/O example.\n")
 This code creates (or overwrites) a file named [Link] and writes two lines of text to it.
 The with statement automatically closes the file when the block is exited.
2. Reading from a File
You can read the contents of a file using the following code:
# Reading from a file
with open('[Link]', 'r') as file:
content = [Link]() # Read the entire file
print(content) # Output: Contents of the file
 This reads the entire content of [Link] and prints it to the console.
3. Reading Line by Line
To read a file line by line, you can use a loop:
# Reading a file line by line
with open('[Link]', 'r') as file:
for line in file:
print([Link]()) # Output each line, stripping whitespace
4. Appending to a File
You can append new data to an existing file using the append mode 'a':
# Appending to a file
with open('[Link]', 'a') as file:
[Link]("Appending a new line to the file.\n")
Using Loops to Process Files :-
Using loops to process files in Python is a common way to read and manipulate data line by line. This method is
especially useful for handling large files, as it allows you to read one line at a time rather than loading the entire
file into memory.
Example: Reading a File Line by Line with a Loop
Here’s a simple example that demonstrates how to read a file using a loop:
Step 1: Create a Sample File
First, let’s create a sample text file named [Link] with some content:
# Writing sample data to a file
with open('[Link]', 'w') as file:
[Link]("Line 1: Hello, World!\n")
[Link]("Line 2: Python is great for file I/O.\n")
[Link]("Line 3: Loops can help process files efficiently.\n")
Step 2: Reading the File Using a Loop
Now, let’s read the content of [Link] line by line using a for loop:
# Reading the file line by line
with open('[Link]', 'r') as file:

for line in file:


print([Link]()) # Output each line without extra whitespace
Explanation
1. Writing to the File:
o We create a file called [Link] and write three lines of text to it.
2. Opening the File:
o We open the file in read mode ('r').
3. Using a Loop:
o We use a for loop to iterate over each line in the file.
The strip() method is used to remove any leading or trailing whitespace, including newline characters.
o
4. Printing Each Line:
o Each line is printed to the console.
Processing Records :-
Processing records in Python can be done in a straightforward manner, especially when dealing with structured data such as
CSV files. Let’s create a simple example that demonstrates how to read records from a CSV file, process the data, and display
the results.
Example: Processing a Simple CSV File
Step 1: Create a Sample CSV File
We’ll create a sample CSV file named [Link], which contains employee names and their salaries.
# Writing sample data to a CSV file
with open('[Link]', 'w') as file:
[Link]("Name,Salary\n")
[Link]("Alice,70000\n")
[Link]("Bob,80000\n")
[Link]("Charlie,60000\n")
[Link]("David,90000\n")
[Link]("Eve,75000\n")
Step 2: Processing the Records
Now, let’s write a script to read this file, calculate the average salary, and print each employee's name along with their salary.
# Reading and processing the CSV file
total_salary = 0
count = 0

with open('[Link]', 'r') as file:


next(file) # Skip the header row
for line in file:
name, salary = [Link]().split(',') # Split the line into name and salary
salary = int(salary) # Convert salary to an integer
total_salary += salary # Add to total salary
count += 1 # Increment the employee count
print(f"Employee: {name}, Salary: {salary}") # Print employee details

# Calculate and print the average salary


average_salary = total_salary / count if count > 0 else 0
print(f"Average Salary: ${average_salary:.2f}") # Output: Average Salary
Explanation
1. Writing the CSV File:
o We create a file called [Link] and write a header followed by employee records.
2. Reading and Processing:
o We open the file in read mode and skip the header using next(file).
o For each line in the file:
 We split the line into name and salary.
 Convert the salary from a string to an integer.
 Accumulate the total salary and count the number of employees.
 Print the employee’s name and salary.
3. Calculating the Average Salary:
o After processing all records, we calculate the average salary and print it.
Exceptions:-
Exceptions in Python are events that can modify the flow of a program when an error occurs. They allow you to handle errors
gracefully instead of crashing the program. Let’s explore the basics of exceptions with simple examples.
What are Exceptions?
An exception is raised when an error occurs during the execution of a program. Python has built
built-in exceptions, and you can
also define your own.
Basic Syntax for Exception Handling
To handle exceptions in Python, you typically use the try, except, and optionally finally statements. Here's the basic
structure:
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
finally:
# Code that runs no matter what (optional)
Simple Examples
Example 1: Handling Division by Zero
Let’s see a simple
imple example where we handle a division by zero error.
try:
numerator = 10
denominator = 0
result = numerator / denominator
print(f"Result: {result}")
except ZeroDivisionError:
print("Error:
"Error: Cannot divide by zero.")
zero."
Explanation:
 The code attempts to divide 10 by 0, which raises a ZeroDivisionError.
 The except block catches this specific exception and prints an error message.
Example 2: Catching Multiple Exceptions
You can catch multiple exceptions using a single except block or multiple blocks.
try:
number = int(input("Enter
"Enter a number: "))
" # May raise ValueError
result = 100 / number # May raise ZeroDivisionError
print(f"Result: {result}")
except ValueError:
print("Error:
"Error: Invalid input. Please enter a valid integer."
integer.")
except ZeroDivisionError:
print("Error:
"Error: Cannot divide by zero.")
zero."
Finally Block
The finally block is used for cleanup actions, and it runs regardless of whether an exception was raised or not.

try:
file = open('[Link]', 'r')
# Perform file operations
except FileNotFoundError:
print("Error: File not found.")
finally:
print("Executing finally block: Cleaning up.")
# Here you can close files or release resources

You might also like