python判断input输入的是否为数字,检查输入是否具有int,float或bool的Python程序

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.

解决方案

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.

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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值