Dylan
Dylan

Reputation: 45

Python input processing when input is a float or string

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.

Upvotes: 0

Views: 2018

Answers (3)

pzp
pzp

Reputation: 6597

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)

Upvotes: 1

Fernando Vaz
Fernando Vaz

Reputation: 9

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!

Upvotes: 0

GIRISH RAMNANI
GIRISH RAMNANI

Reputation: 624

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

something = input()

try:
    something = int(something)
except:
    print("not an int")

Upvotes: 0

Related Questions