我做了什么来冒犯Python解释器?

Amy*_*Amy -1 python syntax-error

当我运行以下代码时:

# This program calculates gross pay.
def main():

    # Get the number of hours worked.
    hours = int(input('How many hours did you work? '))

    # Get the hourly pay rate.
    pay_rate = float(input('Enter your hourly pay rate: '))

    # Calculate the gross pay.
    gross_pay = hours * pay_rate

    # Display the gross pay.
    print('Gross pay: $', format(gross_pay, ',.2f), sep=''')

# Call the main function.
main()
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

SyntaxError: invalid syntax. 
Run Code Online (Sandbox Code Playgroud)

最后一个主要部分以红色突出显示.出了什么问题?

Joe*_*ett 5

python中有两种类型的字符串文字:

  • "a string"'a string'- 表示单行字符串.

  • """a string"""'''a string'''- 表示多行字符串.

你所做的是(1)无法关闭字符串,.2f,以及(2)无意中打开了(三引号)多行字符串文字:

print('Gross pay: $', format(gross_pay, ',.2f), sep=''')
                  missing a close quote here ^      ^^^ Opened a string literal
Run Code Online (Sandbox Code Playgroud)

解释器假定它之后的所有内容都是该字符串文字的一部分.当它找不到右括号时(因为你从未关闭过字符串文字),那就抱怨了.

有两种方法可以解决这个问题:

  1. 逃避中间报价:sep='\'').这将阻止python将其解释为多行文字.
  2. 使用双引号: sep="'")