【问题标题】:Why showing error in while loops and if statement为什么在while循环和if语句中显示错误
【发布时间】:2021-04-01 21:24:28
【问题描述】:

今天我在python3中写了一个while循环代码,代码如下:

#Simulate supermarket billing process
while True:
    total=0
    repeat="y"
    Noc=input("Enter customer's name here:")
    while repeat=="y":
        print("1. Keep adding.")
        print("2. Print the bill amount.")
        choice=int(input("Enter your choice(1 or 2):")
        if choice==1 or choice==2:
            if choice==1:
               itemqty=int(input("Etner item quantity here:"))
               itemamt=float(input("Enter item price Here:"))
               total=total+itemqty*itemamt
            elif choice==2:
                 print("The total amount is:",total)
                 repeat=input("Do you want to enter more items?(Y/y/N/n)")
        else:
            print("Incorrect choice...Enter again")
#print a bill
print("Name:"," ",Noc,)
print("Total Amount:"," ", total)
print("-----**Thanks for Shopping**-----")
mp=input("Want to go to next person?(Y/y/N/n)")
if mp="N" or mp="n":
   break

这个错误来了

File "/home/agupta/Documents/anant/codingPlayground/learnPython/Chapter 4/hi.py", line 10
    if choice==1 or choice==2:
                             ^
Syntax Error: invalid syntax

请谁能告诉错误是什么?

【问题讨论】:

  • 对于int() 函数,错误上方的行中缺少右括号。这在调试中经常发生——编译器直到在错误行发生之后才意识到有错误。
  • 顺便说一句,我认为您永远不会打印名称和总金额行,因为最外面的while 循环...您需要一个break 在那里.

标签: python-3.x loops if-statement while-loop


【解决方案1】:

正如@beroe 建议的那样:

choice=int(input("Enter your choice(1 or 2):"))

再提示:解决这个问题后,你也可以这样开始改进这段代码

choice=int(input("Enter your choice(1 or 2):")

if choice==1:
   itemqty=int(input("Etner item quantity here:"))
   itemamt=float(input("Enter item price Here:"))
   total=total+itemqty*itemamt
elif choice==2:
    print("The total amount is:",total)
    repeat=input("Do you want to enter more items?(Y/y/N/n)")
else:
    print("Incorrect choice...Enter again")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 2016-01-12
    • 2012-06-18
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多