Python Basic (Part 1): Practice Exercises and Solutions
Question 1: To print the following string in a certain format, create a Python program (see output).
“Twinkle, twinkle, little star,” for example How curious I am about you! Like a diamond in the sky, high above the planet. “Twinkle, twinkle, little star, What are you?”
You can use the following Python program to print the sample string in a specific format:
pythonCopy codedef print_specific_format(sample_string):
lines = sample_string.split('. ')
for i, line in enumerate(lines):
line = line.strip()
if i % 2 == 0:
line = line.capitalize()
else:
line = line.upper()
print(line)
sample_string = "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are"
print_specific_format(sample_string)
Output:
cssCopy codeTwinkle, twinkle, little star, how i wonder what you are!
UP ABOVE THE WORLD SO HIGH, LIKE A DIAMOND IN THE SKY
Twinkle, twinkle, little star, how i wonder what you are
In this program, the print_specific_format
function splits the input string into lines based on the period (.
) character. Then, it processes each line based on its index. If the index is even, the line is capitalized using the capitalize()
method, and if the index is odd, the line is converted to uppercase using the upper()
method. Finally, the formatted lines are printed to the console.
Question 2: To determine the Python version you are using, create a Python program.
You can use the sys
module in Python to find out the version of Python you are using. The sys
module provides a function called version
which returns the version number of Python. Here’s a simple Python program to do that:
pythonCopy codeimport sys
def python_version():
return sys.version
version_info = python_version()
print("Python version:", version_info)
When you run this program, it will print the version number of Python installed on your system, for example:
csharpCopy codePython version: 3.8.5 (default, Jan 27 2021, 15:41:15)
[GCC 9.3.0]
The version number may vary depending on your Python installation and system configuration.
Question 3: To determine the Python version you are using, create a Python program.
You can use the datetime
module in Python to get the current date and time. Here’s a simple Python program to display the current date and time:
pythonCopy codeimport datetime
def display_current_datetime():
# Get the current date and time
current_datetime = datetime.datetime.now()
# Format the date and time as a string
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
return formatted_datetime
# Call the function to display the current date and time
current_datetime = display_current_datetime()
print("Current Date and Time:", current_datetime)
When you run this program, it will print the current date and time in the format “YYYY-MM-DD HH:MM:SS”, for example:
sqlCopy codeCurrent Date and Time: 2023-07-31 09:15:30
The actual date and time displayed will vary depending on when you run the program.
Question 4: Create a Python application that determines a circle’s area depending on the user-provided radius.
Sure! Here’s a simple Python program that calculates the area of a circle based on the radius entered by the user:
pythonCopy codeimport math
def calculate_circle_area(radius):
# Calculate the area of the circle using the formula: Area = π * radius^2
area = math.pi * radius ** 2
return area
# Get the radius from the user
try:
radius = float(input("Enter the radius of the circle: "))
if radius < 0:
raise ValueError("Radius cannot be negative.")
# Calculate the area of the circle
area = calculate_circle_area(radius)
# Display the result
print(f"The area of the circle with radius {radius} is: {area:.2f}")
except ValueError as ve:
print("Error:", ve)
When you run this program, it will prompt you to enter the radius of the circle. After entering the radius, it will calculate the area using the formula A = π * r^2 and display the result. The area will be rounded to two decimal places.
For example, if you enter a radius of 5, the output will be:
csharpCopy codeThe area of the circle with radius 5.0 is: 78.54
Remember to ensure that the user input is a positive number, as a negative radius doesn’t make sense in this context. The program includes a check to handle negative input.
Question 5: Create a Python script that takes the user’s first and last name and prints them with a space between them in reverse order.
Python script that takes the user’s first and last name, combines them with a space in between, and then prints the result in reverse order:
pythonCopy codedef reverse_name(first_name, last_name):
# Concatenate first name and last name with a space in between
full_name = first_name + " " + last_name
# Reverse the full name
reversed_name = full_name[::-1]
return reversed_name
# Get user input for first name and last name
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
# Call the function to get the reversed name
reversed_full_name = reverse_name(first_name, last_name)
# Display the result
print("Reversed Name:", reversed_full_name)
When you run this script, it will prompt you to enter your first name and last name. After entering both names, it will print the reversed full name.
For example, if you enter “John” as the first name and “Doe” as the last name, the output will be:
yamlCopy codeReversed Name: eoD nhoJ
The script concatenates the first name and last name with a space in between, then uses string slicing with [::-1]
to reverse the full name before printing it.
Explanation of Questions 4:
The Python program aims to calculate the area of a circle based on the radius entered by the user. The program demonstrates how to take user input, perform a simple mathematical calculation, and display the result. The program utilizes the math module to access the value of π for more accurate calculations. In addition, the program incorporates error handling to ensure that the user provides valid input.
Importing Required Modules:
The program starts by importing the math module, which allows access to mathematical functions and constants, including π (pi). The math module simplifies the calculation of the area of a circle by providing the value of π for accurate results.
Defining the calculate_circle_area Function:
The program defines the calculate_circle_area function to calculate the area of a circle. The function takes the radius of the circle as an argument and returns the calculated area using the formula: Area = π * radius^2. The math.pi constant from the math module provides the value of π, and the formula calculates the area based on the user’s input.
Receiving User Input:
The program prompts the user to input the radius of the circle. The input() function is used to collect the user’s input as a string. The entered value is then converted to a floating-point number using float() to ensure that the radius can be used in mathematical operations.
Error Handling for Invalid Input:
The program incorporates error handling to ensure that the user provides a valid and non-negative radius. If the user enters a negative value or any non-numeric input, a ValueError is raised. The program uses a try-except block to handle this exception gracefully and displays an error message explaining that the radius cannot be negative.
Calculating and Displaying the Area:
Once the program successfully receives the radius from the user, it calls the calculate_circle_area function with the provided radius as an argument. The function returns the calculated area, which is then displayed to the user using the print() function. The output message presents the area with two decimal places for better readability.
The Python program for calculating the area of a circle is a simple yet effective example of basic input processing, mathematical computation, and output display in Python. By importing the math module, the program leverages the value of π to ensure precise area calculations. Additionally, the program demonstrates the importance of incorporating error handling to handle user input gracefully and provide meaningful feedback. Overall, this program is a useful illustration of Python’s versatility and ease of use in handling real-world scenarios such as mathematical computations.
Practice Time
Practice 1:
Consider the following Python program that calculates the area of a circle based on the user’s input:
pythonCopy codeimport math
def calculate_circle_area(radius): # Calculate the area of the circle using the formula: Area = π * radius^2 area = math.pi * radius ** 2 return area try: radius = float(input("Enter the radius of the circle: ")) if radius < 0: raise ValueError("Radius cannot be negative.") area = calculate_circle_area(radius) print(f"The area of the circle with radius {radius} is: {area:.2f}") except ValueError as ve: print("Error:", ve)
Choose the correct option based on the given code:
What does the Python program calculate?
a) The perimeter of a circle
b) The area of a square
c) The area of a rectangle
d) The area of a circle
Which Python module is used in the program to access mathematical functions and constants?
a) sys
b) math
c) datetime
d) os
What will be the output of the program if the user enters a radius of 5?
a) The area of the circle with radius 5 is: 78.54
b) The area of the circle with radius 5.0 is: 78.54
c) The area of the circle with radius 5 is: 78.54 square units
d) The area of the circle with radius 5.0 is: 78.54 square units
Why is error handling used in the program?
a) To calculate the area more accurately
b) To convert the radius to a floating-point number
c) To check if the user’s input is numeric
d) To handle negative radii gracefully
What happens if the user enters a negative value for the radius?
a) The program calculates the area with the negative radius
b) The program displays an error message and terminates
c) The program converts the negative radius to a positive value
d) The program asks the user to enter a positive radius
Choose the correct letter for each question (e.g., 1 – a, 2 – b, 3 – c, 4 – d, 5 – b).
Practice 2:
What does the math.pi
constant represent in the program?
a) The square root of 2
b) The mathematical constant “π” (pi)
c) The Euler’s number “e”
d) The golden ratio “φ” (phi)
What is the purpose of using the try-except
block in the program?
a) To check if the input radius is an integer b) To handle errors and exceptions that may occur during program execution
c) To check if the input radius is less than or equal to zero
d) To ensure that the program runs without any errors
Which function is used to receive the user’s input for the radius of the circle?
a) input()
b) get_input()
c) user_input()
d) read_input()
What is the data type of the area
variable in the program?
a) String
b) Integer
c) Float
d) Boolean
If the user enters a non-numeric value for the radius, what will be the output of the program?
a) The area of the circle with radius None is: 0.00
b) The area of the circle with radius None is: None
c) The area of the circle with radius None is: Error: could not convert string to float
d) The program will not execute and will raise a syntax error
Choose the correct letter for each question (e.g., 6 – b, 7 – b, 8 – a, 9 – c, 10 – c). These questions will test students’ understanding of the Python program and its components, including modules, functions, error handling, and data types.