【问题标题】:Syntax Error, Cant figure out why(Line 17)语法错误,无法弄清楚原因(第 17 行)
【发布时间】:2015-10-11 21:48:41
【问题描述】:

b.创建一个模拟简单储蓄账户模拟的程序。首先向用户询问初始余额(必须至少为 100 美元且小于 400,000 美元)。只要用户想继续允许他们进行存款和取款 - 不要透支!用户完成后,输出最终余额。 (建议......使用类似的菜单: 1. 存款 2. 提款 3.退出)

balance = int(input("Enter initial balance: $ "))

while balance <= 100 or balance >= 400000:
    print ("Invalid Amount!")
    balance = int(input("Ener valid amount: $ "))

deposit = 0
withdraw = 0

if balance >= 100 and balance <= 400000:
    while ans != 3: 
        print("""
    1. Deposit
    2. Withdrawal
    3. Quit
    """)
ans = int(input("What would you like to do? Please enter the appropriate     number. "))
if ans == 1:
    deposit = int(input("\n How much would you like to deposit: $")
    balance = balance + deposit
elif ans == 2:
    withdraw = int(input("\n How much would you like to withdraw: $")
    if (balance - withdraw) < 0
        withdraw = int(input("\n Tried to withdraw too much! How much would  you like to withdraw: $")
        balance = balance - withdraw
elif ans == 3:
print("Your final balance is %d" %balance.)

【问题讨论】:

  • if (balance - withdraw) &lt; 0 缺少 :。你最后的print 语句没有缩进,而且你在balance 之后有一个尾随.
  • 余额 = 余额 + 存款时仍然出现错误
  • 前一行缺少尾随 )。始终查看上面检测到错误的行。
  • 第 19 行还缺少)
  • 你在定义之前不使用ans吗?这将导致 NameError。

标签: python loops iteration


【解决方案1】:

你在上一行缺少),你想要:

if ans == 1:
deposit = int(input("\n How much would you like to deposit: $"))

还有一个:

withdraw = int(input("\n How much would you like to withdraw: $"))

然后是尾随::

if (balance - withdraw) < 0:

还有一个) 进一步:

    if (balance - withdraw) < 0
        withdraw = int(input("\n Tried to withdraw too much! How much would  you like to withdraw: $"))

然后在你的% 后面加一个空格(去掉.):

print("Your final balance is %d" % balance)

【讨论】:

  • 感谢 Paul,我的语法正确,但现在出现 NameError,我应该如何定义 ans?
  • 您需要在while ans != 3: 之前定义ans,类似于输入ans 的行复制
  • 如果我在 while ans != 3 之前分配它:它会给我错误,如果我在第 6 行之后立即分配它,它会在无限循环中运行。对不起,我还是新手
  • @HissanMunir 基本上你的代码中有很多错误。您还有一些工作要做……但距离您的不远。
  • 是的,我也这么认为。我一直在努力。请指出我正确的方向。
【解决方案2】:

您在第 16 行缺少一个 ')'。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多