Here’s a list of practice questions to test your understanding of the print
and input
functions in Python. Read each question, attempt to answer it, and then expand to verify if your answer is correct.
1. Write a program that asks the user for their name and then prints a greeting message using their name.
name = input("Enter your name: ")
print("Hello, ", name ,"! Nice to meet you.")
2. How can you convert the user input to a specific data type, such as an integer or a float?
You can convert user input to a specific data type using type casting. For example:
name = input("Enter your name: ")
print("Hello, ", name ,"! Nice to meet you.")
3. Write a program to ask the user for 2 integers. And print their sum.
Here we are converting the user input to integer because input function takes the input as string always. So to do the sum we have to convert to integer.
a = int(input("enter 1st integer"))
b = int(input("enter 2nd integer"))
print("sum is", a+b)
4. Is it possible to display the output of the print
function on the same line without a new line character?
Yes, you can prevent the print
function from adding a new line character at the end of the output by passing the end
argument with an empty string.
print("Hello", end=" ") #Instead of printing next line in new line it will add a space and print in the same line.
print("Python")
5. Is it possible to print a string that includes double quotes using the print function? How can you achieve this?
Yes, it is possible using various ways. To achieve this, you can use escape characters to indicate that the double quotes are part of the string and not the string delimiter. The escape character for double quotes is \"
.
print("This is a string with double quotes: \"Hello, World!\"")
Else you can keep the string with double quote inside a single quote as below.
print('This is a string with double quotes inside single quotes"Hello, World!"')
6. How to print a string that consist of use of both single and double quotes inside the string?
You can either use escape character for double quotes as described in the previous question or you can use triple quote like below.
print("""This string consist of both 'single quote' and "double quotes" """)