Python
Python
1. Installing Python:
b. Run Installer: Once the download is complete, run the installer. Make sure
to check the box that says "Add Python to PATH" during the installation
process. This will allow you to run Python from the command prompt.
You can start writing and running Python code directly in the interpreter. For
example:
>>> print("Hello, world!")
Hello, world!
c. Interactive Learning:
You can use the interpreter to experiment with Python features and learn
interactively. Try out different expressions, calculations, and statements. For
example:
Hello, Alice
To exit the Python interpreter, simply type exit() or press Ctrl + Z (Windows)
or Ctrl + D (macOS/Linux).
You can also write Python programs in separate files and run them using the
command prompt. Here's a simple example:
Open a text editor like Notepad (Windows), TextEdit (macOS), or any code
editor you prefer.
Write your Python program in the text editor. For example, let's create a
simple program that calculates the sum of two numbers and prints the result:
Open a command prompt or terminal and navigate to the directory where you
saved the sum.py file. Then, run the program by typing python sum.py or python3
sum.py and pressing Enter.
This will execute the program and you'll see the output and any interactions
specified in the code.
# Strings
print("String:", my_string)
print("Indexing:", my_string[0])
print("Slicing:", my_string[7:])
print("Repetition:", my_string * 3)
# Lists
my_list = [1, 2, 3, 4, 5]
print("\nList:", my_list)
print("Indexing:", my_list[0])
print("Slicing:", my_list[1:4])
print("Repetition:", my_list * 2)
# Tuples
print("\nTuple:", my_tuple)
print("Indexing:", my_tuple[0])
print("Slicing:", my_tuple[1:])
# Dictionaries
print("\nDictionary:", my_dict)
print("Indexing:", my_dict["name"])
new_data = {"gender": "Female"}
my_dict.update(new_data)
# Sets
my_set = {1, 2, 3, 4, 5}
print("\nSet:", my_set)
print("Membership:", 3 in my_set)
print("Union:", new_set)
Output :-
Indexing: H
Slicing: World!
List: [1, 2, 3, 4, 5]
Indexing: 1
Slicing: [2, 3, 4]
Concatenation: [1, 2, 3, 4, 5, 6, 7]
Repetition: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
Indexing: 10
Indexing: Alice
Updated Dictionary: {'name': 'Alice', 'age': 25, 'city': 'New York', 'gender':
'Female'}
Set: {1, 2, 3, 4, 5}
Membership: True
Union: {1, 2, 3, 4, 5, 6, 7
Q3. Solve problems using decision and looping statements.
import random
print("I'm thinking of a number between 1 and 100. Can you guess it?")
attempts = 0
max_attempts = 10
attempts += 1
print("Too low.")
print("Too high.")
else:
print(f"Congratulations! You've guessed the number {target_number} in
{attempts} attempts.")
break
Output :-
I'm thinking of a number between 1 and 100. Can you guess it?
Too low.
Too high.
Too low.
Q4. Handle numerical operations using math and random number
functions.
import math
import random
random_sqrt = math.sqrt(random_number)
Output :-
# Positional Arguments
# Default Argument
return area
# Variable-Length Arguments
def add_numbers(*args):
total = sum(args)
return total
# Keyword Arguments
print("Hobbies:", hobbies)
greet("Alice", 30)
area = calculate_area(10)
area_custom = calculate_area(10, 8)
sum_result = add_numbers(1, 2, 3)
Output :-
Q6. Perform File manipulations- open, close, read, write, append and
copy from one file to another.
content = file.read()
print("Read content:\n", content)
content = source_file.read()
dest_file.write(content)
copied_content = file.read()
Output:-
Read content:
Copied content:
def print_matrix(matrix):
print(row)
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix1[0])):
row.append(matrix1[i][j] + matrix2[i][j])
result.append(row)
return result
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix2[0])):
value = 0
for k in range(len(matrix2)):
row.append(value)
result.append(row)
return result
def identity_matrix(n):
identity = []
for i in range(n):
row = [0] * n
row[i] = 1
identity.append(row)
return identity
# Example matrices
print("Matrix A:")
print_matrix(matrix_A)
print("\nMatrix B:")
print_matrix(matrix_B)
# Matrix Addition
print("\nMatrix Addition:")
print_matrix(result_addition)
# Matrix Multiplication
result_multiplication = multiply_matrices(matrix_A, matrix_B)
print("\nMatrix Multiplication:")
print_matrix(result_multiplication)
# Identity Matrix
identity = identity_matrix(n)
print("\nIdentity Matrix:")
print_matrix(identity)
Output:-
Matrix A:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Matrix B:
[9, 8, 7]
[6, 5, 4]
[3, 2, 1]
Matrix Addition:
Matrix Multiplication:
Identity Matrix:
[1, 0, 0]
[0, 1, 0]
[0, 0, 1]
Q8. Text processing using python , Import a CSV file and perform various
Statistical and Comparison operations on rows/column.
import csv
# csv file name
filename = "aapl.csv"
fields = []
rows = []
csvreader = csv.reader(csvfile)
fields = next(csvreader)
rows.append(row)
# get total number of rows
print("%10s"%col,end=" "),
print('\n')
Output :-
Field names are: Date, Open, High, Low, Close, Adj Close, Volume