简体   繁体   English

如何在Python的if语句中使用While循环?

[英]How to use While loop within an if statement on python?

def change():
    if choice == 1:    #<--- issue here
        while True:
            amt = float(input("Enter amount of cash: $"))
            if amt >= a:
                print("Your change will be: ${:.2f}".format(amt - a))
                break
            else:
                print("Not enough, missing: ${:.2f}".format(a - amt))
                input("press enter to continue")


a = 15.60
b = 56.12
c = 89.53
d = 32.93
print("1. a: $15.60\t\t\t2. b: $56.12\n3. c: $89.53\t\t\t4. d: $32.93")
choice = input("Choose product (1-4): ")
change()

If I remove line 2, it would function properly but choice 1 would not be selected. 如果我删除第2行,它将正常运行,但不会选择选项1。 I'd like it so this would run while choice 1 is selected. 我希望它可以在选择选项1时运行。 For some reason it's not allowing me to put an if statement before while loop. 由于某种原因,它不允许我在while循环之前放置if语句。 Is there a solution? 有解决方案吗?

It's the problem in your input statement. 这是您输入语句中的问题。 In python 3 input get default as string.So you need convert it to integer as below. 在python 3中输入默认为字符串。因此您需要将其转换为整数,如下所示。

choice = int(input("Choose product (1-4): "))

在python 3.x中将字符串转换为整数使用int()

choice = int(input("Choose product (1-4): "))

Please try below code 请尝试以下代码

def change():
print(choice, choice == 1, type(choice), int(choice) == 1)
if int(choice) == 1:    #<--- issue here
    while True:
        amt = float(input("Enter amount of cash: $"))
        if amt >= a:
            print("Your change will be: ${:.2f}".format(amt - a))
            break
        else:
            print("Not enough, missing: ${:.2f}".format(a - amt))
            input("press enter to continue")


a = 15.60
b = 56.12
c = 89.53
d = 32.93
print("1. a: $15.60\t\t\t2. b: $56.12\n3. c: $89.53\t\t\t4. d: $32.93")
choice = input("Choose product (1-4): ")
change()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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