Python read string input

Пользовательский ввод (input) в Python

Обычно программа работает по такой схеме: получает входные данные → обрабатывает их → выдает результат. Ввод может поступать как непосредственно от пользователя через клавиатуру, так и через внешний источник (файл, база данных).

В стандартной библиотеке Python 3 есть встроенная функция input() (в Python 2 это raw_input() ), которая отвечает за прием пользовательского ввода. Разберемся, как она работает.

Чтение ввода с клавиатуры

Функция input([prompt]) отвечает за ввод данных из потока ввода:

s = input() print(f»Привет, !») > мир # тут мы с клавиатуры ввели слово «мир» > Привет, мир!

  1. При вызове функции input() выполнение программы приостанавливается до тех пор, пока пользователь не введет текст на клавиатуре (приложение может ждать бесконечно долго).
  2. После нажатия на Enter , функция input() считывает данные и передает их приложению (символ завершения новой строки не учитывается).
  3. Полученные данные присваиваются переменной и используются дальше в программе.

Также у input есть необязательный параметр prompt – это подсказка пользователю перед вводом:

name = input(«Введите имя: «) print(f»Привет, !») > Введите имя: Вася > Привет, Вася!

📃 Более подробное описание функции из документации:

def input([prompt]): «»» Read a string from standard input. The trailing newline is stripped. The prompt string, if given, is printed to standard output without a trailing newline before reading input. If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError. On *nix systems, readline is used if available. «»» pass

Читайте также:  Export default class typescript

Преобразование вводимые данные

Данные, введенные пользователем, попадают в программу в виде строки, поэтому и работать с ними можно так же, как и со строкой. Если требуется организовать ввод цифр, то строку можно преобразовать в нужный формат с помощью функций явного преобразования типов.

☝️ Важно : если вы решили преобразовать строку в число, но при этом ввели строку (например: test), возникнет ошибка:

ValueError: invalid literal for int() with base 10: ‘test’

На практике такие ошибки нужно обрабатывать через try except . В примере ниже пользователь будет вводить данные до тех пор, пока они успешно не преобразуются в число.

def get_room_number(): while True: try: num = int(input(«Введите номер комнаты: «)) return num except ValueError: print(«Вы ввели не число. Повторите ввод») room_number = get_room_number() print(f»Комната успешно забронирована!») > Введите номер комнаты: test > Вы ввели не число. Повторите ввод > Введите номер комнаты: 13 > Комната 13 успешно забронирована!

Input() → int

Для преобразования в целое число используйте функцию int() . В качестве аргумента передаются данные которые нужно преобразовать, а на выходе получаем целое число:

age_str = input(«Введите ваш возраст: «) age = int(age_str) print(age) print(type(age)) > Введите ваш возраст: 21 > 21 >

То же самое можно сделать в одну строку: age = int(input(«Введите ваш возраст: «)) .

Input() → float

Если нужно получить число с плавающей точкой (не целое), то его можно получить с помощью функции float() .

weight = float(input(«Укажите вес (кг): «)) print(weight) print(type(weight)) > Укажите вес (кг): 10.33 > 10.33 >

Input() → list (список)

Если в программу вводится информация, которая разделяется пробелами, например, «1 word meow», то ее легко преобразовать в список с помощью метода split() . Он разбивает введенные строки по пробелам и создает список:

list = input().split() print(list) print(type(list)) > 1 word meow > [‘1’, ‘word’, ‘meow’] >

💭 Обратите внимание, что каждый элемент списка является строкой. Для преобразования в число, можно использовать int() и цикл for. Например, так:

int_list = [] for element in input().split(): int_list.append(int(element)) print([type(num) for num in int_list]) > 1 2 3 > [, , ]

Ввод в несколько переменных

Если необходимо заполнить одним вводом с клавиатуры сразу несколько переменных, воспользуйтесь распаковкой:

В этом примере строка из input() разбивается по пробелу функцией split() . Далее применяется синтаксис распаковки – каждый элемент списка попадает в соответствующую переменную.

Все переменные после распаковки будут строкового типа. Преобразовать их (например в int) можно так:

a, b = [int(s) for s in input().split()] print(f»type a: , type b: «) > 13 100 > type a: , type b:

☝️ Важно : не забывайте обрабатывать ошибки:

  • если введенных значений больше чем переменных, получите ошибку – ValueError: too many values to unpack (expected 3) ;
  • если введенных значений меньше чем переменных, получите ошибку – ValueError: not enough values to unpack (expected 3, got 2) ;
  • если преобразовываете в int, а вводите строку – ValueError: invalid literal for int() with base 10: ‘test’ .

В этом руководстве вы узнали, как принимать данные от пользователя, введенные с клавиатуры, научились преобразовывать данные из input и обрабатывать исключения.

Источник

Python – Read String from Console

To read a string from console as input to your Python program, you can use input() function.

input() can take an argument to print a message to the console, so that you can prompt the user and let him/her know what you are expecting.

In this tutorial, we will learn how to use input() function, to read an input from user in your console application.

Examples

1. Read a string value from console

In the following program, we shall prompt the user to enter his name. input() function does print the prompt message to console and waits for the user to enter input.

Python Program

#read string from user firstName = input('Enter your first name: ') print('Hello',firstName)

Run the program. The prompt appears on the console. Type the string and click enter. The new line is considered end of the input and the execution continues with statements after input() statement in the program.

Enter your first name: Brooks Hello Brooks

input() function returns what you have provided as input in the console and you can assign it to a variable. In the above program, we have assigned input() function to a variable. As a result, you can access the string value entered by the user using this variable.

2. Read multiple strings entered by user in console

In this program, we will read multiple strings from user through console, one by one. It is similar to our previous example, but it has two input() statements. The first input() statement shall read a string from console and assign it to firstName. The second input() statement shall read a string from console and assign it to lastName.

Python Program

#read multiple strings from user firstName = input('Enter your first name: ') lastName = input('Enter your last name: ') print('Hello',firstName, lastName)

Run the program, and you shall see the prompt by first input() statement. After you enter some string and type enter, you shall see the prompt by second input() statement. Enter a string for last name and click enter. The program has now read two strings from you, the user.

Enter your first name: Brooks Enter your last name: Henry Hello Brooks Henry

Summary

In this tutorial of Python Examples, we learned to read input from user, specifically to say, read string through console from user, using Python input(), with the help of well detailed Python example programs .

Источник

Python Input String

Python Input String

In Python, to read the string or sentence from the user through an input device keyboard and return it to the output screen or console, we use the input() function. There are also some built-in methods or functions to read the string on the console and return it in other languages. In Python, as we know that we don’t specify any data types while declaring any variable, and also there are two different functions to display and handle input data obtained from the user, they are input() and print(). In Python, the print() function is used to display the input obtained or the value it wants to display, which is specified, whereas to accept the input line from the user, there are two functions such as input() and raw_input().

Web development, programming languages, Software testing & others

Working of Python Input String

Python has two functions for taking in the input from the user or reads the data that is entered through the console, and the result of this can be a string, list, tuple or int, etc., which is stored into a variable. Two input functions of Python are:

1. raw_input()

This Python method reads the input line or string and can read commands from users or data entered using the console. The return value of this method will be only of the string data type. In Python, this method is used only when the user wants to read the data by entering through the console, and the return value is a string.

raw_input([prompt]) Parameter:

prompt: This is optional; it can be any string or command which you want to display on the output console.

place = raw_input("Where do you stay?") print ("Name of the place where I stay is: ", place) print(type(place)) 

Python Input String 1

2. input()

This is also a Python method for reading the input string from the user through an input device like a keyboard and display the return value of this function on the output screen or console. The return value of this method can be string or number or list or tuple, etc. In Python, we do not declare any data type while initializing or declaring the variable. As in the raw_input() function, it can return an only a string value, but in this input() function, we can get the return value of any data type; Python decides as to what data type to be returned based on the variable value. If you have asked the user to enter the age, it will automatically take an int as the data type for the variable age.

prompt: This is optional again; it can be any string or commands that the user wants to display. In this function, whatever the user enters, the input() function converts it into a string, and this function stops the execution of the further program until the user enters the value that is asked through this function.

name = input("Enter your name: ") print("my name is: ", name) age = input("Enter your age: ") print("age is:", age) print(type(name)) print(type(age)) 

Python Input String 2

From the above program, as the first variable “name” has input() function that asks the user to enter the name input() function always converts the value taken by into string as “name” variable is already of string type there is no such problem, but in the second variable it’s “age” which is of data type int, still the input() function converts it into a string. Sometimes you can be more perfect by declaring input value as integer type explicitly.

Examples

Lets us discuss the Examples of Python Input String.

Example #1

Let us take to display the multiplication of two numbers.

n1 = int( input("Enter the first number for multiplication: ")) n2 = int( input("Enter the second number for multiplication: ")) product = n1 * n2 print( "Multiplication of two numbers is: ", product) 

Python Input String 3

Example #2

The input() function can also accept the float value similarly to integer value by explicitly declaring float as we did in the above program as int.

fn1 = float(input("Enter float number: ")) print("The float number is: ", fn1) 

Python Input String 4

Example #3

This input() function can also be used to read the list as input from users. We could accept int and float in the same way we can accept list and array also through this function().

lst = input ("Enter the list of numbers you want to display: ") out_list = lst.split() print(" The list you entered is: ", lst) 

example 4

Example #4

From the above example, we are using the split() function to split the string by space and append those numbers to the list.

Lastly, you can use the input() function to even read multiple values from users of different data types in one sentence. This can be shown in the below example:

Let us consider we want to ask the profile of the user as below code:

name, height, weight, age = input(" Enter the profile data as your name, height, weight, age\n using space to differentiate the values: ") .split() print(" The profile data of the user is as follows: ", name, height, weight, age) 

example 4-1

Conclusion

In Python also you can ask the user to enter the values or string or list of tuples, etc., through an input device and display it on the output screen or console. As in C language, we do this by using the scanf() function similarly in Python, it can be done using raw_input and input(), and to display these values obtained by these functions, we use the print() function. As we saw in this article raw_input() function is very rarely used as it can return only the values of the string data type. But the input() function is mostly used as it can accept the input of any data type and if we want to be surer, then we can even explicitly convert the value of the variable to the respective data type as input() function always converts any data type of the variable to string.

We hope that this EDUCBA information on “Python Input String” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Источник

Оцените статью