Python if语句问题和循环

时间:2015-07-26 07:30:01

标签: python if-statement

这更多是来自ubuntu社区的求助。我做了很多搜索和阅读,我想我错过了一些东西。我正在尝试在python中编写一个非常基本的程序,这就是问题:我问问题raw_input("question" ),然后分配一个if语句,如下所示: 这是错误:

The debugged program raised the exception unhandled NameError
"name 'tx_rate' is not defined"
File: /home/Budget.py, Line: 47.

这是代码:

ans1 = raw_input("Do you know your tax rate?" )
if 'ans1' == 'yes':
    tx_rate = raw_input("What is it?")
    float(tx_rate)
    tx_rate = float(tx_rate)
    print "Thank you! Will use tax rate %s, instead of 0.15!" % (tx_rate)
elif "ans1" == "no":
    print "Okay, that's alright, we'll use 0.15 as the average tax rate!"
    tx_rate = 0.15
else:
    print "Sorry, incorrect value, please answer yes or no."
gross_pay = (hrs * rate) * 4.0
net_pay = gross_pay - (gross_pay * tx_rate) # [That last line is line 47]

错误来自tx_rate的变量从未被分配,因为天气我不是或不是它运行else选项

所以基本上它问我“你知道你的税率吗?”无论我输入什么,它都会将我带到else选项并显示错误。这告诉我我需要将其循环回来,我该怎么做?那么当调用“else”时,让它重新运行问题,直到if或elif满意为止?

3 个答案:

答案 0 :(得分:1)

您的代码已修订:

ans1 = raw_input("Do you know your tax rate?" )
hrs = 10
while True:
    if ans1 == 'yes':
         tx_rate = raw_input("What is it?")
         float(tx_rate)
         tx_rate = float(tx_rate)
         print "Thank you! Will use tax rate %s, instead of 0.15!" % (tx_rate)
         break
    elif ans1 == "no":
        print "Okay, that's alright, we'll use 0.15 as the average tax rate!"
        tx_rate = 0.15
        break
    else:
        print "Sorry, incorrect value, please answer yes or no."
        ans1 = raw_input("Do you know your tax rate?" )
gross_pay = (hrs * tx_rate) * 4.0
net_pay = gross_pay - (gross_pay * tx_rate)
print(net_pay)

我的输出是:

>>> ================================ RESTART ================================
>>> 
Do you know your tax rate?no
Okay, that's alright, we'll use 0.15 as the average tax rate!
5.1
>>> ================================ RESTART ================================
>>> 
Do you know your tax rate?yes
What is it?0.151
Thank you! Will use tax rate 0.151, instead of 0.15!
5.12796
>>> 

答案 1 :(得分:0)

首先,请注意ifelse条件错误 - 它们会比较字符串 'ans1'而不是变量ans1

修复后,有几种方法可以解决您的问题。一种方法是使用while循环继续,直到提供'yes''no'为止:

ans1 = None

while ans1 not in ['yes','no']:
    ans1 = raw_input("Do you know your tax rate?" )
    if ans1 == 'yes':
        tx_rate = raw_input("What is it?")
        float(tx_rate)
        tx_rate = float(tx_rate)
        print "Thank you! Will use tax rate %s, instead of 0.15!" % (tx_rate)
    elif ans1 == "no":
        print "Okay, that's alright, we'll use 0.15 as the average tax rate!"
        tx_rate = 0.15
    else:
        print "Sorry, incorrect value, please answer yes or no."

答案 2 :(得分:0)

您应该尝试在if ... else条件之前定义tx_rate = 0.15。因为当你的用户没有输入任何你要求是或否的第一个问题时,它直接进入没有tx_rate的else部分,所以给你错误“变量未定义”