在python3中循环时如何转到下一行? [英] How can i go to next line while in a loop in python3?

查看:531
本文介绍了在python3中循环时如何转到下一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个小的游戏,您可以猜出这个数字.但是我有一个问题.我需要能够重新开始循环,而不是重复错误/正确答案"的文字.

这是我所拥有的:

I have made a little "game where you guess the number. However I have a problem. I need to be able to restart the loop instead of having the "wrong/right answer" text be repeated.

Here is what I have:

number = 34
guess = int(input("guess the number"))
while guess != 34:
    if guess > number:
        print("Too high")
    else:
        print("too low")
if guess == number:
    print("You got it.")

推荐答案

您只需输入一次即可.如果循环不是正确的数字,则需要在循环结束时更新guess(从用户处获取新的输入).

假设您与一个朋友一起玩游戏,而您是一个计算机",而您的朋友是必须猜测您正在考虑的数字的用户.怎么样了?

1)你的朋友猜出了一个
2)您将这个猜测评估为低/高或正确
3)重复1)和2),直到猜测正确为止

因此,您现在应该能够意识到需要进行猜测并在一个循环中对其进行评估.
You only take input once. You''ll need to update guess (get new input from the user) at the end of your loop if it''s not the correct number.

Pretend you''re playing the game with a friend you''re the "computer" and your friend is the user who has to guess the number you''re thinking of. How will that go?

1) Your freind makes a guess
2) You evaluate that guess, to low/high or correct
3) You repeat 1) and 2) untill the guess is correct

So you''ll now you should be able to realize that you need to take a guess and evaluate it in a loop.


首先,您看不到算法本身是不正确的?

当猜测"不超过34时,代码将带入"if"的"else"分支,因此,如果恰好是34,则将打印太低".这是不正确的,因为在下一行中,您将打印"You got it".更不用说您在函数中使用了34个硬编码的立即数.游戏的目标是猜测34吗? :-)始终应避免使用硬编码的常量,但广泛使用的常量(例如0或1)除外.

对于您的问题,您显然不知道循环是什么,因此很难猜测下一行"的含义.没有什么需要重复一段代码了.只需阅读手册即可: http://docs.python.org/tutorial/controlflow.html [ ^ ].

—SA
First of all, can''t you see that the algorithm itself is incorrect?

The code will bring the "else" branch of your "if" when the "guess" is not more than 34, so if it is exactly 34, you will print "too low". This is not correct, as in next line you will print "You got it". Not mentioning that you''re using immediate constant of 34 hard-coded in your function. Is the goal of the game to guess 34? :-) Hard-coded constants should always be avoided, except for widely used constants like 0 or 1.

As to your question, you apparently don''t know what the loop is, so it''s hard to guess what you mean by "next line". There is nothing which requires a fragment of code to be repeated. Just read the manual: http://docs.python.org/tutorial/controlflow.html[^].

—SA


这篇关于在python3中循环时如何转到下一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆