简体   繁体   中英

How can test a variable if it is an integer?

As the title might specify, I want to ask how can I test a variable if it is an integer. I have seen other topics and they don't seem to have code that works or that I know how to use.

print("Enter the weight of the bag in grams.")

weight = float(input()) # float was used as it might be a decimal sometimes

amtcoin = weight / 3.56

How do I test if amtcoin is a integer? As the variable suggests, it is the amount of coins and you cannot have a fraction of a coin. Thanks.

您可以像is_integer一样转换为float,然后使用is_integer方法进行检查:

float(weight).is_integer()

amtcoin variable is instance of class you declare it. Declare it as float and if you want to know if it's a fraction or not check amtcoin % 1 == 0

Try something like this:

if int(amtcoin) == amtcoin:
    do_something()

If it is int , this condition will be met.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM