python替代goto,替代Goto,Python中的Label?

这篇博客探讨了如何在Python程序中实现一个猜数字游戏,重点在于避免使用Goto语句。作者提供了一个解决方案,利用while循环和条件判断来实现游戏逻辑,包括错误输入处理和提示用户猜测更高或更低的数字。通过这种方式,程序的流程更加清晰,符合良好的编程实践。
摘要由CSDN通过智能技术生成

I know I can't use Goto and I know Goto is not the answer. I've read similar questions, but I just can't figure out a way to solve my problem.

So, I'm writing a program, in which you have to guess a number. This is an extract of the part I have problems:

x = random.randint(0,100)

#I want to put a label here

y = int(raw_input("Guess the number between 1 and 100: "))

if isinstance( y, int ):

while y != x:

if y > x:

y = int(raw_input("Wrong! Try a LOWER number: "))

else:

y = int(raw_input("Wrong! Try a HIGHER number "))

else:

print "Try using a integer number"

#And Here I want to put a kind of "goto label"`

What would you do?

解决方案

There are lots of ways to do this, but generally you'll want to use loops, and you may want to explore break and continue. Here's one possible solution:

import random

x = random.randint(1, 100)

prompt = "Guess the number between 1 and 100: "

while True:

try:

y = int(raw_input(prompt))

except ValueError:

print "Please enter an integer."

continue

if y > x:

prompt = "Wrong! Try a LOWER number: "

elif y < x:

prompt = "Wrong! Try a HIGHER number: "

else:

print "Correct!"

break

continue jumps to the next iteration of the loop, and break terminates the loop altogether.

(Also note that I wrapped int(raw_input(...)) in a try/except to handle the case where the user didn't enter an integer. In your code, not entering an integer would just result in an exception. I changed the 0 to a 1 in the randint call too, since based on the text you're printing, you intended to pick between 1 and 100, not 0 and 100.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值