首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用while循环打印输出的Python作业

使用while循环打印输出的Python作业
EN

Stack Overflow用户
提问于 2018-07-13 05:47:20
回答 2查看 460关注 0票数 3

我正在尝试学习“while”循环和计数器。我知道如何在基本级别上使用它们,但我觉得在这种情况下我已经不再使用它们了,而且可能会有一个更好的初学者答案,它仍然使用while循环和if/elif/else语句。

基本上,程序应该根据从0开始的计数器来打印每一句话,并打印sentence1,然后在第四句之后打印合唱...然后,它继续打印接下来的4个句子,然后在最后打印两次合唱。

这就是我现在所处的位置,但就像我提到的,我觉得我已经不再使用while循环了,这让它变得更简单,感觉有点像作弊。

代码语言:javascript
复制
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原始语句。

代码语言:javascript
复制
verse1 = "I came home and my dog was gone"
verse2 = "She took my dog and my truck"
verse3 = "oh no she didn't"
chorus = "ohh how times have changed"

truck = 'gone'
dog = 'gone'

if dog == "gone":
    print (verse1)
    print (chorus)
else:
    print(verse3)

if truck == 'gone':
    print (verse2)
    print (chorus)
else:
    print (verse3)

这只是程序的第一部分,因为我不想继续它,浪费我的时间,如果有一个更好的答案,而不是只复制/粘贴while循环,通过几个小编辑来确定打印什么。

EN

回答 2

Stack Overflow用户

发布于 2018-07-13 07:12:27

既然是作业,我就不给你代码了。在这里使用while循环实际上是违反直觉的,但它是有效的。

如果计数器是0/1/2/3,那么它是反的。否则,如果它是4,9,10,它就是chrous。否则,如果是5/6/7/8,就是verse2。因此,您可以在while循环中使用3个if语句,用于不同的场景。因此,每次在这个while循环中,您都会检查这3个场景,然后增加计数器。

如果你想使用4个while循环,abarnert有一个很好的解决方案。但是,您可以在一个while循环中使用我所写的内容,但您需要使用IF语句。

票数 1
EN

Stack Overflow用户

发布于 2018-07-13 10:52:56

谢谢大家的帮助。我最终让它以正确的输出正常运行,尽管我觉得我在第一段之后将计数器重置为0,这仍然有点作弊。但也许因为这只是我的第二节课,所以它是可以接受的。我非常确定我没有必要这样做,但是我不知道如何在不重置计数器的情况下使用print(ver2counter)。否则我会得到一个'list index out of range‘的错误,因为ver2是一个不同的变量,并且ver2的列表条目的索引从0开始。

代码语言:javascript
复制
ver1 = ['sentence1', 'sentence2', 'sentence3', 'sentence4']
ver2 = ['sentence5', 'sentence6', 'sentence7', 'sentence8']
chor1= ['chorus1', 'chorus2']

counter = 0

while counter < 4:
    print(ver1[counter])
    counter += 1

if counter == 4:
    print(chor1[0])
    counter += 1

counter = 0

while counter < 4:
    print(ver2[counter])
    counter += 1

if counter == 4:
    print(*chor1, sep = "\n")
#I googled around a bit to find a way to print the items in chor1 with a 
#line return so it lined up with the rest instead of printing side by 
#side
#I do see now where @abarnert showed the sep = "\n" to return the line
#though I missed it in all the code options listed. 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51314944

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档