Python input int str

Пользовательский ввод (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

Читайте также:  Document

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

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

☝️ Важно : если вы решили преобразовать строку в число, но при этом ввели строку (например: 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 input() Function

Python Input Function

The input() function in Python makes it very easy to get input from users of your application. The input function is built in just like the print function and its use is quite common. When you call the input function(), you can think of it as an expression that evaluates to whatever the user typed in at the prompt. This always gets returned as a string so if you want to use numbers as input, you will need to handle that by using the int() function. we’ll see several examples of how to use this function here.

The input() Function

  • Takes in a prompt
  • Displays prompt on the screen
  • The user can type a response to the prompt
  • Returns user input as a string

User Name As Input

One of the classic examples of the input function in Python is getting the name of the user of your application. So let’s go ahead and do that now we can write some code that will prompt the user for their name and store that result in a ‘name’ variable. Here we go:

python input jupyter notebook

The snippet above is actually something called a Jupyter Notebook, which is a really interesting tool to use for Python programming. By using Jupyter Notebook in this example, it makes it really easy to see what the prompt looks like when calling that input() function. We can type some characters into the prompt for our name. Then, we can add the code to print() that variable.

input string jupyter python

We might want to make that output just a little more interesting. In the following Jupyter Cell, we can concatenate some additional text with the result stored in the name variable to make the output a little more pleasing.

python concatenate with print

Using input() In A Loop

You might find a case where you want to prompt the user for some input more than once. In that case, you can use the input function inside of a loop. The loop will continue to prompt the user for some input until a specific condition is met. In this next example, we are going to ask the user what are some names that they like. The logic for this is put inside of a while loop. Inside the while loop, we can use the if-else construct to determine if we are going to print out the name or break out of the loop.

python input inside loop

Using input() With Numbers

In order for your program to be useful, you might need to accept input in the form of numbers from your user. Let’s look at a simple example that uses the input function to get 2 numbers from the user. The goal of this program is to record those two values, add them together, and print out the result for the user. Let’s try this now.

python input number as string

Wait a second. What happened here? Our program asked the user for the first number. We typed in the number 5. The program then asked the user for the second number. We typed in the value of four. Then the program prints out a message that the sum of five and four is 54. That doesn’t seem correct, does it? Let’s try this again with a small adjustment.

int() and str()

Before we look at the code that is going to fix the bug that the above example has, let’s talk about two new utility functions in Python. These are the int() function and the str() function. These functions allow you to transform a data type between an integer and a string. Y’all need to do this because it is quite possible to add numbers together in Python, and it is also possible to add strings together in Python. What you cannot do is to add integers and strings to each other. So this next example is a refactor of the program making use of both the int() and str() functions so that we get the output we would expect.

python input int str

input() with Loop, int(), and str()

In this example, we will make use of the input function inside of a while loop in Python. The program will ask the user for a number or they can type the letter Q to quit the program. While the condition is true inside of the loop the program will convert the number that the user typed from decimal to binary format. For each number the user types, the program will print out the binary equivalent.

python input loop int str

Show Me A Dog!

We have one more program to go over that makes perfect use of the input() function. This program is going to ask a user if they would like to see a dog. I mean, who doesn’t want to see a Dog, right?! So what we can do is have the user simply type the letter ‘y’ if they want to see a dog, and ‘n’ if they do not. We’ll put this inside of a loop so that you can keep looking at dogs for as long as you like. We needed to add some special modules from IPython.display such as display and HTML in order for images to display inside of our Jupyter notebook. Let’s see this in action.

ipython display html

python show me a dog

Python input() Function Summary

Python input() is a built-in function used to read a string from the user’s keyboard. The input() function returns the string typed in by the user in the standard input. When you call this input() function, the Python Interpreter waits for user input from the keyboard. When the user enters types in some data, each character is echoed to the output. This helps the user as feedback of what value is being inputted. After you enter the value and hit Return or Enter key, the string that is typed in by you until this last enter key is returned by the input() function.

Источник

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