0% found this document useful (0 votes)
56 views

Python

The document discusses installing Python and learning the basics of Python programming. It covers downloading and installing Python, using the interactive Python interpreter to learn interactively and run code, and writing and running simple Python programs from files. Key steps include verifying the Python installation, opening the interpreter, writing and running code within it, exiting the interpreter, writing programs in text files and running the files from the command line.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Python

The document discusses installing Python and learning the basics of Python programming. It covers downloading and installing Python, using the interactive Python interpreter to learn interactively and run code, and writing and running simple Python programs from files. Key steps include verifying the Python installation, opening the interpreter, writing and running code within it, exiting the interpreter, writing programs in text files and running the files from the command line.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Q1.

Installation of Python, and learning interactively at command prompt


and writing simple programs.

1. Installing Python:

Follow these steps to install Python on your computer:

a. Download Python: Go to the official Python website


(https://www.python.org/downloads/) and download the latest version of
Python for your operating system (Windows, macOS, or Linux).

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.

c. Verify Installation: Open a command prompt (Windows) or terminal


(macOS/Linux) and type python --version or python3 --version and press Enter.
This should display the version of Python you installed.

2. Learning Interactively and Writing Simple Programs:

Python provides an interactive environment called the Python interpreter or


REPL (Read-Eval-Print Loop) that you can use to learn and write code
interactively. Here's how to do it:

a. Opening the Python Interpreter:

 Open a command prompt (Windows) or terminal (macOS/Linux).


 Type python or python3 and press Enter. This will start the Python
interpreter, and you'll see a prompt like >>> where you can enter
Python code.

b. Writing and Running Code:

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:

>>> name = "Alice"

>>> print("Hello, " + name)

Hello, Alice

d. Exiting the Interpreter:

To exit the Python interpreter, simply type exit() or press Ctrl + Z (Windows)
or Ctrl + D (macOS/Linux).

3. Writing Simple Programs:

You can also write Python programs in separate files and run them using the
command prompt. Here's a simple example:

a. Open a Text Editor:

Open a text editor like Notepad (Windows), TextEdit (macOS), or any code
editor you prefer.

b. Write Your Program:

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:

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))

sum_result = num1 + num2

print("The sum is:", sum_result)

c. Save the File:

Save the file with a .py extension, for example, sum.py.

d. Run the Program:

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.

Q2. Perform Creation, indexing, slicing, concatenation, and repetition


operations on Python built-in data types: Strings, List, Tuples ,
Dictionary, Set.

# Strings

my_string = "Hello, World!"

print("String:", my_string)

print("Indexing:", my_string[0])

print("Slicing:", my_string[7:])

print("Concatenation:", my_string + " Welcome")

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("Concatenation:", my_list + [6, 7])

print("Repetition:", my_list * 2)

# Tuples

my_tuple = (10, 20, 30)

print("\nTuple:", my_tuple)

print("Indexing:", my_tuple[0])

print("Slicing:", my_tuple[1:])

print("Concatenation:", my_tuple + (40, 50))

# Dictionaries

my_dict = {"name": "Alice", "age": 25, "city": "New York"}

print("\nDictionary:", my_dict)

print("Indexing:", my_dict["name"])
new_data = {"gender": "Female"}

my_dict.update(new_data)

print("Updated Dictionary:", my_dict)

# Sets

my_set = {1, 2, 3, 4, 5}

print("\nSet:", my_set)

print("Membership:", 3 in my_set)

new_set = my_set | {6, 7}

print("Union:", new_set)

Output :-

String: Hello, World!

Indexing: H

Slicing: World!

Concatenation: Hello, World! Welcome

Repetition: Hello, World!Hello, World!Hello, 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]

Tuple: (10, 20, 30)

Indexing: 10

Slicing: (20, 30)

Concatenation: (10, 20, 30, 40, 50)

Dictionary: {'name': 'Alice', 'age': 25, 'city': 'New York'}

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

# Generate a random number between 1 and 100

target_number = random.randint(1, 100)

print("Welcome to the Number Guessing Game!")

print("I'm thinking of a number between 1 and 100. Can you guess it?")

attempts = 0

max_attempts = 10

while attempts < max_attempts:

guess = int(input("Enter your guess: "))

attempts += 1

if guess < target_number:

print("Too low.")

elif guess > target_number:

print("Too high.")

else:
print(f"Congratulations! You've guessed the number {target_number} in
{attempts} attempts.")

break

if attempts == max_attempts and guess != target_number:

print(f"Sorry, you've used all {max_attempts} attempts. The number was


{target_number}.")

Output :-

Welcome to the Number Guessing Game!

I'm thinking of a number between 1 and 100. Can you guess it?

Enter your guess: 51

Too low.

Enter your guess: 787

Too high.

Enter your guess: 0

Too low.
Q4. Handle numerical operations using math and random number
functions.

import math

import random

# Calculate the area of a circle

radius = float(input("Enter the radius of the circle: "))

area = math.pi * math.pow(radius, 2)

print(f"The area of the circle with radius {radius} is {area:.2f}")

# Generate a random integer between 1 and 100

random_number = random.randint(1, 100)

print("Random Number:", random_number)

# Calculate the square root of a random number

random_sqrt = math.sqrt(random_number)

print(f"The square root of the random number {random_number} is


{random_sqrt:.2f}")

Output :-

Enter the radius of the circle: 5

The area of the circle with radius 5.0 is 78.54


Random Number: 55

The square root of the random number 55 is 7.42

Q5. Create user-defined functions with different types of function


arguments.

# Positional Arguments

def greet(name, age):

print(f"Hello, {name}! You are {age} years old.")

# Default Argument

def calculate_area(base, height=5):

area = 0.5 * base * height

return area

# Variable-Length Arguments

def add_numbers(*args):

total = sum(args)

return total
# Keyword Arguments

def person_info(name, age, city):

print(f"Name: {name}, Age: {age}, City: {city}")

# Mix of Different Argument Types

def describe_person(name, age, *hobbies, city="Unknown"):

print(f"Name: {name}, Age: {age}, City: {city}")

print("Hobbies:", hobbies)

# Calling the functions

greet("Alice", 30)

area = calculate_area(10)

print(f"Area with default height: {area}")

area_custom = calculate_area(10, 8)

print(f"Area with custom height: {area_custom}")

sum_result = add_numbers(1, 2, 3)

print("Sum of numbers:", sum_result)


person_info(name="Bob", age=25, city="Los Angeles")

describe_person("Charlie", 40, "Coding", "Traveling", city="San Francisco")

Output :-

Name: Bob, Age: 25, City: Los Angeles

Name: Charlie, Age: 40, City: San Francisco

Hobbies: ('Coding', 'Traveling')

Q6. Perform File manipulations- open, close, read, write, append and
copy from one file to another.

# Opening a file in write mode and writing content

with open("example.txt", "w") as file:

file.write("Hello, this is some text.\n")

file.write("Welcome to file manipulation in Python.\n")

# Reading content from the file

with open("example.txt", "r") as file:

content = file.read()
print("Read content:\n", content)

# Appending content to the file

with open("example.txt", "a") as file:

file.write("Appending new line.\n")

# Copying content from one file to another

with open("example.txt", "r") as source_file:

content = source_file.read()

with open("copy.txt", "w") as dest_file:

dest_file.write(content)

print("Copying content from example.txt to copy.txt.")

# Reading the copied content

with open("copy.txt", "r") as file:

copied_content = file.read()

print("Copied content:\n", copied_content)

Output:-
Read content:

Hello, this is some text.

Welcome to file manipulation in Python.

Copying content from example.txt to copy.txt.

Copied content:

Hello, this is some text.

Welcome to file manipulation in Python.

Appending new line.

Q7. Matrix addition, multiplications, and unity matrix.

def print_matrix(matrix):

for row in matrix:

print(row)

def add_matrices(matrix1, matrix2):

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

def multiply_matrices(matrix1, matrix2):

result = []

for i in range(len(matrix1)):

row = []

for j in range(len(matrix2[0])):

value = 0

for k in range(len(matrix2)):

value += matrix1[i][k] * matrix2[k][j]

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

matrix_A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

matrix_B = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]

print("Matrix A:")

print_matrix(matrix_A)

print("\nMatrix B:")

print_matrix(matrix_B)

# Matrix Addition

result_addition = add_matrices(matrix_A, matrix_B)

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

n = 3 # Size of 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:

[10, 10, 10]

[10, 10, 10]

[10, 10, 10]

Matrix Multiplication:

[30, 24, 18]

[84, 69, 54]

[138, 114, 90]

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.

# importing csv module

import csv
# csv file name

filename = "aapl.csv"

# initializing the titles and rows list

fields = []

rows = []

# reading csv file

with open(filename, 'r') as csvfile:

# creating a csv reader object

csvreader = csv.reader(csvfile)

# extracting field names through first row

fields = next(csvreader)

# extracting each data row one by one

for row in csvreader:

rows.append(row)
# get total number of rows

print("Total no. of rows: %d"%(csvreader.line_num))

# printing the field names

print('Field names are:' + ', '.join(field for field in fields))

# printing first 5 rows

print('\nFirst 5 rows are:\n')

for row in rows[:5]:

# parsing each column of a row

for col in row:

print("%10s"%col,end=" "),

print('\n')

Output :-

Total no. of rows: 185

Field names are: Date, Open, High, Low, Close, Adj Close, Volume

First 5 rows are:

2014-09-29 100.589996 100.690002 98.040001 99.620003 93.514290


142718700
2014-10-06 99.949997 102.379997 98.309998 100.730003 94.556244
280258200

2014-10-13 101.330002 101.779999 95.180000 97.669998 91.683792


358539800

2014-10-20 98.320000 105.489998 98.220001 105.220001 98.771042


358532900

2014-10-27 104.849998 108.040001 104.699997 108.000000 101.380676


220230600

You might also like