我正在学习while循环和计数器。我知道如何在基本级别上使用它们,但我觉得在这种情况下我已经过度使用它们了,可能有一个更好的初学者答案仍然使用while循环和if/elif/else语句。
基本上,程序应该根据计数器从0开始打印句子1,然后在第4个句子之后打印合唱。。。然后它继续打印接下来的4个句子,然后在最后两次合唱。
这就是我现在所处的位置,但正如我所提到的,我觉得我过度使用while循环使其更简单,这有点像作弊。
ver1 = ['sentence1', 'sentence2', 'sentence3', 'sentence4']
ver2 = ['sentence5', 'sentence6', 'sentence7', 'sentence8']
chor1= ['chorus1', 'chorus2']
counter = 0
while counter == 0:
print(ver1[0])
counter += 1
while counter == 1:
print(ver1[1])
counter += 1
while counter == 2:
print(ver1[2])
counter += 1
while counter == 3:
print(ver1[3])
counter += 1
#this if statement was my decision just to see if I could use it properly, but I'd like to do the entire thing with while loops if possible....but using if/elif/else statements isn't forbidden.
if counter >= 5:
print(ver1[3])
else:
print(chor1[0])
我用if语句创建了它,但是老师问我是否可以尝试用while循环作为家庭作业。。。这是我写的if/elif/else原始语句。
^{pr2}$这只是程序的第一部分,因为我不想继续它,浪费我的时间,如果有一个更好的答案,而不仅仅是复制/粘贴,同时进行一些小编辑,以确定打印什么。
既然是家庭作业,我就不给你密码了。在这里使用while循环实际上是违反直觉的,但它是有效的。在
如果计数器为0/1/2/3,则为韵文。否则如果是4,9,10,那就是克洛斯。否则如果是5/6/7/8,那就是第2节。因此,您可以在while循环中有一个while循环,其中包含3个if语句,用于不同的场景。所以每次在while循环中,都要检查3个场景,然后增加计数器。在
如果你想使用4个while循环,abarner有一个很好的解决方案。不过,您可以在一个while循环中使用我所写的,但是您需要IF语句。在
谢谢大家的帮助。我终于让它以正确的输出正确地运行,尽管我觉得在第一个诗句之后,我还是把计数器重置为0,这有点欺骗人。但也许因为这只是我的第二堂课,这是可以接受的。我很确定我不必这样做,但我无法在不重置计数器的情况下,想出如何使用print(ver2[counter])。否则,我会得到一个“list index out of range”错误,因为ver2是一个不同的变量,ver2的列表项的索引从0开始。在
实际上,您过度使用了
while
循环,使其变得更加复杂。在让我们追踪一下你的代码:
当您第一次命中
while
,counter
将为0,因此它将运行一次。然后将counter递增到1,这样它就不会再运行了。在因此,这与关闭
^{pr2}$while
循环并编写以下内容的效果相同:下一个循环是相同的:
这将始终只运行一次,因此不需要循环。在
其他人也一样。在
这意味着当您到达循环的末尾时,
counter
将始终是4
。在因此,您可以将所有代码替换为:
或者,您也可以利用
while
来避免重复四次,如下所示:虽然实际上,用
for
语句来写可能更好:或者,更好的是:
其中任何一个都可以通过不同的方式扩展到处理不仅仅是verse-1的行:
……或者
……或者
……或者
……或者
……或者,如果你真的想让你的老师知道你的成绩远远领先于班上其他同学,或者是把你在网上发现的你不懂的代码交上来
相关问题 更多 >
编程相关推荐