这个Python代码有什么问题?

时间:2009-05-16 10:09:06

标签: python

我很新,所以只是学习,所以请放轻松!

start = int(input('How much did you start with?:' ))
if start < 0:
    print("That's impossible!  Try again.")
    print(start = int(input('How much did you start with:' )))
if start >= 0:
    print(inorout = raw_input('Cool!  Now have you put money in or taken it out?: '))
    if inorout == in:
        print(in = int(raw_input('Well done!  How much did you put in?:')))
        print(int(start + in))

这总是导致语法错误?我确定我做了一些明显的错误!

谢谢!

3 个答案:

答案 0 :(得分:7)

  • 您无法在Python中的表达式中分配变量,例如C:print(start = int(input('blah')))不正确。首先在单独的声明中完成作业。
  • 第一行不能缩进,但这可能只是复制和粘贴错误。
  • 单词in是保留字,因此您不能将其用于变量名称

答案 1 :(得分:3)

分配in语句是你的问题。 将分配移出打印语句

答案 2 :(得分:0)

  • 考虑使用包裹循环的函数提示输入。
  • 不要将input用于一般用户输入,而是使用raw_input代替
  • 将您的脚本执行包装在主函数中,以便它不会在导入时执行

def ask_positive_integer(prompt, warning="Enter a positive integer, please!"):
    while True:
        response = raw_input(prompt)
        try:
            response = int(response)
            if response < 0:
                print(warning)
            else:
                return response
        except ValueError:
            print(warning)

def ask_in_or_out(prompt, warning="In or out, please!"):
    '''
    returns True if 'in' False if 'out'
    '''
    while True:
        response = raw_input(prompt)
        if response.lower() in ('i', 'in'): return True
        if response.lower() in ('o', 'ou', 'out'): return False
        print warning

def main():
    start = ask_positive_integer('How much did you start with?: ')
    in_ = ask_in_or_out('Cool!  Now have you put money in or taken it out?: ')
    if in_:
        in_amount = ask_positive_integer('Well done!  How much did you put in?: ')
        print(start + in_amount)
    else:
        out_amount = ask_positive_integer('Well done!  How much did you take out?: ')
        print(start - out_amount)

if __name__ == '__main__':
    main()