Проверка ввода цифр python

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

Достаточно часто требуется узнать: записано ли в переменной число. Такая ситуация может возникнуть при обработке введенных пользователем данных. При чтении данных из файла или при обработке полученных данных от другого устройства.

В Python проверка строки на число можно осуществить двумя способами:

  • Проверить все символы строки что в них записаны цифры. Обычно используется для этого функция isdigit.
  • Попытаться перевести строку в число. В Python это осуществляется с помощью методов float и int. В этом случае обрабатывается возможное исключение.

Рассмотрим как применяются эти способы на практике.

isdigit, isnumeric и isdecimal

У строк есть метод isdigit, который позволяет проверить, являются ли символы, являются ли символы, из которых состоит строка цифрами. С помощью этого метода мы можем проверить, записано ли в строку целое положительное число или нет. Положительное — это потому, что знак минус не будет считаться цифрой и метод вернет значение False.

a = '0251' print(a.isdigit()) True

Если в строка будет пустой, то функция возвратит False.

Читайте также:  Как посчитать ema python

Методы строки isnumeric и isdecimal работают аналогично. Различия в этих методах только в обработке специальных символов Unicode. А так как пользователь будет вводить цифры от 0 до 9, а различные символы, например, дробей или римских цифр нас не интересуют, то следует использовать функцию isdigit.

Проверка с помощью исключения

Что же делать, если требуется проверить строку на отрицательное число. В Python с помощью isdigit не удастся определить отрицательное число или число с плавающей точкой. В этом случае есть универсальный и самый надежный способ. Надо привести строку к вещественному числу. Если возникнет исключение, то значит в строке записано не число.

Приведем функцию и пример ее использования:

def is_number(str): try: float(str) return True except ValueError: return False a = '123.456' print(is_number(a)) True

Для целых чисел

Аналогично можно сделать и проверку на целое число:

def is_int(str): try: int(str) return True except ValueError: return False a = '123.456' print(is_int(a)) False

Источник

Python: проверка, является ли переменная числом

В этой статье мы рассмотрим несколько примеров того, как проверить, является ли переменная числом в Python.

Python имеет динамическую типизацию. Нет необходимости объявлять тип переменной во время ее создания — интерпретатор определяет тип во время выполнения:

variable = 4 another_variable = 'hello' 

Кроме того, переменную можно переназначить новому типу в любой момент:

# Присвойте числовое значение variable = 4 # Переназначить строковое значение variable = 'four' 

Этот подход, имея преимущества, также знакомит нас с несколькими проблемами. А именно, когда мы получаем переменную, мы обычно не знаем, какого она типа. Если мы ожидаем число, но получаем неопределенный variable , мы захотим проверить, является ли он числом, прежде чем выполнять какие-то действия.

Использование функции type()

В Python функция type() возвращает тип аргумента:

myNumber = 1 print(type(myNumber)) myFloat = 1.0 print(type(myFloat)) myString = 's' print(type(myString)) 

Таким образом, способ проверки типа:

myVariable = input('Enter a number') if type(myVariable) == int or type(myVariable) == float: # Do something else: print('The variable is not a number') 

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

Если бы мы просто сказали if type(var) == int or float , что вроде бы нормально, возникла бы проблема:

myVariable = 'A string' if type(myVariable) == int or float: print('The variable a number') else: print('The variable is not a number') 

Это, независимо от ввода, возвращает:

Это потому, что Python проверяет значения истинности утверждений. Переменные в Python могут быть оценены как True за исключением False , None , 0 и пустых [] , <> , set() , () , » или «» .

Следовательно, когда мы пишем or float в нашем условии, это эквивалентно записи or True , которая всегда будет возвращать True .

numbers.Number

Хороший способ проверить, является ли переменная числом — это модуль numbers . Вы можете проверить, является ли переменная экземпляром класса Number , с помощью функции isinstance() :

import numbers variable = 5 print(isinstance(5, numbers.Number))

Примечание. Этот подход может неожиданно работать с числовыми типами вне ядра Python. Некоторые фреймворки могут иметь нечисловую реализацию Number , и в этом случае этот подход вернет ложный результат False .

Использование блока try-except

Другой способ проверить, является ли переменная числом — использовать блок try-except. В блоке try мы преобразуем данную переменную в int или float . Успешное выполнение блока try означает, что переменная является числом, то есть либо int , либо float :

myVariable = 1 try: tmp = int(myVariable) print('The variable a number') except: print('The variable is not a number')

Это работает как для int, так и для float, потому что вы можете привести int к float и float к int.

Если вы специально хотите только проверить, является ли переменная одной из них, вам следует использовать функцию type() .

String.isnumeric()

В Python isnumeric() — это встроенный метод, используемый для обработки строк. Методы issnumeric() возвращают «True», если все символы в строке являются числовыми символами. В противном случае он возвращает «False».
Эта функция используется для проверки, содержит ли аргумент все числовые символы, такие как: целые числа, дроби, нижний индекс, верхний индекс, римские цифры и т.д. (Все написано в юникоде)

string = '123ayu456' print(string.isnumeric()) string = '123456' print( string.isnumeric()) 

String.isdigit()

Метод isdigit() возвращает истину, если все символы являются цифрами, в противном случае значение False.

Показатели, такие как ², также считаются цифрами.

print("\u0030".isdigit()) # unicode for 0 print("\u00B2".isdigit()) # unicode for ² 

Источник

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.

Источник

Check user Input is a Number or String in Python

In this lesson, you will learn how to check user input is a number or string in Python. We will also cover how to accept numbers as input from the user. When we say a number, it means it can be integer or float.

Understand user input

Python 3 has a built-in function input() to accept user input. But it doesn’t evaluate the data received from the input() function, i.e., The input() function always converts the user input into a string and then returns it to the calling program.

python check input is a number or a string

Let us understand this with an example.

number1 = input("Enter number and hit enter ") print("Printing type of input value") print("type of number ", type(number1))
Output Enter number and hit enter 10 Printing type of input value type of number class 'str'

As you can see, The output shows the type of a variable as a string (str).

Solution: In such a situation, We need to convert user input explicitly to integer and float to check if it’s a number. If the input string is a number, It will get converted to int or float without exception.

Convert string input to int or float to check if it is a number

How to check if the input is a number or string in Python

  1. Accept input from a user Use the input() function to accept input from a user
  2. Convert input to integer number To check if the input string is an integer number, convert the user input to the integer type using the int() constructor.
  3. Convert input to float number To check if the input is a float number, convert the user input to the float type using the float() constructor.
  4. Validate the result If an input is an integer or float number, it can successfully get converted to int or float type. Else, we can conclude it is a string

Note: If an input is an integer or float number, it can successfully get converted to int or float, and you can conclude that entered input is a number. Otherwise, You get a valueError exception, which means the entered user input is a string.

def check_user_input(input): try: # Convert it into integer val = int(input) print("Input is an integer number. Number = ", val) except ValueError: try: # Convert it into float val = float(input) print("Input is a float number. Number = ", val) except ValueError: print("No.. input is not a number. It's a string") input1 = input("Enter your Age ") check_user_input(input1) input2 = input("Enter any number ") check_user_input(input2) input2 = input("Enter the last number ") check_user_input(input2)
Output Enter your Age 28 Input is an integer number. Number = 28 Enter any number 3.14 Input is a float number. Number = 3.14 Enter the last number 28Jessa No.. input is not a number. It's a string
  • As you can see in the above output, the user has entered 28, and it gets converted into the integer type without exception.
  • Also, when the user entered 3.14, and it gets converted into the float type without exception.
  • But when the user entered a number with some character in it (28Jessa), Python raised a ValueError exception because it is not int.

Use string isdigit() method to check user input is number or string

Note: The isdigit() function will work only for positive integer numbers. i.e., if you pass any float number, it will not work. So, It is better to use the first approach.

Let’s execute the program to validate this.

def check_is_digit(input_str): if input_str.strip().isdigit(): print("User input is Number") else: print("User input is string") num1 = input("Enter number and hit enter") check_is_digit(num1) num2 = input("Enter number and hit enter") check_is_digit(num2) 
Output Enter number and hit enter 45 User input is Number Enter number and hit enter 45Jessa User input is string

Also, If you can check whether the Python variable is a number or string, use the isinstance() function.

num = 25.75 print(isinstance(num, (int, float))) # Output True num = '28Jessa' print(isinstance(num, (int, float))) # Output False

Only accept a number as input

Let’s write a simple program in Python to accept only numbers input from the user. The program will stop only when the user enters the number input.

while True: num = input("Please enter a number ") try: val = int(num) print("Input is an integer number.") print("Input number is: ", val) break; except ValueError: try: float(num) print("Input is an float number.") print("Input number is: ", val) break; except ValueError: print("This is not a number. Please enter a valid number") 
Output Please enter a number 28Jessa This is not a number. Please enter a valid number Please enter a number 28 Input is an integer number. Input number is: 28

Practice Problem: Check user input is a positive number or negative

user_number = input("Enter your number ") print("\n") try: val = int(user_number) if val > 0: print("User number is positive ") else: print("User number is negative ") except ValueError: print("No.. input string is not a number. It's a string")

Next Steps

Let me know your comments and feedback in the section below.

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

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