0% found this document useful (0 votes)
7 views8 pages

Python LabTW

The document provides a comprehensive guide on writing Python scripts, including examples for storing and printing strings, demonstrating fundamental data types, and using various functions like id(), type(), and range(). It also includes user input examples for student academic details and programs to calculate total marks and determine senior citizen status. Additionally, it illustrates the use of print attributes such as 'sep' and 'end', and the replacement operator for formatted output.

Uploaded by

lavizamakandar
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)
7 views8 pages

Python LabTW

The document provides a comprehensive guide on writing Python scripts, including examples for storing and printing strings, demonstrating fundamental data types, and using various functions like id(), type(), and range(). It also includes user input examples for student academic details and programs to calculate total marks and determine senior citizen status. Additionally, it illustrates the use of print attributes such as 'sep' and 'end', and the replacement operator for formatted output.

Uploaded by

lavizamakandar
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

TERM WORK-1

1. Write a python script that stores a string in a variable, then prints the string by referencing
the variable within the print() function.

# Store a string in a variable


message = "Hello, world!"

# Print the string by referencing the variable


print(message)

output
Hello, world!

2. Demonstrate about fundamental data types in python programming (i.e., int, float, boolean and
string types).

#type conversion functions in python

#initial data
int_num = 10
float_num = 12.34
str_num = "123"
str_float = "45.67"
bool_val = True
list_data = [1, 2, 3]
tuple_data = (4, 5, 6)

#int() function - converts to a integer


print("int('123'): ", int(str_num)) # string to integer
print("int(12.34): ", int(float_num))#float to integer
print("\n") # Prints a blank line (new line)

#float() function - converts to a float


print("float('45.67'): ", float(str_float)) # string to float
print("float(10): ", float(int_num))# integer to float
print("\n")

#str() function - converts to a string


print("str (10):", str(int_num)) # integer to string
print("str(12.34):", str(float_num)) #float to string
print("\n")
#bool() function - converts to a boolean
print("bool(o):", bool(0)) # 0 is considered as false
print("bool(1):", bool(1)) #1 is considered as true
print("bool(""):", bool('')) #empty string is a false
print("bool('hello'): ", bool('hello')) #non-empty string is true
print("\n")

#list() functions - convert to a list


print("list([4,5, 6 ]): ", list(tuple_data)) #tuple to list
print("\n")

#tuple() function - converts to a tuple


print("tuple([1, 2, 3]): ", tuple(list_data)) # list to tuple
print("\n")

#demonstrating complex() - converts to a complex number


print("complex(10): ", complex(int_num)) #integer to complex
print("complex(12.34):", complex(float_num)) # Convert float to complex (directly)

# Convert string representation of a number to complex


str_num = "5"
print("complex('5'):", complex(str_num))
print("\n")

# Using ordinal numeric // ord() to convert a character to its ASCII value


print("ord('A'):", ord('A'))
print("\n")

#demonstrating chr() - converts an ASCII value to its corresponding character


print("char(65):", chr(65))
print("\n")

output
int('123'): 123
int(12.34): 12

float('45.67'): 45.67
float(10): 10.0

str (10): 10
str(12.34): 12.34

bool(o): False
bool(1): True
bool(): False
bool('hello'): True
list([4,5, 6 ]): [4, 5, 6]

tuple([1, 2, 3]): (1, 2, 3)

complex(10): (10+0j)
complex(12.34): (12.34+0j)
complex('5'): (5+0j)

ord('A'): 65

char(65): A

#list is Mutable
list=[1, 2, 3]
list[0]= 10
[Link](4)
[Link](2)
print(list)

output
[10, 3, 4]

#Tuple is Immutable
tuple=(1, 2, 3)
tuple[0]=10

output
TypeError: 'tuple' object does not support item assignment

3. Demonstrate the working of following functions in python.


i) id()
ii) type()
iii) range()

#demonstrating the id() function - returns memory address


x = 42
print("value of x: ", x)
print("memory address of x (id): ", id(x))

#demonstrating the type() function - returns type of object


y = 3.14
print("\n value of y: ", y)
print("type of y: ", type(y))
# Demonstrating the range() function - generating a sequence of numbers
print("\nUsing range() to create a sequence of numbers:")
for i in range(5): # Generates numbers from 0 to 4
print(i)

print("\nUsing range() with start, stop, and step:")


for i in range(1, 10, 2): # Generates numbers from 1 to 9 with a step of 2
print(i) #start, stop-1 with the given step

output
value of x: 42
memory address of x (id): 140716356021976

value of y: 3.14
type of y: <class 'float'>

Using range() to create a sequence of numbers:


0
1
2
3
4

Using range() with start, stop, and step:


1
3
5
7
9

4. create a python script that prompt the user to input student academic details with appropriate
labels. Display the details on the screen with the corresponding labels.

#prompts the user to input student academic details


name = input("enter the student name: ")
usn = input("enter the USN: ")
branch = input("enter the branch: ")
year = input("enter the year of study: ")
cgpa = input("enter the CGPA: ")

#display the details with corresponding labels


print("\n student academic details: ")
print(f"Name: {name}")
print(f"USN: {usn}")
print(f"Branch: {branch}")
print(f"Year of Study: {year}")
print(f"CGPA: {cgpa}")
# f (formatted string literal) before a string in Python to enable string interpolation—which means you
can insert variables or expressions directly into the string

output
enter the student name: xyz
enter the USN: 2sd24ai064
enter the branch: AIML
enter the year of study: 2024-2027
enter the CGPA: 9.6

student academic details:


Name: xyz
USN: 2sd24ai064
Branch: AIML
Year of Study: 2024-2027
CGPA: 9.6

5. write python programs to demonstrate the following:


i) input()
ii) print()
iii) ‘sep’ attribute
iv) ‘end’ attribute
v) Replacement operator ( {} )

# Demonstrating input()
name = input("Enter your name: ")
age = input("Enter your age: ")

# Demonstrating print()
print("\nUsing print():")
print("Hello", name, "! You are", age, "years old.")

# Demonstrating 'sep' attribute


print("\nUsing 'sep' attribute:")
print("Python", "is", "fun", sep="@")

# Demonstrating 'end' attribute


print("\nUsing 'end' attribute:")
print("This is printed on the same line", end="----")
print("because of the 'end' attribute.")

# Demonstrating replacement operator ({}):


print("\nUsing replacement operator ({}):")
print("Hello, {}! You are {} years old.".format(name, age))
output
Enter your name: xyz
Enter your age: 20

Using print():
Hello xyz ! You are 20 years old.

Using 'sep' attribute:


Python@is@fun

Using 'end' attribute:


This is printed on the same line----because of the 'end' attribute.

Using replacement operator ({}):


Hello, xyz! You are 20 years old.
Journal programs

1) A) Develop a program to read the student details like Name, USN, and Marks in three subjects.
Display the student details, total marks and percentage with suitable messages.

# Step 1: Taking input from the user


name = input("Enter Student Name: ") # Reads the student's name
usn = input("Enter Student USN: ") # Reads the student's USN
marks = [] # Initializes an empty list to store marks

# Step 2: Reading marks for three subjects


for i in range(3):
mark = int(input(f"Enter marks for subject {i+1}: ")) # Reads marks for each subject
[Link](mark) # Appends marks to the list

# Step 3: Calculating total marks and percentage


total_marks = sum(marks) # Computes total marks
percentage = total_marks / 3 # Computes percentage

# Step 4: Displaying student details and results


print("\nStudent Details:")
print(f"Name: {name}") #Creates a formatted string., which is used to format and display output.
print(f"USN: {usn}")
print(f"Marks: {marks}")
print(f"Total Marks: {total_marks}")
print(f"Percentage: {percentage:.2f}%")#Formats percentage to 2 decimal places.

Output
Enter Student Name: xyz
Enter Student USN: 2sd24ai064
Enter marks for subject 1: 95
Enter marks for subject 2: 82
Enter marks for subject 3: 98

Student Details:
Name: xyz
USN: 2sd24ai064
Marks: [95, 82, 98]
Total Marks: 275
Percentage: 91.67%
1) B) Develop a program to read the name and year of birth of a person. Display whether the
person is a senior citizen or not.

# Step 1: Taking input from the user


name = input("Enter your Name: ") # Reads the person's name
year_of_birth = int(input("Enter your Year of Birth: ")) # Reads the year of birth

# Step 2: Calculating age


current_year = 2025 # Update this to the current year if needed
age = current_year - year_of_birth # Calculates the person's age

# Step 3: Checking if the person is a senior citizen


if age >= 60:
status = "Senior Citizen"
else:
status = "Not a Senior Citizen"

# Step 4: Displaying the result


print("\nPerson Details:")
print(f"Name: {name}")
print(f"Year of Birth: {year_of_birth}")
print(f"Age: {age}")
print(f"Status: {status}")

output
Enter your Name: xyz
Enter your Year of Birth: 2000

Person Details:
Name: xyz
Year of Birth: 2000
Age: 25
Status: Not a Senior Citizen

Enter your Name: xyz


Enter your Year of Birth: 1950

Person Details:
Name: xyz
Year of Birth: 1950
Age: 75
Status: Senior Citizen

You might also like