检查输入是否具有int,float或bool的Python程序 [英] Python program that checks wether an input has an int, float or bool

查看:128
本文介绍了检查输入是否具有int,float或bool的Python程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图在此处制作一个要求输入的程序,然后检查输入是否具有整数,布尔值或浮点数,并且如果具有这些字符中的任何字符,则它将再次要求输入.我想这样做,而不是像用户输入intbool那样仅编写str(input()),它将打印错误并停止程序.

So I'm trying to make a program here that asks for an input but then checks whether the input has an integer, boolean or float and if it has any of these characters then it will ask for the input again. I want to do that instead of just writing str(input()) as if the user inputs an int or bool etc it will print error and stop the program.

这是我目前所拥有的,但是它不起作用:

Here is what I have at the moment but it isn't working:

x=input('Enter your name: ')
while True:
    if x==int or x==bool or x==float:
       print('error, incorrect name please try again!')
    else:
       print('Nice name', x, '!')
       break

如果可以帮助您,请回复.

If you can help please reply.

推荐答案

似乎您想检查自己的名字仅包含字母数字字符和潜在的空格.在按空格分割后,您可以通过str.isalpha来实现此目的.

It seems you want to check your name only includes alphanumeric characters and potentially whitespace. You can achieve this via str.isalpha after splitting by whitespace.

请记住,input 总是返回一个字符串,因此您需要使用字符串方法来验证用户输入.您可以使用if not x作为附加验证来检查空字符串. typeisinstance的使用是不合适的.

Remember that input always returns a string, so you need to use string methods to validate user input. You can check for empty strings using if not x as an additional validation. Use of type or isinstance is inappropriate.

此外,您需要在while循环中包含input,以便用户能够重新输入名称.这是一个示例:

In addition, you need to include input within your while loop so that a user is able to re-enter a name. Here's an example:

while True:
    x = input('Enter your name: ')
    if (not x) or (not all(i.isalpha() for i in x.split())):
        print('Error, incorrect name please try again!')
    else:
        print('Nice name', x, '!')
        break

这篇关于检查输入是否具有int,float或bool的Python程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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