Проверка ввода числа питон

Validation¶

When we accept user input we need to check that it is valid. This checks to see that it is the sort of data we were expecting. There are two different ways we can check whether data is valid.

Method 1: Use a flag variable. This will initially be set to False . If we establish that we have the correct input then we set the flag to True . We can now use the flag to determine what we do next (for instance, we might repeat some code, or use the flag in an if statement).

Method 2: Use try/except. Here, we try to run a section of code. If it doesn’t work (for instance, we try to convert a string to a number, but it doesn’t contain a number) then we run the except block of code.

Validation technique Meaning
Type check Checking the data type e.g. int, float etc.
Length check Checking the length of a string
Range check Checking if a number entered is between two numbers

Easy example¶

while True: try: age = int(input('How old are you? ')) break except ValueError: print('Please enter a whole number') print('Your age is: ' + str(age)) 
How old are you? asdf Please enter an whole number How old are you? 14.5 Please enter an whole number How old are you? 15 Your age is: 15

This example isn’t easy to understand if it is new to you, but it is the easiest way to ask the user to enter an input and check the input contains an integer.

Читайте также:  login here

Syntax¶

Using a flag¶

flagName = False while not flagName: if [Do check here]: flagName = True else: print('error message') 

Using an exception¶

while True: try: [run code that might fail here] break except: print('This is the error message if the code fails') print('run the code from here if code is successfully run in the try block of code above') 

Examples¶

Example 1 — Check if input contains digits using a flag¶

validInteger = False while not validInteger: age = input('How old are you? ') if age.isdigit(): validInteger = True else: print('You must enter a valid number') print('You are ' + str(age)) 
How old are you? asdf You must enter a valid number How old are you? 15.0 You must enter a valid number How old are you? 18.2 You must enter a valid number How old are you? -3 You must enter a valid number How old are you? 15 You are 15

This has the same result as the easy example above which makes use of try/except to do the same thing.

This example is fine for checking integers, but will not check floating point numbers or negative numbers. Use try/except to do this — see examples below.

Example 2 — A range and type check using a flag and exception¶

isTeenager = False while not isTeenager: try: age = int(input('How old are you? ')) if age >= 13 and age  19: isTeenager = True except: print('You must enter a valid number between 13 and 19') print('You are a teenager aged ' + str(age)) 
How old are you? asdf You must enter a valid number between 13 and 19 How old are you? -3 How old are you? 15.2 You must enter a valid number between 13 and 19 How old are you? 12 How old are you? 14 You are a teenager aged 14

Example 3 — A length check using a flag¶

isLongEnough = False while not isLongEnough: password = input('Enter password at least 5 characters: ') if len(password) >= 5: isLongEnough = True else: print('Password entered is too short') print('Your password entered is: ' + password) 
Enter password at least 5 characters: asdf Password entered is too short Enter password at least 5 characters: 1234 Password entered is too short Enter password at least 5 characters: ad4fgj Your password entered is: ad4fgj

Example 4 — Multiple validations using a flag¶

isFourDigitPassword = False oldPassword = '2154' while not isFourDigitPassword: password = input('Enter a new PIN: ') if len(password) == 4 and password.isdigit() and password != oldPassword: isFourDigitPassword = True else: print('Your PIN must be 4 digits and not the same as your old PIN') print('Your PIN entered is: ' + password) 
Enter a new PIN: asdf Your PIN must be 4 digits and not the same as your old PIN Enter a new PIN: 2154 Your PIN must be 4 digits and not the same as your old PIN Enter a new PIN: 12345 Your PIN must be 4 digits and not the same as your old PIN Enter a new PIN: 123 Your PIN must be 4 digits and not the same as your old PIN Enter a new PIN: 1234 Your PIN entered is: 1234

Example 5 — Check for a float using an exception¶

while True: try: height = float(input('What is your height in cm? ')) break except ValueError: print('Please enter a number') print('Your height is: ' + str(height)) 
What is your height in cm? 5 foot 4 inches Please enter a number What is your height in cm? 162.5 Your height is: 162.5

Example 6 — A function to get an integer from the user¶

def getInteger(message): while True: try: userInt = int(input(message)) return userInt except ValueError: print('You must enter an integer') age = getInteger('What is your age? ') players = getInteger('How many players in the game? ') 
What is your age? fifteen You must enter an integer What is your age? 15 How many players in the game? two You must enter an integer How many players in the game? 2.2 You must enter an integer How many players in the game? 2

You can reuse this function in your own code as an easy way to get an integer from a user.

Example 7 — A function to get a floating point number from the user¶

def getFloat(message): while True: try: userFloat = float(input(message)) return userFloat except ValueError: print('You must enter a number') height = getFloat('How tall are you? ') print('Your height is: ' + str(height)) 
How tall are you? 1 meter 60 You must enter a number How tall are you? 1.60 Your height is: 1.6

Key points¶

In general we don’t use while True: and break as this can end up creating poor quality code or infinite loops. In the case of try/except, this is acceptable for getting user input and validation.

© Copyright 2017, Axsied Ltd. All rights reserved.

Источник

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

Проверка ввода целого числа (Telebot)
Достаточно долго не получается реализовать проверку ввода числа с некоторыми условиями в Telebot. .

Проверка ввода на числа
Добрый вечер, необходимо проверить, что N – число в пределах от 1 до 10. Если одно из условий не.

Проверка ввода числа
Подскажите, как организовать проверку, того что введено число, а не буквы?

Проверка ввода числа
if (a != int.MaxValue && a != int.MinValue && b != int.MaxValue && b != int.MinValue) < .

Проверка ввода на числа
Друзья, подскажите, как лучше реализовать проверку, дабы при вводе НЕ числа, либо при нажатии любой.

Лучший ответ

Сообщение было отмечено Mural как решение

Решение

while True: try: n = int(input("Введите число: ")) if n  1: raise Exception() print("Сумма чисел от 1 до n: ", sum([i for i in range(1,n+1)])) break except Exception as e: print('Неверный формат')

tooru, а возможно сделать чтобы выдавало 2 разные ошибки? на символы — неверный формат, а на числа 110 «Введите число от 1 до 10»?

Добавлено через 6 минут
меньше 1 или символ*

while n.isalpha() or int(n) < 0:
n = input(«Введите число: «)n = int(n)

print(«Сумма чисел от 1 до n: «, sum([i for i in range(1, n + 1)]))

Лучший ответ

Сообщение было отмечено Mural как решение

Решение

while True: try: n = int(input("Введите число: ")) if n  1 or n > 10: raise Exception print("Сумма чисел от 1 до n: ", sum([i for i in range(1,n+1)])) break except ValueError: print('Неверный формат') except Exception: print('Введите число от 1 до 10')
n = input("Введите число: ") while n.isalpha() or int(n)  0: n = input("Введите число: ") n = int(n) print("Сумма чисел от 1 до n: ", sum([i for i in range(1, n + 1)]))

Проверка правильности ввода числа
Всем доброго времени суток. Подскажите пожалуйста как осуществить: Нужно выполнить проверку на.

Проверка правильности ввода числа
<form action="31.php" name="31"> <p>Введите дату <input type="text" name="day".

Проверка ввода неотрицательного числа
Надо чтобы при вводе отрицательного числа выводило ошибку или предупреждение. Производить действия.

Проверка ввода числа на корректность
На отрицательность число проверил. Если ввожу отрицательное, то выводится сообщение: "Вы ввели.

Проверка правильности ввода числа
Всем привет! Прошу помочь с такой задачей: Дано число в двоичной системе счисления. Проверить.

Источник

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.

Источник

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