Input
Python provides the input()
function to take input from the user. By default, it returns a string.
Python
name = input("Enter your name: ")
print("Hello,", name)
Important Note: The input is always a string. To convert it to a number, use int()
or float()
.
Python
age = int(input("Enter your age: "))
print("You are", age, "years old.")
Output
The print()
function is used to display output to the console. It can handle various data types.
Python
name = "Alice"
age = 30
print("Name:", name, "Age:", age)
Formatting Output:
- f-strings: For formatted output with embedded expressions.Python
name = "Alice" age = 30 print(f"Hello, {name}. You are {age} years old.")
str.format()
method: For more complex formatting.Pythonprint("Hello, {}. You are {} years old.".format(name, age))
Additional Considerations
- File Input/Output: For handling data from files, use functions like
open()
,read()
,write()
, andclose()
. - Error Handling: Use
try-except
blocks to handle potential errors during input/output operations.
How do I take user input in Python?
Use the input()
function to get user input as a string.
How do I display output in Python?
Use the print()
function to display output to the console.
What is the default data type of input from the user?
It’s a string. You need to convert it to other data types (int, float) if necessary.
Can I format the output using print()
?
Yes, use f-strings or the format()
method for formatted output.
What happens if the user enters invalid input?
The program might crash. Use try-except
blocks to handle potential errors.
Can I read data from a file?
Yes, use the open()
function to open a file and read its contents.
Can I write data to a file?
Yes, use the open()
function with the 'w'
mode to write data to a file.
Can I validate user input?
Yes, use conditional statements and error handling (try-except) to check for valid input.