python - 我在这个游戏中做错了什么?
问题描述
我正在尝试使用我的第一种脚本语言:python。我目前正在制作一个小游戏,您可以在其中猜测 1-100 的预定数字。它还会告诉您正确答案是更大还是更小。目前我的代码总是返回正确的数字较小,而事实并非如此。
编辑:非常感谢你帮助我!
import random
print("this is a game made by Sven")
print("you're supposed to guess the right number. it is between 0 & 101.")
print("lucky for you, you're getting hints.")
print("succes!")
rightnumber = (random.randint(1, 100))
print(rightnumber)
gok = int(input("type your guess here and press enter"))
def compareguess():
if gok > rightnumber:
print("wrong! the right number is smaller :)")
elif gok == rightnumber:
print("WOW! you guessed right!")
else:
print("wrong! the right number is bigger.")
compareguess()
def guessAgain():
int(input("try again. type your guess and press enter."))
compareguess()
if rightnumber == gok:
print("that was it! you won!")
else: guessAgain()
if rightnumber == gok:
print("that was it! you won!")
else: guessAgain()
解决方案
您可以gok
作为参数传递以避免全局变量。
问题是:
当您再次输入时:int(input("try again. type your guess and press enter."))
,您不会将值分配给任何东西。所以gok
保持不变,总是更大或更小
import random
print("this is a game made by Sven")
print("you're supposed to guess the right number. it is between 0 & 101.")
print("lucky for you, you're getting hints.")
print("succes!")
rightnumber = (random.randint(1, 100))
gok = int(input("type your guess here and press enter"))
def compareguess(gok):
if gok > rightnumber:
print("wrong! the right number is smaller :)")
elif gok == rightnumber:
print("WOW! you guessed right!")
else:
print("wrong! the right number is bigger.")
compareguess(gok)
def guessAgain():
gok=int(input("try again. type your guess and press enter."))
compareguess(gok)
if rightnumber == gok:
print("that was it! you won!")
else: guessAgain()
if rightnumber == gok:
print("that was it! you won!")
else: guessAgain()
另外,不要使用递归。相反,使用while
循环。没有递归的缩短代码:
import random
print("this is a game made by Sven")
print("you're supposed to guess the right number. it is between 0 & 101.")
print("lucky for you, you're getting hints.")
print("succes!")
rightnumber = (random.randint(1, 100))
while True:
gok = int(input("type your guess here and press enter"))
if gok > rightnumber:
print("wrong! the right number is smaller :)")
elif gok == rightnumber:
print("WOW! you guessed right!")
break
else:
print("wrong! the right number is bigger.")
推荐阅读
- android - 按搜索关键字对 ArrayList 进行排序
- java - 我是否正确处理休眠会话?
- html - 如何使用 CSS 使这个网页空间优化?
- visual-studio-code - 在 Visual Studio 代码中提交后自动关闭 git 面板
- excel - 从VBA中的范围中删除特殊字符
- javascript - 如何使用 Vuetify 规则创建自定义验证来检查现有项目
- node.js - 运行节点命令 x 次
- ffmpeg - FFMPEG 将缩略图附加到视频的第一帧
- powershell - 如何在包含多个变量的特定行中查找和替换单词
- python - 尝试为 PYPI 打包 Python 包时出现无效要求错误