Working with User Input and Output

Tutorial 5 of 5

Working with User Input and Output in Python

1. Introduction

1.1 Tutorial Goal

The main goal of this tutorial is to teach you how to work with user input and output in Python.

1.2 Learning Outcomes

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.

1.3 Prerequisites

Basic understanding of Python programming is required.

2. Step-by-Step Guide

2.1 User Input

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)

2.2 User Output

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!")

2.3 Best Practices and Tips

  • Always provide a descriptive prompt for input().
  • Use the str.format() method or f-strings (Python 3.6+) for cleaner string concatenation.
  • Remember that input() always returns a string. Use int() or float() to convert to numbers if necessary.

3. Code Examples

3.1 Basic Input and Output

# 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.

3.2 Input and Output with Numbers

# 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.

4. Summary

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.

5. Practice Exercises

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!