The main goal of this tutorial is to teach you how to work with user input and output in Python.
By the end of this tutorial, you will be able to:
- Understand Python's built-in functions for user input and output.
- Use these functions to interact with users effectively.
- Create practical and interactive Python programs.
Basic understanding of Python programming is required.
In Python, you can use the input()
function to get user input. This function reads a line from input (usually user), converts it into a string, and returns it.
name = input("Enter your name: ")
print("Hello, " + name)
Python uses the print()
function to output data to the standard output device (screen). You can also use the print()
function to output to a file.
print("Hello, World!")
input()
.str.format()
method or f-strings (Python 3.6+) for cleaner string concatenation.input()
always returns a string. Use int()
or float()
to convert to numbers if necessary.# Ask the user for their name
name = input("Please enter your name: ")
# Print a greeting message
print("Hello, {}!".format(name))
In this example, input()
is used to get the user's name and print()
is used to display a greeting message. The {}
is a placeholder which gets replaced by the value of name
.
# Ask the user for two numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
# Calculate their sum
sum = num1 + num2
# Print the result
print("The sum of {} and {} is {}.".format(num1, num2, sum))
In this example, we convert the user input into integers using int()
. The sum of the numbers is then calculated and displayed.
In this tutorial, you have learned how to use Python's built-in functions for user input (input()
) and output (print()
). You can now create interactive Python programs.
Exercise 1: Write a program that asks the user for their name and age and prints out a message addressed to them with their age.
Exercise 2: Write a program that asks the user for a number and then prints out a list of all the divisors of that number.
Exercise 3: Write a program that asks the user for two numbers and then prints out the result of their division with a remainder.
Solutions and tips for these exercises can be found here.
Keep practicing and exploring more about Python's built-in functions. Happy coding!