Контроль ввода в python

Контроль ввода в python

Last updated: Feb 20, 2023
Reading time · 6 min

banner

# Table of Contents

# Validating user input in Python

To validate user input:

  1. Use a while loop to iterate until the provided input value is valid.
  2. Check if the input value is valid on each iteration.
  3. If the value is valid, break out of the while loop.
Copied!
# ✅ Validating integer user input num = 0 while True: try: num = int(input("Enter an integer 1-10: ")) except ValueError: print("Please enter a valid integer 1-10") continue if num >= 1 and num 10: print(f'You entered: num>') break else: print('The integer must be in the range 1-10') # ---------------------------------------------- # ✅ Validating string user input password = '' while True: password = input('Enter your password: ') if len(password) 5: print('Password too short') continue else: print(f'You entered password>') break print(password)

The first example validates numeric user input in a while loop.

If the try block completes successfully, then the user entered an integer.

Copied!
num = 0 while True: try: num = int(input("Enter an integer 1-10: ")) except ValueError: print("Please enter a valid integer 1-10") continue if num >= 1 and num 10: print(f'You entered: num>') break else: print('The integer must be in the range 1-10')

The if statement checks if the integer is in the range 1-10 and if the condition is met, we break out of the while loop.

The break statement breaks out of the innermost enclosing for or while loop.

If the integer is not in the specified range, the else block runs and prints a message.

If the user didn’t enter an integer, the except block runs, where we use the continue statement to prompt the user again.

The continue statement continues with the next iteration of the loop.

When validating user input in a while loop, we use the continue statement when the input is invalid, e.g. in an except block or an if statement.

If the input is valid, we use the break statement to exit out of the while loop.

The input function takes an optional prompt argument and writes it to standard output without a trailing newline.

The function then reads the line from the input, converts it to a string and returns the result.

Note that the input() function is always guaranteed to return a string, even if the user enters a number.

You can use the same approach when validating user input strings.

# Prompting the user for input until validation passes

Here is an example that prompts the user for input until they enter a value that is at least 5 characters long.

Copied!
password = '' while True: password = input('Enter your password: ') if len(password) 5: print('Password too short') continue else: print(f'You entered password>') break print(password)

The while loop keeps iterating until the user enters a value that has a length of at least 5.

If the value is at least 5 characters long, we use the break statement as the input is valid.

You can use the boolean OR and boolean AND operators if you need to check for multiple conditions.

# Validating user input based on multiple conditions (OR)

Here is an example that checks if the input value is at least 5 characters long and not in a list of values.

Copied!
password = '' common_passwords = ['abcde', 'asdfg'] while True: password = input('Enter your password: ') if len(password) 5 or password in common_passwords: print('Pick a strong password') continue else: print(f'You entered password>') break print(password)

The if statement checks if the password is less than 5 characters or is in the commonly used passwords list.

We used the boolean or operator, so the if block runs if either of the two conditions is met.

If the password is less than 5 characters or is contained in the commonly used passwords list, we continue to the next iteration and prompt the user again.

# Validating user input based on multiple conditions (AND)

Use the and boolean operator if you need to check if multiple conditions are met when validating the input.

Copied!
password = '' common_passwords = ['abcde', 'asdfg'] while True: password = input('Enter your password: ') if len(password) > 5 and password not in common_passwords: print(f'You entered password>') break else: print('Pick a strong password') continue print(password)

We used the and boolean operator, so for the if block to run both conditions have to be met.

The password has to be longer than 5 characters and it has to not be in the commonly used passwords list.

If the conditions are met, we use the break statement to exit out of the while True loop.

If the conditions aren’t met, we use the continue statement to continue to the next iteration.

# Accept input until Enter is pressed in Python

To accept input until the Enter key is pressed:

  1. Declare a variable that stores an empty list.
  2. Use a while loop to iterate an arbitrary number of times.
  3. Append each user input value to the list.
  4. Break out of the while loop when the user presses Enter.
Copied!
# ✅ When taking strings as input my_list = [] user_input = '' while True: user_input = input('Enter a string: ') # 👇️ Take input until Enter is pressed without value if user_input == '': print('User pressed enter') break my_list.append(user_input) print(my_list) # --------------------------------------------- # ✅ When taking integers as input my_list = [] user_input = '' while True: user_input = input('Enter a number: ') # 👇️ Take input until Enter is pressed without value if user_input == '': print('User pressed enter') break try: my_list.append(int(user_input)) except ValueError: print('Invalid number.') continue print(my_list)

The examples repeat the program and keep taking user input until the user presses Enter without typing in a value.

This could be any other condition, e.g. if the user types done or if the list stores at least 3 input values.

The first example takes strings as input from the user.

Copied!
my_list = [] user_input = '' while True: user_input = input('Enter a string: ') # 👇️ Take input until Enter is pressed without value if user_input == '': print('User pressed enter') break my_list.append(user_input) print(my_list)

We used a while loop to take user input while iterating an arbitrary number of times.

If the user presses Enter without typing in a value, we break out of the while loop.

The break statement breaks out of the innermost enclosing for or while loop.

The list.append() method adds an item to the end of the list.

Here is an example that keeps repeating the program until the user input is correct when taking integers.

Copied!
my_list = [] user_input = '' while True: user_input = input('Enter a number: ') # 👇️ Take input until Enter is pressed without value if user_input == '': print('User pressed enter') break try: my_list.append(int(user_input)) except ValueError: print('Invalid number.') continue print(my_list)

The input function takes an optional prompt argument and writes it to standard output without a trailing newline.

The function then reads the line from the input, converts it to a string and returns the result.

We used the int() class to convert each string to an integer.

The try/except statement is used to handle the ValueError that is raised if an invalid integer is passed to the int() class.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Получение корректного ввода от пользователя в Python

Python developer handling user input errors.

Одной из распространенных проблем, с которой сталкиваются разработчики при работе с Python, является получение корректного ввода от пользователя. Для примера рассмотрим следующий код:

age = int(input("Введите ваш возраст: ")) if age >= 18: print("Вы можете голосовать на выборах!") else: print("Вы не можете голосовать на выборах.")

Данный код будет работать корректно, пока пользователь вводит числа. Однако, если пользователь введет что-либо другое, например, строку или символ, программа выдаст ошибку и завершится.

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

Чтобы избежать такой ситуации, можно использовать цикл while и обработку исключений. Вот как это можно сделать:

while True: try: age = int(input("Введите ваш возраст: ")) if age >= 18: print("Вы можете голосовать на выборах!") else: print("Вы не можете голосовать на выборах.") break except ValueError: print("Извините, я не понял вас. Попробуйте снова.")

В этом случае, если пользователь введет некорректные данные, программа выдаст сообщение об ошибке и попросит ввести данные снова, а не завершится с ошибкой. Цикл while True будет повторяться до тех пор, пока пользователь не введет корректные данные и break не прервет его.

Таким образом, с помощью цикла while и обработки исключений можно обеспечить получение корректного ввода от пользователя в Python.

Источник

Python проверка ввода числа (или текста)

Юн Сергей

Несколько алгоритмов для проверки ввода числа (строки и т.д) в Python, оформленные функциями.

Проверка ввода числа (или текста)

Вариант ValueError

def getNumber01(): # Первый вариант while type: getNumber = input('Введите число: ') # Ввод числа try: # Проверка что getTempNumber преобразуется в число без ошибки getTempNumber = int(getNumber) except ValueError: # Проверка на ошибку неверного формата (введены буквы) print('"' + getNumber + '"' + ' - не является числом') else: # Если getTempNumber преобразован в число без ошибки, выход из цикла while break return abs(getNumber) # возвращает модуль getTempNumber (для искл. отрицат. чисел) print(getNumber01())

Вариант isdigit()

def getNumber02 (): while True: getNumber = input('Введите целое положительное число: ') # Ввод числа if getNumber.isdigit() : return getNumber print(getNumber02())

You may also like

Домашняя работа по курсу Веб-вёрстка от Skillbox

Отключение перенаправления файлов Python (Wow64)

Проверка и установка принтера по умолчанию

Оставьте комментарий X

You must be logged in to post a comment.

Источник

Читайте также:  Fetch using MySQL and Node.js
Оцените статью