📚 Python String Formatting Practice
---
🔹 Part 1 — Using the % Operator
1️⃣ Fill in the blanks:
Write the correct code to get the output.
Q1.
name = "Ali"
age = 21
print("My name is %s and I am %d years old." % (____, ____))
✅ Expected Output: My name is Ali and I am 21 years old.
---
Q2.
price = 499.99
print("The price is %.2f dollars." %(____))
✅ Expected Output: The price is 499.99 dollars.
---
Q3.
x = 5
y = 10
print("x = %d, y = %d" % (____, ____))
✅ Expected Output: x = 5, y = 10
---
2️⃣ Small Task:
Write a Python line to display: Temperature: 37.5°C using % formatting.
---
🔹 Part 2 — Using .format()
1️⃣ Fill in the blanks:
Q4.
city = "Lahore"
print("I live in {}.".format(____))
✅ Expected Output: I live in Lahore.
---
Q5.
subject = "Math"
marks = 95
print("I got {} marks in {}.".format(____, ____))
✅ Expected Output: I got 95 marks in Math.
---
Q6.
Use indexing:
print("{1} is {0} years old.".format(20, "Ahmed"))
✅ What is the output?
---
2️⃣ Small Task:
Write code to display:
Book: Python Basics | Pages: 350
using .format().
---
🔹 Part 3 — Small Challenges
Q7.
Write a single print statement using % formatting to output:
PI is approximately 3.14.
---
Q8.
Write a single print statement using .format() to output:
Name: Sara, Age: 18
---
No comments:
Post a Comment