Python User Input

  • Post author:
  • Post comments:0 Comments
  • Reading time:32 mins read

Python User Input

In Python, you can use the built-in input() function to get user input from the command line. The input() function reads a line of text from the user and returns a string object representing the input.

Here is an example of how to use the input() function:


name = input("Enter your name: ")

print("Hello, " + name)

When this code is executed, the program will prompt the user to enter their name, and then it will print a greeting using the name that the user entered.

Examples

Here are some examples of using the input() function:

Example 1: Reading a Single Line of Input

In this example, we will use the input() function to read a single line of input from the user.


line = input("Enter a line of text: ")

print("You entered: " + line)

This program will prompt the user to enter a line of text, and then it will print the line of text that the user entered.

Example 2: Reading Multiple Lines of Input

In this example, we will use the input() function to read multiple lines of input from the user.


lines = []

while True:
    line = input()
    if line:
        lines.append(line)
    else:
        break

text = '\n'.join(lines)

print("You entered: " + text)

This program will prompt the user to enter multiple lines of text, and then it will print all of the lines of text that the user entered. The program will stop reading input when the user enters an empty line (just presses the Enter key without entering any text).

Example 3: Reading a Number

In this example, we will use the input() function to read a number from the user.


num = input("Enter a number: ")

num = int(num)

print("You entered: " + str(num))

This program will prompt the user to enter a number, and then it will print the number that the user entered. However, the input() function always returns a string, so we need to use the int() function to convert the string to an integer. Then, we use the str() function to convert the integer back to a string so that we can print it.

Example 4: Reading a List of Numbers

In this example, we will use the input() function to read a list of numbers from the user.


numbers = input("Enter a list of numbers: ")

numbers = [int(n) for n in numbers.split()]

print("You entered: " + str(numbers))

This program will prompt the user to enter a list of numbers separated by spaces, and then it will print the list of numbers that the user entered. We use the split() method to split the string of numbers into a list of individual numbers, and then we use a list comprehension to convert each number from a string to an integer. Finally, we use the str() function to convert the list of integers back to a string so that we can print it.

Publisher
Latest posts by Publisher (see all)

Publisher

Publisher @ideasorblogs

Leave a Reply