Python user input syntax

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

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

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

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

Читайте также:  Как работает рекурсия python

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 User Input from Keyboard – input() function

The prompt string is printed on the console and the control is given to the user to enter the value. You should print some useful information to guide the user to enter the expected value.

Getting User Input in Python

Here is a simple example of getting the user input and printing it on the console.

value = input("Please enter a string:\n") print(f'You entered ')

Python User Input

What is the type of user entered value?

The user entered value is always converted to a string and then assigned to the variable. Let’s confirm this by using type() function to get the type of the input variable.

value = input("Please enter a string:\n") print(f'You entered and its type is ') value = input("Please enter an integer:\n") print(f'You entered and its type is ')

Please enter a string: Python You entered Python and its type is Please enter an integer: 123 You entered 123 and its type is

How to get an Integer as the User Input?

There is no way to get an integer or any other type as the user input. However, we can use the built-in functions to convert the entered string to the integer.

value = input("Please enter an integer:\n") value = int(value) print(f'You entered and its square is ')

Python User Input Integer

Python user input and EOFError Example

When we enter EOF, input() raises EOFError and terminates the program. Let’s look at a simple example using PyCharm IDE.

value = input("Please enter an integer:\n") print(f'You entered ')
Please enter an integer: ^D Traceback (most recent call last): File "/Users/pankaj/Documents/PycharmProjects/PythonTutorialPro/hello-world/user_input.py", line 1, in value = input("Please enter an integer:\n") EOFError: EOF when reading a line

Python User Input EOFError

Python User Input Choice Example

We can build an intelligent system by giving choice to the user and taking the user input to proceed with the choice.

value1 = input("Please enter first integer:\n") value2 = input("Please enter second integer:\n") v1 = int(value1) v2 = int(value2) choice = input("Enter 1 for addition.\nEnter 2 for subtraction.\nEnter 3 for Multiplication.:\n") choice = int(choice) if choice == 1: print(f'You entered and and their addition is ') elif choice == 2: print(f'You entered and and their subtraction is ') elif choice == 3: print(f'You entered and and their multiplication is ') else: print("Wrong Choice, terminating the program.")

Here is a sample output from the execution of the above program.

Читайте также:  Https forum flprog ru viewtopic php

Python User Input Choice

Quick word on Python raw_input() function

The raw_input() function was used to take user input in Python 2.x versions. Here is a simple example from Python 2.7 command line interpreter showing the use of raw_input() function.

~ python2.7 Python 2.7.10 (default, Feb 22 2019, 21:55:15) [GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.37.14)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> value = raw_input("Please enter a string\n") Please enter a string Hello >>> print value Hello

This function has been deprecated and removed from Python 3. If you are still on Python 2.x versions, it’s recommended to upgrade to Python 3.x versions.

Conclusion

It’s very easy to take the user input in Python from the input() function. It’s mostly used to provide choice of operation to the user and then alter the flow of the program accordingly.

However, the program waits indefinitely for the user input. It would have been nice to have some timeout and default value in case the user doesn’t enter the value in time.

References:

Источник

Python User Input

Python User Input

While programming very often, we are required to take input from the user so as to manipulate the data and process it thereafter. This ensures the program’s dynamism and robustness as it is not hardcoded and can successfully execute at any random value given by the user. In this topic, we are going to learn about Python User Input.

Web development, programming languages, Software testing & others

In today’s article, we would learn about the concept of accepting input from the user at the run time of the program for Python programming language and process that data. This ensures proper communication between the program and the outside world.

Methods of Inputting Data

The following are the ways of inputting data from the user: –

Both basically do the same task, the only difference being the version of Python, which supports the two functions.

raw_input was used in older versions of Python, and it got replaced by input() in recent Python versions.

In this article, we would discuss input() as it is used in recent versions of Python.

Working of Python Input()

When we use the input() function in our program, the flow of execution is halted till the user inputs the data and clicks the Enter button. After that, the user’s value input is stored in some variable in the form of a string. No matter what data type the user intended their data to be, it gets stored as a string only. It needs to explicitly typecast to the desired format before use. Later we will look at such an example where if we do not typecast the data, it will result in an error.

Читайте также:  Php присвоить значение глобальной переменной

Now let us have a look at the syntax of input()

Now let us see some examples and discuss how to use input() to accept data from users for different scenarios.

Examples of Python User Input

Here are the following examples mention below:

Example #1

Inputting normal text from the keyboard

string1 = input() print(string1)

Python User Input output 1

Explanation

In the first line, we used the input() function to take input from the user and store it in the variable named string1. After we press the Enter button, we are instructed to provide our input by the show of a blank input box with a cursor blinking. When we provide the input and press the Enter button, then that value gets stored in the variable named string1. In the next line, when we are printing the variable, we actually see that the input provided by us is actually printed in the console.

Example #2

Inputting number from the console and finding its square

print("Enter number to find the square:") number = input() print("The Square of number <>".format(number,number**2))

Python User Input output 2

Explanation

Here we encounter a TypeError, and if we read the errorMessage, it suggests to us that the first argument, i.e. number variable string datatype. And because of that, it is not able to perform the power operation on that. It is important to note here that the input data type is always taken as a string, so it must be typecast to the desired datatype before it can be worked on.

Let us correct the code and have a look at the output.

print("Enter number to find the square:") number = input() number = int(number) print("The square of the number <> is <>".format(number,number**2))

output 3

Example #3

Inputting multiple numbers and finding out the maximum from them

import numpy as np print("How many numbers we want to find the maximum of:") n=int(input()) numbers = [] for i in range(0, n): ele = int(input("Enter elements: ")) numbers.append(ele) print("The Maximum Number is:", max(numbers))

output 4

Example #4

Inputting sentence and counting the number of characters in that

print("Enter the sentence :") sentence = input() length = len(sentence) print("The number of characters in the sentence is <>".format(length))

output 5

Conclusion

Finally, it is time to draw closure to this article. In today’s article, we learned about the input() function of Python. We looked at the syntax and discussed different examples and use cases. So next time you write a Python program, do remember to use the concepts of input() and test your program on many random user input data.

This is a guide to Python User Input. Here we discuss the methods, working, and the examples of Python User Input along with the appropriate syntax. You may also have a look at the following articles to learn more –

Источник

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