Python input processing when input is a float or s

2019-09-19 05:20发布

I was hoping someone could help or hint to where I'm going wrong with this Python homework assignment:

number = int(input("Enter a number"))
if number == int or float:
    print(number * number, number * number * number, number ** 4)
elif number != int or float:
    print("This is not a valid number")

It runs fine with a whole number, but not with a float or a string. I think it's because number is set to look for an integer, but I'm not sure what to substitute that with in order to make it work.

3条回答
Ridiculous、
2楼-- · 2019-09-19 05:59

you can wrap around input around a try ... except.

something = input()

try:
    something = int(something)
except:
    print("not an int")
查看更多
狗以群分
3楼-- · 2019-09-19 06:01

You want to use a try... except... else block:

try:
    number = float(input("Enter a number"))
except ValueError:
    print("This is not a valid number")
else:
    print(number * number, number * number * number, number ** 4)
查看更多
Juvenile、少年°
4楼-- · 2019-09-19 06:14

Can you just replace the int with a float? like this: "number = float(input("Enter a number"))"

I think it solves your problem. Anyway we could use a little more description.

Good luck!

查看更多
登录 后发表回答