Python如果以利夫其他政治家

2024-04-29 11:15:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图用python创建一个计算运费的程序。

但是,我无法将程序运行到它正常工作的位置。

我的总数是6美元,加拿大是8美元。我好像不能通过。

total = raw_input('What is the total amount for your online shopping?')
country = raw_input('Shipping within the US or Canada?')

if country == "US":
    if total <= "50":
        print "Shipping Costs $6.00"
    elif total <= "100":
            print "Shipping Costs $9.00"
    elif total <= "150":
            print "Shipping Costs $12.00"
    else:
        print "FREE"

if country == "Canada":
    if total <= "50":
        print "Shipping Costs $8.00"
    elif total <= "100":
        print "Shipping Costs $12.00"
    elif total <= "150":
        print "Shipping Costs $15.00"
    else:
        print "FREE"

Tags: thefreeinputrawifcountryelsetotal
3条回答
  1. 您应该从原始输入中获取整数,而不是字符串。使用int()
  2. 比较值,如50,100,150。。。也应该是integer

下面是固定代码。

total = int(raw_input('What is the total amount for your online shopping?'))
country = raw_input('Shipping within the US or Canada?')

if country == "US":
    if total <= 50:
        print "Shipping Costs $6.00"
    elif total <= 100:
        print "Shipping Costs $9.00"   # improved indentation
    elif total <= 150:
        print "Shipping Costs $12.00"  # improved indentation
    else:
        print "FREE"

if country == "Canada":
    if total <= 50:
        print "Shipping Costs $8.00"
    elif total <= 100:
        print "Shipping Costs $12.00"
    elif total <= 150:
        print "Shipping Costs $15.00"
    else:
        print "FREE"

不能用数字比较字符串。而是先转换为int,然后比较。

例如:

if int(total) < 50

避免重复的变量也会有帮助。

当你比较字符串时,它是按字典顺序排列的,就像在电话簿中一样。例如:

"a" < "b":真
"bill" < "bob":真
"100" < "3":真

如果你想按照我们计算数字的顺序来比较数字,你需要使用int类型。

total = int(raw_input('What is the total amount for your online shopping?'))

然后将代码中的所有字符串文本(如"50")更改为整数文本(如50)。

相关问题 更多 >