Python_file-1
Python_file-1
Windows:
3. Important: Check the box that says "Add Python to PATH" during
installation. This allows you to run Python from the command line.
macOS:
Linux:
2. You can use your distribution's package manager (e.g., apt for
Ubuntu/Debian, yum for Fedora/CentOS) to install or update Python.
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:
In the "System variables" section, find the "Path" variable and click
"Edit."
macOS/Linux:
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 code can be written and executed in various ways. Two popular and
powerful tools are VS Code and Jupyter Notebook.
Python file 2
To use VS Code for Python:
Jupyter Notebook:
Python
print("Welcome to Python!")
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)
Comments: Comments are used to explain code. They are ignored by the
Python interpreter.
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")
Example output:
My name is John Doe and I am 30 years old.
Python file 4
Open your terminal or command prompt.
Run the file using the command python your_file_name.py (e.g., python
my_script.py ).
In Python, you don't need to explicitly declare the data type of a variable;
it's automatically inferred.
They are case-sensitive (e.g., myVar and myvar are different variables).
Python
my_name = "Alice"
age = 25
pi = 3.14159
is_student = True
Python file 5
Python
a = 10 # Integer
b = 2.5 # Float
name = "Alice" # String
is_valid = True # 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)
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).
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.")
3.1 Operators
Operators are symbols that perform operations on values (operands). Python
supports various types of operators.
+ : Addition
: Subtraction
: Multiplication
* : 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
+= : 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.
Python
z = 10
z += 5 # z is now 15
z -= 3 # z is now 12
z *= 2 # z is now 24
print(z)
== : Equal to
!= : Not equal to
Python
Python file 8
a=5
b = 10
not : Returns True if the operand is False , and False if the operand is True .
Python
x = True
y = False
age = 25
income = 50000
Ask the user to enter two numbers and the operation they want to
perform.
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."
The if statement checks a condition. If the condition is True , the code block
inside the if statement is executed.
The else statement is executed if none of the previous conditions are True .
Python file 10
else:
print("You are not eligible to drive.")
Use if , elif , and else to assign a grade based on the following criteria:
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(start, stop) : Generates numbers from start up to (but not including) stop .
Python
for i in range(5): # Generates 0, 1, 2, 3, 4
print(i)
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
Python file 12
print(f"Count is: {count}")
count += 1
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.
The outer loop iterates through the numbers for which you want to
generate the table.
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 + "!")
result = add(5, 3)
print(result) # Output: 8
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)
1. Write a function called factorial that takes an integer as input and returns
its factorial.
Python file 15
Lists can contain items of different data types.
Python
my_list = [1, 2, 3, "hello", 3.14]
fruits = ["apple", "banana", "cherry"]
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
: Removes and returns the item at the specified index (or the last
pop(index)
count(item) : Returns the number of times the item appears 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)
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]
Python
squares = [x**2 for x in range(10)] # Creates a list of squares from 0 to 9
print(squares)
Python file 17
Iterate through the string and update the count for each character in the
dictionary.
Create a list of tuples where each tuple contains two numbers (e.g., [(1,
Use the sort() method with a lambda function as the key to sort the list
based on the second element of each tuple.
Strings are created using single quotes ( '...' ) or double quotes ( "..." ).
Python
single_quoted = 'Hello'
double_quoted = "World"
multi_line = """This is a
multi-line
string."""
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
Python
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
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))
find(substring) : Returns the index of the first occurrence of the substring (or -1
if not found).
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
Python file 20
open(filename, mode) : Opens the file.
The with statement automatically closes the file, even if errors occur.
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.
Python file 21
: Writes a list of strings to the file. Note that it does not
file.writelines(list_of_strings)
1. Write a program to read a text file and print its contents line by line.
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.
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
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.")
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.
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!")
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.
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
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")
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}")
def display_research(self):
print(f"Research Area: {self.research_area}")
Python file 26
: Provides functions for interacting with the operating system (e.g., file
os
system operations).
# 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)
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.
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.")
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.
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