fbpx

The input() and print() Functions

Producing Output to the Console

One of the simplest ways to collect input and produce output for the user is from the Python console. So far, we have seen how the print() function allows us to easily print values or messages to the screen. For example:

				
					print("Hello world!")
				
			

The print() function also allows us to pass in multiple parameters, separated by commas, that will print out with spaces in between. For example, the code below should print out “Hi John it’s nice to meet you! The weather today is sunny”

				
					name = "John"
weather = "sunny"

print("Hi", name, "it's nice to meet you! The weather today is", weather)
				
			

By default, the values passed into the print() function will be separated by spaces, but we can also specify a custom separator using the sep attribute. For example, to separate multiple strings by using a dash rather than a space:

				
					month = 12
day = 25
year = 2023

print("The date today is ", month, day, year, sep="-")
# The date today is 12-25-2023
				
			

Depending on the way you want to format a message in the console, you may consider using sep=””, sep=”/”,  or sep=”\n” to connect values together with something besides a simple space.

Collecting Input from the Console

If we want to collect some sort of input from the user, we can use the built-in input() function to do so. Like the print() function, whatever we pass in will be outputted to the console, but it will wait for the user to type something afterwards. Once the user types in their input and presses enter, the code will continue to move forward. We often want to store the entered value in a variable, like name in the below example. Try running the following example in a Python file to see how it works:

				
					name = input("What is your name? ")

print("It's nice to meet you", name, "!")
				
			

By default, the input() function will return what the user enters, casted as a String. So if we want to collect numeric data, for instance, we would need to convert the data as we have already learned. For example:

				
					age = int(input("What is your age?"))
gpa = float(input("Enter your GPA: "))
				
			

Replit Practice

Loading...