Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python_file-1

This document is a comprehensive guide to Python programming, covering installation, environment setup, and basic programming concepts. It includes instructions for using popular tools like VS Code and Jupyter Notebook, as well as explanations of variables, data types, operators, and control flow statements. Additionally, it provides practice exercises to reinforce learning.

Uploaded by

Kartik Sharma
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)
3 views

Python_file-1

This document is a comprehensive guide to Python programming, covering installation, environment setup, and basic programming concepts. It includes instructions for using popular tools like VS Code and Jupyter Notebook, as well as explanations of variables, data types, operators, and control flow statements. Additionally, it provides practice exercises to reinforce learning.

Uploaded by

Kartik Sharma
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/ 29

Python file

Page 1: Python Setup and Basics


Introduction
Welcome to the world of Python programming! This guide will take you through
the essentials of Python, from setting up your environment to building practical
applications. Python is a versatile and beginner-friendly language, widely used
in web development, data analysis, artificial intelligence, and more.
1.1 Installing Python
To begin, you'll need to install Python on your computer.

Windows:

1. Go to the official Python website (python.org) and download the latest


version for Windows.

2. Run the installer.

3. Important: Check the box that says "Add Python to PATH" during
installation. This allows you to run Python from the command line.

4. Follow the installation instructions.

macOS:

1. Python usually comes pre-installed on macOS, but it might be an older


version. You can install the latest version from python.org, similar to
Windows.

2. Alternatively, you can use a package manager like Homebrew to install


Python.

Linux:

1. Python is typically pre-installed on most Linux distributions.

2. You can use your distribution's package manager (e.g., apt for
Ubuntu/Debian, yum for Fedora/CentOS) to install or update Python.

1.2 Setting Up Environment Variables

Python file 1
Environment variables store settings that are accessible to the operating
system and applications. The PATH variable is crucial for running Python from
the command line.

Windows:

1. If you checked "Add Python to PATH" during installation, this is usually


done automatically.

2. To verify or add it manually:

Search for "Edit the system environment variables" in the Start


menu.

Click on "Environment Variables."

In the "System variables" section, find the "Path" variable and click
"Edit."

Click "New" and add the path to your Python executable


(e.g., C:\Python39 ).

Click "OK" to save the changes.

macOS/Linux:

The PATH is usually set automatically during installation.

You can check it by opening a terminal and typing echo $PATH .

If you need to modify it, you can edit your shell's configuration file
(e.g., ~/.bashrc or ~/.zshrc ) and add a line like export
PATH="/usr/local/bin/python3:$PATH" (adjust the path as needed).

Python Setup and Basics (Continued)


1.3 Using VS Code and Jupyter Notebook

Python code can be written and executed in various ways. Two popular and
powerful tools are VS Code and Jupyter Notebook.

VS Code (Visual Studio Code):

A free and highly customizable code editor developed by Microsoft.

Provides excellent support for Python development, including syntax


highlighting, debugging, and integrated terminal.

Python file 2
To use VS Code for Python:

1. Download and install VS Code from code.visualstudio.com.

2. Install the Python extension from the VS Code Marketplace.

3. Create a new file with a .py extension (e.g., my_script.py ).

4. Write your Python code and run it by pressing Ctrl+Shift+B (or


Cmd+Shift+B on macOS) or by right-clicking and selecting "Run
Python File in Terminal."

Jupyter Notebook:

An interactive environment that allows you to mix code, text, and


visualizations in a single document.

Great for learning, experimenting, and data analysis.

To use Jupyter Notebook:

1. Install Jupyter using pip: pip install jupyter

2. Open a terminal, navigate to the directory where you want to create


your notebook, and run jupyter notebook .

3. This will open Jupyter Notebook in your web browser.

4. Create a new Python 3 notebook.

5. Write and execute code in cells.

1.4 Your First Python Program


Let's write a simple Python program to print a message to the console:

Python
print("Welcome to Python!")

print() is a built-in function that displays output.

The text "Welcome to Python!" is a string, enclosed in double quotes.

To run this code:

In VS Code: Save the file (e.g., hello.py ) and run it in the terminal.

In Jupyter Notebook: Type the code in a cell and press Shift+Enter to execute
it.

Python file 3
Python Setup and Basics (Continued)

1.5 Indentation, Whitespace, and Comments

Indentation: Python uses indentation (spaces or tabs) to define code


blocks. This is crucial for control flow (if statements, loops, functions).
Consistent indentation is essential; mixing spaces and tabs can cause
errors. The standard is to use 4 spaces per indentation level.

Whitespace: Whitespace (spaces, tabs, newlines) is used to improve code


readability. Python ignores extra whitespace, but it's important to use it
consistently.

Comments: Comments are used to explain code. They are ignored by the
Python interpreter.

Single-line comments start with a # .

Multi-line comments can be created using triple quotes ( """ or ''' ).

Python
# This is a single-line comment
print("Hello") # This comment is at the end of a line

"""
This is a
multi-line comment.
It can span multiple lines.
"""

def my_function():
# This line is indented (4 spaces)
print("Inside the function")

Python Setup and Basics (Practice)

1.6 Practice Exercises

1. Write a program to print your name and age.

Example output:
My name is John Doe and I am 30 years old.

2. Create a Python file and run it from the command line.

Write any simple Python code in a file (e.g., a print statement).

Save the file with a .py extension (e.g., my_script.py ).

Python file 4
Open your terminal or command prompt.

Navigate to the directory where you saved the file using


the cd command.

Run the file using the command python your_file_name.py (e.g., python

my_script.py ).

Page 5: Variables and Data Types


2.1 Variables

Variables are used to store data in a program.

A variable is like a named container that holds a value.

In Python, you don't need to explicitly declare the data type of a variable;
it's automatically inferred.

Variable names must follow certain rules:

They must start with a letter (a-z, A-Z) or an underscore (_).

They can contain letters, numbers, and underscores.

They are case-sensitive (e.g., myVar and myvar are different variables).

It's good practice to use descriptive variable names.

Python
my_name = "Alice"
age = 25
pi = 3.14159
is_student = True

Variables and Data Types (Continued)

2.2 Data Types

Python has several built-in data types:

Integers (int): Whole numbers (e.g., 10, -5, 0).

Floats (float): Decimal numbers (e.g., 3.14, -2.5, 0.0).

Strings (str): Sequences of characters (e.g., "Hello", 'Python'). Strings can


be enclosed in either single or double quotes.

Booleans (bool): Represent truth values: True or False .

Python file 5
Python
a = 10 # Integer
b = 2.5 # Float
name = "Alice" # String
is_valid = True # Boolean

print(type(a)) # Output: <class 'int'>


print(type(b)) # Output: <class 'float'>
print(type(name)) # Output: <class 'str'>
print(type(is_valid)) # Output: <class 'bool'>

The type() function is used to determine the data type of a variable.

Page 7: Variables and Data Types (Continued)

2.3 Type Conversion


You can convert data from one type to another using built-in functions:

int() : Converts a value to an integer.

float() : Converts a value to a float.

str() : Converts a value to a string.

bool() : Converts a value to a boolean.

Python
age_str = "25"
age = int(age_str) # Convert string to integer
height = 1.75
height_str = str(height) # Convert float to string
is_true = bool(1) # Convert integer to boolean (any non-zero is True, 0 is False)
is_false = bool(0)

print(age, type(age))
print(height_str, type(height_str))
print(is_true, type(is_true))
print(is_false)

Important Notes on Type Conversion:

Converting a float to an integer truncates the decimal part


(e.g., int(3.9) becomes 3 ).

Converting a string to a number will raise a ValueError if the string does not
represent a valid number (e.g., int("abc") will cause an error).

Page 8: Variables and Data Types (Practice)

2.4 Practice Exercises

1. Take input of name and age from the user and print a greeting.

Python file 6
Use the input() function to get user input.

Example:Python
name = input("Enter your name: ")
age = input("Enter your age: ")
print("Hello, " + name + "! You are " + age + " years old.")

2. Convert a string to an int and a float, and demonstrate the differences.

Create a string variable that represents a number with a decimal (e.g.,


"12.34").

Convert it to an integer and a float.

Print the original string, the integer, and the float.

Explain what happened during the integer conversion.

Page 9: Operators and Expressions

3.1 Operators
Operators are symbols that perform operations on values (operands). Python
supports various types of operators.

Arithmetic Operators: Used for mathematical calculations.

Assignment Operators: Used to assign values to variables.

Comparison Operators: Used to compare values.

Logical Operators: Used to combine or modify conditions.

Bitwise Operators: Used for bit-level operations (less common in basic


programming).

3.2 Arithmetic Operators

+ : Addition

: Subtraction

: Multiplication

/ : Division (always returns a float)

// : Floor division (returns the integer part of the division)

% : Modulus (remainder of the division)

* : Exponentiation (power)

Python

Python file 7
x = 10
y=3

print(x + y) # Output: 13
print(x - y) # Output: 7
print(x * y) # Output: 30
print(x / y) # Output: 3.3333333333333335
print(x // y) # Output: 3
print(x % y) # Output: 1
print(x ** y) # Output: 1000

Page 10: Operators and Expressions (Continued)


3.3 Assignment Operators

= : Assigns the value on the right to the variable on the left.

+= : Adds the right operand to the left operand and assigns the result to the
left operand (e.g., x += 5 is equivalent to x = x + 5 ).

= : Subtracts the right operand from the left operand and assigns the result.

= , /= , //= , %= , *= : Similar to += but for other arithmetic operations.

Python
z = 10
z += 5 # z is now 15
z -= 3 # z is now 12
z *= 2 # z is now 24
print(z)

Page 11: Operators and Expressions (Continued)


3.4 Comparison Operators

== : Equal to

!= : Not equal to

> : Greater than

< : Less than

>= : Greater than or equal to

<= : Less than or equal to

Comparison operators return a boolean value ( True or False ).

Python

Python file 8
a=5
b = 10

print(a == b) # Output: False


print(a != b) # Output: True
print(a > b) # Output: False
print(a < b) # Output: True
print(a >= b) # Output: False
print(a <= b) # Output: True

Page 12: Operators and Expressions (Continued)


3.5 Logical Operators

and : Returns True if both operands are True .

or : Returns True if at least one operand is True .

not : Returns True if the operand is False , and False if the operand is True .

Python
x = True
y = False

print(x and y) # Output: False


print(x or y) # Output: True
print(not x) # Output: False
print(not y) # Output: True

age = 25
income = 50000

is_eligible = age > 18 and income > 30000


print(is_eligible)

Page 13: Operators and Expressions (Practice)


3.6 Practice Exercises

1. Write a calculator that performs +, -, *, /, %, **.

Ask the user to enter two numbers and the operation they want to
perform.

Use if-elif-else statements to determine which operation to carry out.

Print the result.

2. Use logical operators to compare age and income.

Ask the user to enter their age and income.

Check if the user is both older than 18 and has an income greater than
$30,000.

Python file 9
Print "Eligible" if both conditions are true, otherwise print "Not Eligible."

Page 14: Control Flow Statements


4.1 if , elif , else Statements
Control flow statements allow you to execute different blocks of code based on
conditions. The if statement is the most basic control flow statement.
Python
score = 85

if score > 90:


print("Excellent")
elif score > 80:
print("Very Good")
elif score > 70:
print("Good")
else:
print("Average")

The if statement checks a condition. If the condition is True , the code block
inside the if statement is executed.

The elif (else if) statement checks an additional condition if the


previous if or elif condition was False .

The else statement is executed if none of the previous conditions are True .

Page 15: Control Flow Statements (Continued)

4.2 Indentation and Code Blocks


Indentation is crucial in Python. It defines the code blocks that belong
to if , elif , else , loops, and functions. Code within the same block must have the
same indentation level (usually 4 spaces).
4.3 Nested if Statements
You can put if statements inside other if statements to create nested
conditions.
Python
age = 20
has_license = True

if age >= 18:


if has_license:
print("You are eligible to drive.")
else:
print("You are old enough to drive, but you need a license.")

Python file 10
else:
print("You are not eligible to drive.")

Page 16: Control Flow Statements (Practice)


4.4 Practice Exercises

1. Check if a number is positive, negative, or zero.

Ask the user to enter a number.

Use if , elif , and else to determine if the number is positive, negative, or


zero.

Print the corresponding message.

2. Create a grade evaluation system based on marks.

Ask the user to enter their marks.

Use if , elif , and else to assign a grade based on the following criteria:

Marks > 90: "A+"

80 < Marks <= 90: "A"

70 < Marks <= 80: "B"

60 < Marks <= 70: "C"

Marks <= 60: "Fail"

Print the grade.

Page 17: Loops - for Loop


5.1 for Loop
The for loop is used to iterate over a sequence (like a list, tuple, string) or other
iterable objects.
Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

In this example, the loop iterates through each element in the fruits list, and
the fruit variable takes on the value of each element in turn.
5.2 range() Function

Python file 11
The range() function is often used with for loops to iterate a specific number of
times. It generates a sequence of numbers.

range(stop) : Generates numbers from 0 up to (but not including) stop .

range(start, stop) : Generates numbers from start up to (but not including) stop .

: Generates numbers from


range(start, stop, step) start up to (but not
including) stop , with a step of step .

Python
for i in range(5): # Generates 0, 1, 2, 3, 4
print(i)

for i in range(2, 7): # Generates 2, 3, 4, 5, 6


print(i)

for i in range(0, 10, 2): # Generates 0, 2, 4, 6, 8


print(i)

Page 18: Loops - for Loop (Continued)

5.3 break and continue Statements

break: Immediately terminates the loop and the program control flows to the
statement immediately following the loop.

continue : Skips the rest of the code inside the current iteration of the loop
and proceeds to the next iteration.

Python
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
break # Exit the loop when num is 3
print(num) # Output: 1, 2

for num in numbers:


if num == 3:
continue # Skip the rest of this iteration when num is 3
print(num) # Output: 1, 2, 4, 5

Page 19: Loops - while Loop


5.4 while Loop

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


Python
count = 0
while count < 5:

Python file 12
print(f"Count is: {count}")
count += 1

It's important to ensure that the condition in a while loop eventually


becomes False to avoid an infinite loop.
Page 20: Loops - Nested Loops
5.5 Nested Loops
You can have one loop inside another loop. The inner loop will execute
completely for each iteration of the outer loop.
Python
for i in range(3):
for j in range(2):
print(f"({i}, {j})")
# Output:
# (0, 0)
# (0, 1)
# (1, 0)
# (1, 1)
# (2, 0)
# (2, 1)

Page 21: Loops (Practice)


5.6 Practice Exercises

1. Print all even numbers between 1 and 50.

Use a for loop with the range() function and an appropriate step, or use
a conditional statement ( if ) inside the loop to check for even numbers.

2. Make a multiplication table (e.g., for numbers 1 to 10) using a


nested for loop.

The outer loop iterates through the numbers for which you want to
generate the table.

The inner loop iterates from 1 to 10 (the multipliers).

Print the multiplication result in a clear format (e.g., "5 x 3 = 15").

Page 22: Functions and Scope


6.1 Defining Functions

Python file 13
A function is a block of organized, reusable code that performs a specific task.
You define functions using the def keyword.
Python
def greet(name):
"""This function greets the person passed in as a parameter."""
print("Hello, " + name + "!")

# Calling the function


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

def is the keyword to define a function.

greet is the name of the function.

name is a parameter (input) that the function accepts.

The docstring ( """...""" ) provides a description of the function's purpose.

The code inside the indented block is the function body.

Page 23: Functions and Scope (Continued)


6.2 Arguments and Return Values
Functions can accept arguments (inputs) and can return values (outputs) using
the return statement.
Python
def add(x, y):
"""This function returns the sum of two numbers."""
sum_result = x + y
return sum_result

result = add(5, 3)
print(result) # Output: 8

def get_full_name(first_name, last_name):


"""Returns the full name."""
full_name = first_name + " " + last_name
return full_name

name = get_full_name("Alice", "Smith")


print(name) # Output: Alice Smith

Page 24: Functions and Scope (Continued)


6.3 Local and Global Scope

Local Scope: Variables defined inside a function have local scope. They are
only accessible within that function.

Python file 14
Global Scope: Variables defined outside any function have global scope.
They can be accessed from anywhere in the program.

Python
global_var = 10

def my_func():
local_var = 5
print(local_var) # Accessible here
print(global_var) # Accessible here

my_func()
# print(local_var) # This would cause an error (local_var is not defined outside)
print(global_var)

another_global = 20
def another_func():
global another_global # To modify a global variable inside a function
another_global = 30
print(another_global)

another_func()
print(another_global) # Output: 30 (global variable was modified)

Page 25: Functions and Scope (Practice)


6.4 Practice Exercises

1. Write a function called factorial that takes an integer as input and returns
its factorial.

The factorial of a non-negative integer n is the product of all positive


integers less than or equal to n (e.g., 5! = 5 * 4 * 3 * 2 * 1 = 120).

2. Write a function called is_palindrome that takes a string as input and


returns True if the string is a palindrome (reads the same forwards and
backwards), and False otherwise.

Example: "madam" is a palindrome.

Page 26: Data Structures: Lists


7.1 Lists
A list is an ordered, mutable (changeable) collection of items. Lists are one of
the most commonly used data structures in Python.

Lists are created using square brackets [] .

Items in a list are separated by commas.

Python file 15
Lists can contain items of different data types.

Python
my_list = [1, 2, 3, "hello", 3.14]
fruits = ["apple", "banana", "cherry"]

7.2 Accessing List Elements

List elements are accessed using their index.

The index starts from 0 for the first element, 1 for the second element, and
so on.

You can also use negative indexing to access elements from the end of
the list (-1 for the last element, -2 for the second to last, etc.).

Python
print(my_list[0]) # Output: 1
print(my_list[3]) # Output: hello
print(fruits[-1]) # Output: cherry

Page 27: Data Structures: Lists (Continued)


7.3 List Methods

Lists have various built-in methods to modify and manipulate them:

append(item) : Adds an item to the end of the list.

insert(index, item) : Inserts an item at a specific index.

remove(item) : Removes the first occurrence of the item.

: Removes and returns the item at the specified index (or the last
pop(index)

item if no index is given).

sort() : Sorts the list in ascending order.

reverse() : Reverses the order of the list.

index(item) : Returns the index of the first occurrence of the item.

count(item) : Returns the number of times the item appears in the list.

len(list) : Returns the number of items in the list.

Python
fruits.append("orange") # Adds "orange" to the end
fruits.insert(1, "grape") # Inserts "grape" at index 1
fruits.remove("banana") # Removes "banana"
last_fruit = fruits.pop() # Removes and returns the last fruit

Python file 16
print(fruits)
print(last_fruit)

Page 28: Data Structures: Lists (Continued)


7.4 List Slicing
You can extract a portion of a list using slicing.

: Returns a new list containing elements from index


list[start:stop] start up to
(but not including) index stop .

: Returns a new list containing elements from index


list[start:] start to the end
of the list.

: Returns a new list containing elements from the beginning of the


list[:stop]

list up to (but not including) index stop .

list[start:stop:step] : Returns a new list containing elements from index start up to


(but not including) index stop , with a step of step .

Python
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5]) # Output: [2, 3, 4]
print(numbers[5:]) # Output: [5, 6, 7, 8, 9]
print(numbers[:3]) # Output: [0, 1, 2]
print(numbers[1:8:2]) # Output: [1, 3, 5, 7]

Page 29: Data Structures: Lists (Continued)


7.5 List Comprehensions (Introduction)
List comprehensions provide a concise way to create new lists based on
existing lists or other iterables.

Python
squares = [x**2 for x in range(10)] # Creates a list of squares from 0 to 9
print(squares)

even_numbers = [x for x in range(20) if x % 2 == 0] # Creates a list of even numbers


print(even_numbers)

Page 30: Data Structures: Lists (Practice)


7.6 Practice Exercises

1. Count the occurrences of each character in a string using a dictionary.

Ask the user to input a string.

Create an empty dictionary to store the character counts.

Python file 17
Iterate through the string and update the count for each character in the
dictionary.

Print the dictionary.

2. Sort a list of tuples by the second element.

Create a list of tuples where each tuple contains two numbers (e.g., [(1,

5), (3, 2), (8, 1)] ).

Use the sort() method with a lambda function as the key to sort the list
based on the second element of each tuple.

Page 31: Data Structures: Strings


8.1 Strings
A string is a sequence of characters. Strings are immutable, meaning you
cannot change individual characters within a string once it's created.

Strings are created using single quotes ( '...' ) or double quotes ( "..." ).

Multi-line strings can be created using triple quotes ( """...""" or '''...''' ).

Python
single_quoted = 'Hello'
double_quoted = "World"
multi_line = """This is a
multi-line
string."""

8.2 Accessing String Characters


Individual characters in a string can be accessed using their index, similar to
lists.
Python
my_string = "Python"
print(my_string[0]) # Output: P
print(my_string[3]) # Output: h
print(my_string[-1]) # Output: n

Page 32: Data Structures: Strings (Continued)


8.3 String Slicing

You can extract substrings using slicing, similar to lists.


Python

Python file 18
my_string = "Programming"
print(my_string[0:4]) # Output: Prog
print(my_string[4:]) # Output: ramming
print(my_string[:7]) # Output: Program
print(my_string[2:9:2]) # Output: oarm

8.4 String Formatting


String formatting allows you to embed expressions inside string literals.

f-strings (formatted string literals): Introduced in Python 3.6, they provide


a concise way to embed expressions.

Python
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")

.format() method: An older method for string formatting.

Python
print("My name is {} and I am {} years old.".format(name, age))
print("My name is {0} and I am {1} years old. My name again: {0}".format(name, age))

Page 33: Data Structures: Strings (Continued)


8.5 String Methods

Strings have many built-in methods for manipulation:

upper() : Returns the string in uppercase.

lower() : Returns the string in lowercase.

strip() : Removes leading and trailing whitespace.

split(separator) : Splits the string into a list of substrings based on the


separator.

: Concatenates elements of an iterable (like a list) into a string


join(iterable)

using the string as a separator.

find(substring) : Returns the index of the first occurrence of the substring (or -1
if not found).

replace(old, new) : Replaces all occurrences of old with new .

startswith(prefix) : Returns True if the string starts with the prefix.

endswith(suffix) : Returns True if the string ends with the suffix.

Python

Python file 19
text = " Python Programming "
print(text.upper()) # Output: PYTHON PROGRAMMING
print(text.lower()) # Output: python programming
print(text.strip()) # Output: Python Programming
words = text.split() # Output: ['Python', 'Programming']
joined_text = "-".join(words) # Output: Python-Programming
print(text.find("thon")) # Output: 4
print(text.replace("Python", "Java")) # Output: Java Programming
print(text.startswith(" ")) # Output: True
print(text.endswith(" ")) # Output: True

Page 34: Data Structures: Strings (Practice)


8.6 Practice Exercises

1. Reverse a given string.

Ask the user to input a string.

Use string slicing with a negative step to reverse the string.

Print the reversed string.

2. Count the number of vowels and consonants in a string.

Ask the user to input a string.

Initialize counters for vowels and consonants.

Iterate through the string, checking if each character is a vowel (a, e, i,


o, u) or a consonant.

Increment the respective counters.

Print the counts.

Page 35: File Handling


9.1 Reading Files
You can read data from files using Python. The open() function is used to open a
file.
Python
# Method 1: Using a context manager (recommended)
with open("my_file.txt", "r") as file:
content = file.read()
print(content)

# Method 2: Without a context manager (need to close the file manually)


file = open("another_file.txt", "r")
content = file.read()
print(content)
file.close()

Python file 20
open(filename, mode) : Opens the file.

"r" : Read mode (default).

"w" : Write mode (creates a new file or overwrites an existing one).

"a" : Append mode (adds to the end of the file).

"b" : Binary mode.

"+" : Updating mode (read and write).

The with statement automatically closes the file, even if errors occur.

file.read() : Reads the entire content of the file as a single string.

file.readline() : Reads one line from the file.

file.readlines() : Reads all lines into a list.

Page 36: File Handling (Continued)

9.2 Writing to Files


You can write data to files using Python.
Python
# Method 1: Writing with context manager (overwrites)
with open("output.txt", "w") as file:
file.write("Hello, file!\n")
file.write("This is another line.\n")

# Method 2: Appending with context manager (adds to the end)


with open("output.txt", "a") as file:
file.write("This line is appended.\n")

# Writing a list of lines


lines = ["First line\n", "Second line\n", "Third line\n"]
with open("lines.txt", "w") as file:
file.writelines(lines)

When opening a file in "w" mode, if the file exists, its contents are
overwritten. If it doesn't exist, a new file is created.

When opening a file in "a" mode, if the file exists, new data is added to the
end. If it doesn't exist, a new file is created.

file.write(string) : Writes the string to the file.

Python file 21
: Writes a list of strings to the file. Note that it does not
file.writelines(list_of_strings)

automatically add newline characters; you need to include them in the


strings.

Page 37: File Handling (Practice)


9.3 Practice Exercises

1. Write a program to read a text file and print its contents line by line.

Create a sample text file with a few lines of text.

Open the file in read mode ( "r" ).

Use a loop (e.g., a for loop iterating through the file object) to read and
print each line.

2. Write a program to take input from the user and save it to a new file.

Ask the user to enter some text.

Open a new file in write mode ( "w" ).

Write the user's input to the file.

Close the file.

Page 38: Exception Handling


10.1 try , except Blocks
Exception handling allows you to gracefully handle errors that might occur
during the execution of your program. The try block contains the code that
might raise an exception, and the except block specifies how to handle a
particular type of exception.
Python
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
result = numerator / denominator
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input. Please enter integers.")

If an exception occurs in the try block, the program execution immediately


jumps to the corresponding except block.

You can have multiple except blocks to handle different types of exceptions.

Python file 22
Page 39: Exception Handling (Continued)
10.2 else and finally Blocks

block: The code inside the


else else block is executed if no exceptions
were raised in the try block.

block: The code inside the finally block is always executed,


finally

regardless of whether an exception occurred or not. It's often used for


cleanup operations (e.g., closing files).

Python
try:
file = open("my_data.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("Error: File not found.")
else:
print("File read successfully.")
finally:
if 'file' in locals() and not file.closed:
file.close()
print("File closed.")

Page 40: Exception Handling (Continued)


10.3 Raising Exceptions
You can explicitly raise exceptions in your code using the raise keyword. This
can be useful for indicating errors or specific conditions.
Python
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
print("Age is valid:", age)

try:
user_age = int(input("Enter your age: "))
check_age(user_age)
except ValueError as e:
print("Error:", e)

Here, if the age is negative, a ValueError is raised with a custom error message.
The except block catches this specific exception and prints the error message.

Page 41: Object-Oriented Programming (OOP)


11.1 Classes and Objects

Python file 23
Object-Oriented Programming (OOP) is a programming paradigm that uses
"objects" to structure code. A class is a blueprint for creating objects. An object
is an instance of a class.
Python
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed

def bark(self):
print("Woof!")

# Creating objects (instances) of the Dog class


my_dog = Dog("Buddy", "Golden Retriever")
your_dog = Dog("Lucy", "Poodle")

print(my_dog.name) # Output: Buddy


print(your_dog.breed) # Output: Poodle
my_dog.bark() # Output: Woof!

class Dog: defines a new class named Dog .

is a special method called the constructor. It's


__init__(self, name, breed)

automatically called when an object is created. self refers to the instance of


the class being created.

self.name = name and self.breed = breed create attributes (data members) of the
object.

bark(self) is a method (function associated with the object) that defines the
behavior of the Dog object.

Page 42: Object-Oriented Programming (Continued)


11.2 Methods
Methods are functions defined within a class and are associated with the
objects of that class. They can access and modify the object's attributes.
Python
class Circle:
def __init__(self, radius):
self.radius = radius

def area(self):
return 3.14159 * self.radius ** 2

def circumference(self):
return 2 * 3.14159 * self.radius

Python file 24
my_circle = Circle(5)
print(f"Area: {my_circle.area()}") # Output: Area: 78.53975
print(f"Circumference: {my_circle.circumference()}") # Output: Circumference: 31.4159

Page 43: Object-Oriented Programming (Continued)


11.3 Inheritance
Inheritance allows you to create a new class (subclass or derived class) based
on an existing class (superclass or base class). 1 The subclass inherits the
attributes and methods of the superclass and 2 can also add its own.

Python
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
print("Generic animal sound")

class Cat(Animal):
def speak(self):
print("Meow!")

class Dog(Animal):
def speak(self):
print("Woof!")

my_animal = Animal("Generic")
my_cat = Cat("Whiskers")
my_dog = Dog("Buddy")

my_animal.speak() # Output: Generic animal sound


my_cat.speak() # Output: Meow!
my_dog.speak() # Output: Woof!

Here, Cat and Dog inherit from Animal and override the speak() method to
provide their specific sounds.
Page 44: Object-Oriented Programming (Continued)
11.4 Practice Exercises

1. Create a class Student with attributes name , age , and grade . Include a
method display_info() that prints the student's information.Python
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade

Python file 25
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}, Grade: {self.grade}")

student1 = Student("Alice", 16, "A")


student1.display_info()

2. Extend the Student class to create a subclass GraduateStudent that includes


an additional attribute research_area and a method display_research() that prints
the research area.Python
class GraduateStudent(Student):
def __init__(self, name, age, grade, research_area):
super().__init__(name, age, grade)
self.research_area = research_area

def display_research(self):
print(f"Research Area: {self.research_area}")

grad_student = GraduateStudent("Bob", 24, "A+", "Artificial Intelligence")


grad_student.display_info()
grad_student.display_research()

Page 45: Modules and Packages


12.1 Importing Modules
A module is a file containing Python definitions and statements. You can use
code from other modules by importing them.
Python
# Importing the entire module
import math
print(math.sqrt(16)) # Output: 4.0

# Importing specific functions from a module


from datetime import datetime
now = datetime.now()
print(now)

# Importing a module with an alias


import random as rnd
print(rnd.randint(1, 10))

Page 46: Modules and Packages (Continued)


12.2 Built-in Modules
Python has many useful built-in modules:

math : Provides mathematical functions (e.g., sqrt , sin , cos ).

random : For generating random numbers.

datetime : For working with dates and times.

Python file 26
: Provides functions for interacting with the operating system (e.g., file
os

system operations).

sys : Provides access to system-specific parameters and functions.

12.3 Practice Exercises

1. Create a module named my_math_functions.py containing functions for


addition, subtraction, multiplication, and division. Then, import and use
these functions in another Python script.Python
# my_math_functions.py
def add(x, y):
return x + y

def subtract(x, y):


return x - y

# main_script.py
import my_math_functions

result_add = my_math_functions.add(5, 3)
print(f"Addition: {result_add}")

2. Explore the os module. Write a script to list all files and directories in the
current working directory.Python
import os

current_dir = os.getcwd()
print(f"Current directory: {current_dir}")
items = os.listdir(current_dir)
print("Files and directories:")
for item in items:
print(item)

Page 47: Project 1: To-Do List CLI App


14.1 Features
Let's start building a simple command-line interface (CLI) to-do list application.
It will have the following features:

Add tasks: Allow users to add new tasks to the list.

View tasks: Display the current list of tasks with their index numbers.

Delete tasks: Allow users to remove tasks from the list based on their
index.

14.2 Data Storage

Python file 27
For simplicity, we'll store the to-do list in a Python list in memory. When the
application closes, the data will be lost. In a later iteration, we can explore
saving the data to a file for persistence.
Page 48: Project 1: To-Do List CLI App (Continued)
14.3 Implementation (Basic)
Python
todo_list = []

def add_task(task):
todo_list.append(task)
print(f"Task '{task}' added.")

def view_tasks():
if not todo_list:
print("Your to-do list is empty.")
else:
print("To-Do List:")
for index, task in enumerate(todo_list):
print(f"{index + 1}. {task}")

def delete_task(index):
try:
index = int(index) - 1
if 0 <= index < len(todo_list):
deleted_task = todo_list.pop(index)
print(f"Task '{deleted_task}' deleted.")
else:
print("Invalid task number.")
except ValueError:
print("Invalid input. Please enter a number.")

while True:
print("\nOptions: add | view | delete | exit")
action = input("Enter action: ").lower()

if action == 'add':
task = input("Enter task to add: ")
add_task(task)
elif action == 'view':
view_tasks()
elif action == 'delete':
index = input("Enter task number to delete: ")
delete_task(index)
elif action == 'exit':
print("Exiting application.")
break
else:
print("Invalid action. Please try again.")

Page 49: Project 1: To-Do List CLI App (Continued)

Python file 28
14.4 User Interaction and Prompts
The code above uses simple input() prompts to get user actions and task
descriptions. The output is printed to the console using print() .
14.5 File Persistence (Enhancement)
To make the to-do list persistent, you can modify the application to save
the todo_list to a file (e.g., a text file where each line is a task) when the program
exits and load the tasks from the file when the program starts. You would need
to implement functions to read from and write to the file.
Page 50: Project 1: To-Do List CLI App (Further Enhancements)
You can further enhance this application with features like:

Marking tasks as complete: Add a status (e.g., "[ ]" for incomplete, "[x]"
for complete) to each task.

Editing tasks: Allow users to modify existing tasks.

Saving to different file formats: Explore saving the data in CSV or JSON
format.

Better error handling: Implement more robust error checking for user input.

Python file 29

You might also like