【问题标题】:Python while loop, I'm stuck help! :CPython while循环,我被困住了! :C
【发布时间】:2016-09-21 00:09:28
【问题描述】:

我是编程新手(3 天前刚开始),我需要有关此代码的帮助,我真的需要。

我不知道如何执行while 循环。 (在#### 行下方)。你能帮帮我吗?

我正在使用python 3.4.2 版

import random

right = 0
wrong = 0

for i in range(10):

        x = random.randint (2,29)
        y = random.randint (3,29)
        z = (x*y)
        qq = input("What's " + str(x) + " times " + str(y) + "? ")


        if   str(z) == str(qq):
             right = right +1
             print ("Correct!\n")

        else:
            wrong = wrong + 1
            print ("Wrong the correct answer is ",str(z),"\n")


print ("You got", right, "out of 10 questions")

if right==10:
        print ("Well Done! Perfect score!")

elif right>=5:
        print ("Well done! try getting perfect score next time")

else:
        print ("Noob")
#################################################
restart = y
while True:
        yess = input ("Would you like to try again? y/n?")
        if restart == yess:
                print (i)
        else:
                break

【问题讨论】:

  • 您只需将整个代码放入 while 循环中,这样它就会真正重复

标签: python python-3.x while-loop


【解决方案1】:

以下是该问题的快速解决方法:

import random

while True:    
    right = 0
    wrong = 0

    for i in range(10):

            x = random.randint (2,29)
            y = random.randint (3,29)
            z = (x*y)
            qq = input("What's " + str(x) + " times " + str(y) + "? ")


            if   str(z) == str(qq):
                 right = right +1
                 print ("Correct!\n")

            else:
                wrong = wrong + 1
                print ("Wrong the correct answer is ",str(z),"\n")


    print ("You got", right, "out of 10 questions")

    if right==10:
            print ("Well Done! Perfect score!")

    elif right>=5:
            print ("Well done! try getting perfect score next time")

    else:
            print ("Noob")
    #################################################
    restart = "y"
    yess = input ("Would you like to try again? y/n?")
    if restart != yess:
        break;

基本上,您只需将整个代码放入 while 循环中,这样它就会真正重复。

另外,老实说,当我将"y" 放在引号中以使其成为字符串时,我真的希望我没有搞砸。一个多小时没接触 Python,所以对语法有些模糊。

【讨论】:

  • 天哪,你是个传奇,我明白了:P 非常感谢!.. 所以如果我希望我的代码继续重复,我只需将所有内容放入 while 循环 ryt ?
  • 差不多,但始终确保有一种方法可以退出它,这样它就不会是一个无法终止它的无限循环(除非这确实是你需要的)。你写下的就是发生的事情,一切都是逐行解释的(尤其是在 Python 中),毕竟 :)
猜你喜欢
  • 2017-09-26
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
  • 2021-08-26
  • 2020-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多