Python无效语法:Print和Elif语句

杰克

我对Python和编程真的很陌生(准确地说是2天)。我闲着闲逛,试图提出一个比打印“ Hello world”还要复杂的过程。我想知道是否有人可以告诉我为什么它将我的print和elif语句标记为无效。我正在使用Python 2.7.10,谢谢!

A = raw_input("Do you live in the US or Canada?")
if A == " US" or "Canada":
        print "Welcome!"
else:
    print "We're sorry, but your country is currently not supported!"

B = int(raw_input("How much is your package?")
        if B >= 25
            print "Your shipping is $4.00"
    elif B >= 50
        print "Your shipping is $8.00"
else:
    print "Congrats, your shipping is free!"
克达克

您可能注意到的关于python的第一件事是一致的缩进不仅是一个好主意,而且是强制性的。经验丰富的程序员(无论是否编写Python)总会这样做,所以没什么大不了的。使用空格(通常为4)并避免使用制表符-更改您的编辑器以将制表符替换为4个空格。

由于四舍五入,对金额使用浮点数是个坏主意。最好使用较大的类型(如Decimal),或将金额存储为int单位为美分,然后在显示时插入小数点。为简单起见,我一直坚持使用float,但是要注意。

您的代码中存在许多逻辑错误,以及样式问题。编程风格不仅与外观漂亮有关,还在于您以后是否可以理解代码。

风格点:

不要对变量使用大写。按照惯例,大写保留给常量

使用有意义的变量名,而不是A和B

这是一个经过纠正的程序,带有注释。请阅读评论!

# This is a comment, it is ignored by python
# This is used later on by sys.exit()
import sys

# Logically the user would enter "Yes" or "No" to this quesion,
# not US or Canada!
ans = raw_input("Do you live in the US or Canada? ")    # Notice the space after ?

# Note how the condition has been expanded
if ans == "US" or ans == "Canada":
    print "Welcome!" 
else: 
    print "We're sorry, but your country is currently not supported!"

    # Now what?  Your program just carried on.  This will stop it
    sys.exit()

# I'm using a floating point number for simplicity
amount = float(raw_input("How much is your package? "))

# I changed this around, since 50 is also >= 25!
# However, this is strange.  Usually the more you spend the LESS the shipping!
# You were missing the : after the condition
if amount >= 50:
    print "Your shipping is $8.00"
    amount += 8           # This adds 8 to the amount
elif amount >= 25:
    print "Your shipping is $4.00"
    amount += 4           # This adds 4 to the amount
else:
    print "Congrats, your shipping is free!"

# print the amount showing 2 decimal places, rounding
print "Amount to pay: $%.2f" % (amount)

您还有很多事要做。也许可以应对用户输入的国家名称使用小写或大小写字母的情况-并问问自己问题对用户是否合乎逻辑。

以后,您可能需要一个有效的国家/地区列表,并in用来测试用户是否输入了有效的国家/地区。然后将其展开以使用词典,指示每个国家/地区的货币符号,运输金额和货币转换率。

享受Python!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章