Python中WHILE和IF的组合

Python中WHILE和IF的组合,python,if-statement,while-loop,Python,If Statement,While Loop,我是Python的新手,所以我正在尝试编写一些基本代码。 下面您可以看到一个简单的代码,但它给出了后续错误: 文件“”,第9行 打印('不是您的号码') ^ 缩进错误:应为缩进块 c = 0 while c < 5: print(f'The current number is: {c}') c = c + 1 if c == 4: print('Not your number.') else: print ('You have

我是Python的新手,所以我正在尝试编写一些基本代码。 下面您可以看到一个简单的代码,但它给出了后续错误: 文件“”,第9行 打印('不是您的号码') ^ 缩进错误:应为缩进块

c = 0

while c < 5:
    
    print(f'The current number is: {c}')
    c = c + 1
    
    if c == 4:
    print('Not your number.')

else:
    print ('You have reached your limit.')
c=0
c<5时:
打印(f'当前编号为:{c}')
c=c+1
如果c==4:
打印('不是您的号码')
其他:
打印('您已达到限制')

你能帮我找出错误吗?提前谢谢你

正如您在底部else子句中缩进一样,您必须在while循环中缩进if子句。下面的方法应该有效

c = 0

while c < 5:
    
    print(f'The current number is: {c}')
    c = c + 1
    
    if c == 4:
        print('Not your number.')

else:
    print ('You have reached your limit.')
c=0
c<5时:
打印(f'当前编号为:{c}')
c=c+1
如果c==4:
打印('不是您的号码')
其他:
打印('您已达到限制')

python中的缩进很重要。当您有一条语句,该语句需要一个代码块在它之后执行,就像if语句或while循环一样,如果您没有提供正确缩进的块,您将得到一个语法错误

c = 0

while c < 5:
    
    print(f'The current number is: {c}')
    c = c + 1
    
    if c == 4:
        print('Not your number.') # this statement has to be indented because of the if statement
else:
    print ('You have reached your limit.')
c=0
c<5时:
打印(f'当前编号为:{c}')
c=c+1
如果c==4:
打印(“不是您的号码”)#由于if语句,此语句必须缩进
其他:
打印('您已达到限制')

您已经研究过“if”语句的缩进要求了吗?请查看关于控制流的官方Python教程。您的
if
语句与教程中的语句类似吗?它有什么不同?为什么压痕应该是这样的?@quamrana我纠正了它,谢谢!我没有说任何事情是正确的或不正确的。“你没有给出一个理由,为什么它应该是这样或那样的”。@quamrana是的,我用一个解释更新了我的答案。