Structure of a Python Program:
1. Documentation
2. Import Statements
3. Global Variables
4. Function Definitions
5. Main Program Execution
1. Comments and Documentation
Comments describe what the code does, improving readability.
Documentation helps others understand the purpose of the program
or function.
In the example, comments explain the program's purpose and what
each function does.
2. Import Statements
Import statements bring in external libraries to extend functionality.
They are typically placed at the top of the file for easy access.
In the example, the math module is imported, even though it isn't
used.
3. Global Variables
Global variables store values used throughout the program.
They are defined outside functions so they can be accessed
anywhere.
The PI variable in the example is a global constant for
demonstration.
4. Function Definitions
Functions are blocks of code that perform specific tasks.
They help break down the program into smaller, reusable pieces.
The example defines functions for addition, subtraction,
multiplication, and division.
5. Main Program Execution
The main section contains the program's core logic.
It runs when the script is executed directly.
In the example, user input is collected, and the appropriate function
is called based on the user’s choice.
Eg:
# Comments and Documentation
# This program demonstrates the structure of a Python program
# It performs basic arithmetic operations: addition, subtraction,
multiplication, and division.
# Import Statements
import math # Example import (not used in this program but
demonstrates structure)
# Global Variables
PI = 3.14159 # Example global variable
# Function Definitions
def add(a, b):
"""Returns the sum of a and b"""
return a + b
def subtract(a, b):
"""Returns the difference between a and b"""
return a - b
def multiply(a, b):
"""Returns the product of a and b"""
return a * b
def divide(a, b):
"""Returns the division of a by b"""
if b != 0:
return a / b
else:
return "Error! Division by zero."
# Main Program Execution
if __name__ == "__main__":
# Display Menu
print("Simple Calculator")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
# User Input
choice = int(input("Enter your choice (1-4): "))
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Perform Operation
if choice == 1:
print("Result:", add(num1, num2))
elif choice == 2:
print("Result:", subtract(num1, num2))
elif choice == 3:
print("Result:", multiply(num1, num2))
elif choice == 4:
print("Result:", divide(num1, num2))
else:
print("Invalid choice!")
intha program eh arithmetic calculator ku use panniko dude
Methods to Exit a Function in Python
1. Using return
o Exits the function immediately and optionally returns a value.
o Syntax:
return [expression]
2. Using exit() or sys.exit()
o Terminates the entire program, not just the function.
o Requires the sys module for sys.exit().
o Syntax:
import sys
exit() # or sys.exit()
3. Using raise
o Exits the function by raising an exception.
o Syntax:
raise ExceptionType("Message")
4. Reaching the End of the Function
o If no explicit return is given, the function exits automatically
when it reaches the end. By default, it returns None.
o Syntax:
def my_function():
# Some code
pass
Syntax for find() Function
The find() method is used in strings to locate the index of the first
occurrence of a substring. If the substring is not found, it returns -1.
Syntax:
string.find(substring, start, end)
Parameters:
1. substring (required): The substring to search for.
2. start (optional): The starting index for the search. Default is 0.
3. end (optional): The ending index for the search. Default is the length
of the string.
Example:
text = "Hello, world!"
index = text.find("world")
print(index) # Output: 7
list operations
1. Creating a List
Lists can be created using square brackets [], and they can hold elements
of any data type.
Syntax:
my_list = [element1, element2, element3]
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits) # Output: ['apple', 'banana', 'cherry']
2. Accessing Elements
You can access elements using their index. Python supports both positive
and negative indexing.
Syntax:
list[index]
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: 'apple' (positive indexing)
print(fruits[-1]) # Output: 'cherry' (negative indexing)
3. Slicing a List
Retrieve a subset of elements using slicing with a start, stop, and optional
step.
Syntax:
list[start:stop:step]
Example:
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4]) # Output: [2, 3, 4]
print(numbers[::2]) # Output: [1, 3, 5]
4. Modifying Elements
Change the value of a specific element by accessing it through its index.
Syntax:
list[index] = new_value
Example:
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits) # Output: ['apple', 'blueberry', 'cherry']
5. Adding Elements
Add new elements to the list using append(), insert(), or extend().
append(): Adds an element to the end of the list.
list.append(element)
Example:
fruits.append("orange")
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
insert(): Inserts an element at a specific index.
list.insert(index, element)
Example:
fruits.insert(1, "mango")
print(fruits) # Output: ['apple', 'mango', 'banana', 'cherry']
extend(): Adds elements of another list to the current list.
list.extend(another_list)
Example:
fruits.extend(["pineapple", "grapes"])
print(fruits) # Output: ['apple', 'banana', 'cherry', 'pineapple', 'grapes']
6. Removing Elements
Remove elements using remove(), pop(), or del.
remove(): Removes the first occurrence of a specified value.
list.remove(element)
Example:
fruits.remove("banana")
print(fruits) # Output: ['apple', 'cherry']
pop(): Removes and returns the element at the specified index.
list.pop(index)
Example:
fruits.pop(1)
print(fruits) # Output: ['apple', 'cherry']
del: Deletes an element or the entire list.
del list[index]
Example:
del fruits[0]
print(fruits) # Output: ['banana', 'cherry']
7. Sorting a List
Sort the list elements in ascending or descending order.
Syntax:
list.sort() # Ascending
list.sort(reverse=True) # Descending
Example:
numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers) # Output: [1, 2, 5, 9]
numbers.sort(reverse=True)
print(numbers) # Output: [9, 5, 2, 1]
9. Reversing a List
Reverse the order of elements in a list.
Syntax:
list.reverse()
Example:
fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits) # Output: ['cherry', 'banana', 'apple']
10. Copying a List
Create a shallow copy of a list using copy() or slicing.
Syntax:
new_list = list.copy()
Example:
fruits = ["apple", "banana"]
new_fruits = fruits.copy()
print(new_fruits) # Output: ['apple', 'banana']
11. Clearing a List
Remove all elements from the list.
Syntax:
list.clear()
Example:
fruits = ["apple", "banana"]
fruits.clear()
print(fruits) # Output: []
13. Joining Lists
Concatenate multiple lists using the + operator.
Syntax:
new_list = list1 + list2
Example:
list1 = [1, 2]
list2 = [3, 4]
result = list1 + list2
print(result) # Output: [1, 2, 3, 4]
Python Files
In Python, files are used to store and manipulate data. Files provide a way
to work with external data and allow data persistence. Python supports
working with text files (plain text or structured data) and binary files
(images, videos, etc.).
Types of Files in Python
1. Text Files
o Files that contain readable characters like letters, numbers, or
special characters.
o Examples: .txt, .csv, .log.
o Data is stored in human-readable format.
Example:
text
Copy code
Hello, World!
This is a text file.
2. Binary Files
o Files that contain data in binary (0s and 1s) format.
o Examples: .png, .jpg, .mp3.
o Data is not human-readable and is suitable for computer
processing.
Example:
A binary file of an image or audio stored in encoded format.
Common File Operations
Python provides various functions and methods to work with files. These
include creating, reading, writing, and deleting files.
1. Opening a File
Use the open() function to open a file. It requires a filename and mode.
Syntax:
python
Copy code
file = open(filename, mode)
Modes for Opening Files:
Mod
Description
e
'r' Read mode (default). Opens file for reading.
Write mode. Overwrites if file exists; creates if
'w'
not.
Append mode. Adds new data at the end of the
'a'
file.
'b' Binary mode (e.g., 'rb', 'wb').
'x' Create mode. Fails if file exists.
Example:
python
Copy code
file = open("example.txt", "r")
2. Reading a File
Read the content of a file using methods like read(), readline(), and
readlines().
read(): Reads the entire content of the file.
Syntax:
python
Copy code
content = file.read()
Example:
python
Copy code
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
readline(): Reads one line at a time.
Syntax:
python
Copy code
line = file.readline()
Example:
python
Copy code
file = open("example.txt", "r")
line = file.readline()
print(line)
file.close()
readlines(): Reads all lines as a list.
Syntax:
python
Copy code
lines = file.readlines()
Example:
python
Copy code
file = open("example.txt", "r")
lines = file.readlines()
print(lines)
file.close()
3. Writing to a File
Write content to a file using the write() or writelines() methods.
write(): Writes a string to the file.
Syntax:
python
Copy code
file.write(string)
Example:
python
Copy code
file = open("example.txt", "w")
file.write("This is a new file.\n")
file.close()
writelines(): Writes a list of strings to the file.
Syntax:
python
Copy code
file.writelines(list_of_strings)
Example:
python
Copy code
file = open("example.txt", "w")
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file.writelines(lines)
file.close()
7. Checking File Existence
Use the os module to check if a file exists.
Example:
python
Copy code
import os
if os.path.exists("example.txt"):
print("File exists.")
else:
print("File does not exist.")
Functions for File Operations
1. open(): Opens a file in the specified mode.
2. read(), readline(), readlines(): Reads data from a file.
3. write(): Writes a string to a file.
4. writelines(): Writes multiple lines to a file.
5. close(): Closes the file.
6. flush(): Flushes the file buffer, forcing the write to disk.
7. tell(): Returns the current file position.
8. seek(): Moves the file cursor to a specific position.
Example: File Operations
python
Copy code
# Writing to a file
with open("example.txt", "w") as file:
file.write("Python File Handling Example.\n")
file.write("This is a new file.\n")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print("File Content:")
print(content)
# Appending to a file
with open("example.txt", "a") as file:
file.write("This line is appended.\n")
# Reading updated file
with open("example.txt", "r") as file:
print("Updated Content:")
print(file.read())
Output:
text
Copy code
File Content:
Python File Handling Example.
This is a new file.
Updated Content:
Python File Handling Example.
This is a new file.
This line is appended.