
Reading Input, Writing Output in Python
Reading Input, Writing Output in Python
In Python, reading input from the user and writing output to the console are essential skills. This tutorial will introduce you to the basics of reading input and writing output in Python, utilizing the built-in functions input() and print().
Reading Input from the Keyboard
The input() function allows you to prompt the user for input. It reads a line from the input and returns it as a string. Here's an example:
name = input("Enter your name: ")
print("Hello, " + name)In this example, the input() function prompts the user to enter their name. The entered name is then stored in the name variable and printed to the console using the print() function.
Converting Keyboard Input
By default, the input() function returns the input as a string. If you need a different data type, such as an integer or a float, you can use type conversion. Here's an example of converting input to an integer:
age = int(input("Enter your age: "))
print("You are " + str(age) + " years old")In this example, the user is prompted to enter their age. The input is converted to an integer using the int() function, and then it's printed to the console.
Writing Output to the Console
The print() function is used to display output to the console. You can pass multiple arguments to print() to concatenate and display them together. Here's an example:
name = "Alice"
age = 25
print("Name:", name, "| Age:", age)In this example, the print() function displays the name and age of a person by concatenating them with other strings.
Using Keyword Arguments with print()
You can use keyword arguments with the print() function to specify the separator and end strings. Here's an example:
print("Python", "Programming", sep="-", end="!")
print("Is", "Fun", sep="***", end="!!!")In this example, the output will be: Python-Programming!Is***Fun!!!
By learning these fundamental skills of reading input and writing output in Python, you’ll be well-equipped to build interactive programs and handle user interactions effectively.
To dive deeper into these concepts, you can explore the provided downloadable resources and related learning paths to further enhance your Python skills. Happy coding!
