从TeamTreeHouse.com示例创建我自己的场景引发错误。

2024-04-18 02:02:48 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我试图从视频中创建自己的示例,以便更好地理解示例和课程。在构建自己的过程中,我遇到了两个错误。第一个是:

    status = input('Are you single or married?: '.lower())
      File "<string>", line 1, in <module>
    NameError: name 'single' is not defined

第二个是:

    except ValueError:
         ^
    SyntaxError: invalid syntax

我的代码是:

print ('When entering numbers, do not use commas or periods''\n')
salary = int(input('What is your annual salary before taxes?'))

status = input('Are you single or married?: '.lower())
if status == ('single'):
    status = (status)
elif status == 'married':
    status = ('married')
except ValueError:
    print('Sorry I did not understand your input')


else:
    print('You answered that you are {} making {} a year').format(status, salary)

我看了一遍视频,重新阅读了我的笔记,但我认为,因为我试图建立自己的例子,我错过了一些视频中没有的简单内容


Tags: oryou示例input视频isstatusnot
1条回答
网友
1楼 · 发布于 2024-04-18 02:02:48

您的第一个错误是因为您使用的是python 2。您应该使用raw_input()而不是input()input()仅适用于数字输入

关于你的SyntaxError,这是因为你做了一个except之前没有try语句,我认为你在寻找else语句

以下是您的代码的修改版本:

print ('When entering numbers, do not use commas or periods''\n')
salary = input('What is your annual salary before taxes?')

status = raw_input('Are you single or married?: ').lower() 
# put .lower() outside if you want the input to be lowercase instead of the question with lowercase letters.

if status != 'single' and status != 'married':
    print('Sorry I did not understand your input')
else:
    print('You answered that you are {} making {} a year').format(status, salary)

(我还没有测试过,但我希望它能工作)

相关问题 更多 >