7.Python Tutorial: Input/Output and f-Strings
In Python, input and output operations are fundamental for interacting with users and displaying results. This tutorial covers how to read user input, display output, and format strings using f-strings. These concepts are essential for building interactive programs.
Reading Input in Python
Python provides the built-in function input() to read data from the user. The input() function always returns a string, so you may need to convert it to other types like int or float.
name = input(“Enter your name: “)
print(“Hello,”, name)
Displaying Output in Python
The print() function is used to display output to the console. It can print strings, numbers, and even multiple values separated by commas.
print(“Welcome to Python!”)
print(“The sum of 2 and 3 is”, 2 + 3)
Using f-Strings for Formatting
Introduced in Python 3.6, f-strings provide a concise and readable way to embed expressions inside string literals. You prefix the string with an ‘f’ or ‘F’ and use curly braces {} to include variables or expressions.
Example:
name = “Alice”
age = 25
print(f”My name is {name} and I am {age} years old.”)
Combining Input, Output, and f-Strings
You can combine input(), print(), and f-strings to create interactive programs that display formatted output based on user input.
Example:
name = input(“Enter your name: “)
age = int(input(“Enter your age: “))
print(f”Hello {name}, you are {age} years old!”)
Additional Notes
input() always returns a string; convert it using int(), float(), etc. when needed.
• f-strings can include expressions, e.g., f”2 + 3 = {2 + 3}”.
• print() can take multiple arguments and supports optional parameters like sep and end.
Conclusion
Mastering input/output and f-strings is crucial for writing interactive and user-friendly Python programs. Practice these concepts to build dynamic scripts that respond to user input and display well-formatted output.