【问题标题】:Am I structuring my IF statement incorrectly in python?我是否在 python 中错误地构造了我的 IF 语句?
【发布时间】:2014-10-18 10:34:25
【问题描述】:

我正在做一些计算机科学作业,并且正在尝试学习一些基本的 Python。我正在尝试执行 IF 语句,但我不断收到语法错误(顺便说一下,python 版本 3.3.3)。有人可以告诉我我做错了什么吗?请注意,虽然我的错误很可能出现在 IF 语句中,但也可能出现在其他地方。谢谢。

print ("Hello. What is your name?")
print("")
name = input()
print("")
print("Hello ", name, ". What lesson do you have next?")
print("")
lesson = input()
print("")
print("I hate ", lesson, ". You're rubbish.")
wait = input()
print("...")
wait = input()
print("...")
wait = input()
print("...")
wait = input()
print("")
print("Do you like me? If you love me, type 1. If you hate me, type 2. If you're inbetween, type 3.")
print("")
emotion = input()
print("")
if emotion == 1:
    print ("Awwwwwww.")
    print ("")
    else:
        if emotion == 2:
        print ("Yeah well I don't like you either.")
        print ("")
        else:
            if emotion == 3:
            print ("Yeah OK fair enough")
            print ("")
            else:
                print("I said type 1, 2 or 3. I'm going now.")
                print("")
print("I'm going now. Goodbye friend.")
print("")
wait = input()
quit()

【问题讨论】:

  • 发布您收到的实际错误消息
  • 我得到的只是“语法错误”。它不会告诉我什么。
  • 你是如何运行它的?你至少应该得到一个回溯。

标签: python if-statement syntax


【解决方案1】:

else 必须始终缩进到与对应的if 相同的级别:

if emotion == 1:
    print ("Awwwwwww.")
    print ("")
else:
    if emotion == 2:
        # etc.

接下来,你可以在这里使用elif

if emotion == 1:
    print ("Awwwwwww.")
    print ("")
elif emotion == 2:
    # etc.

接下来,我根本不会在这里使用if...elif...;你会使用列表或映射来代替:

emotions = ['', 'Awwwwwww.', "Yeah well I don't like you either.", ...]
print(emotions[emotion])

【讨论】:

  • 感谢您的帮助。我已经添加了您的 elif 建议(因为我仍然是初学者并且不理解另一个建议)但是现在我收到 2 旁边的冒号的“无效语法”错误 == 2:
  • @user2627595:那么你在某个地方还有另一个错误。例如,您实际上在elif 下有一个套件(一个缩进的语句块)吗?
【解决方案2】:

Python 对缩进敏感。 else的缩进必须和if的缩进一致:

if emotion == 1: # 1
    <code>
    if <condition>: # 2
         <code>
    elif <condition>: # 2
         <code>
    else: # 2
         <code>
else: # 1
    <code>

#1 else 属于#1 if。 #2 elifelse 属于 #2 if

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 2022-12-08
    • 1970-01-01
    相关资源
    最近更新 更多