我正在制作一个函数来检测Python中的输入类型,但是我无法使其正常工作 [英] I am making a function to detect input types in Python and I can't make it work

查看:82
本文介绍了我正在制作一个函数来检测Python中的输入类型,但是我无法使其正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在将质数检测器作为一个项目.我对编程非常陌生,我的朋友给我看了一些python.我想做一个函数来检测用户是否输入了数字(例如5,28,156,42,63),以及是否输入了其他东西(例如香蕉,裤子或谷物),从而给他们一个自定义错误说无效数字.请重试",然后循环执行程序,直到输入数字为止.

So I am making a prime number detector as a project. I’m VERY new to programming and my friend showed me a little python. I want to make a function that detects if the user puts in a number for the input (like 5,28,156,42,63) and if the put in something else (like banana,pants,or cereal) to give them a custom error saying "Invalid Number. Please Try Again" and then looping the program until they put in a number.

请帮助我完成这项工作.

Please help me make this work.

def number_checker():
    user_number = int(input('Please enter a Number: '))
    check = isinstance(user_number, int)
    if check == True:
        print ('This is a number')
    if check == False:
        print ('This is not a number')

推荐答案

1)如果无法将输入字符串转换为int,则将输入强制转换为int会引发异常.

1) Casting input to int would raise an exception if the input string cannot be converted to int.

user_number = int(input('Please enter a Number: '))
              ^^^

2)用int实例交叉验证user_number是没有意义的,因为它已经是int
3)您可以尝试

2) It does not make sense to cross-verify user_number with int instance as it would already be int
3) You can try

def number_checker():                          
    while not input("enter num: ").isdigit():  
        print("This is not a number")          
    print("This is a number")                  
number_checker()                     

这篇关于我正在制作一个函数来检测Python中的输入类型,但是我无法使其正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆