简体   繁体   English

初学者 python 循环回到我的简单数字猜谜游戏的开始

[英]beginner python on looping back to the start of my simple number guessing game

This is my code so far (in PyCharm), I am writing a very simple number guessing game that has integers from 1-9.到目前为止,这是我的代码(在 PyCharm 中),我正在编写一个非常简单的数字猜谜游戏,其中包含 1-9 的整数。 I am still trying to master thought & flow as well as loops, and I hit a roadblock:我仍在努力掌握思维和流程以及循环,但我遇到了障碍:

import random


Player_Name = input("What is your name?\n")
print(f"Hello {Player_Name}!\n")
random_num = random.randint(1, 10)
guess = int(input("What is the number you want to pick? Guess one, 1-9\n"))


def number_game():
    if guess == random_num:
        print(f"You guessed right, the number is confirmed to be {random_num}.")
    else:
        print(f"You guessed the wrong number. Try again.\n")


number_game()

I called the function and ran the code... everything appears to be working except I really can't figure out how to keep the game going in a loop until the player gets the right number out of 1-9...and end it when I need to.我打电话给 function 并运行了代码……一切似乎都正常,除了我真的不知道如何让游戏循环进行,直到玩家从 1-9 中得到正确的数字……然后结束它在我需要的时候。 I tried searching all my resources and am quite stuck on this beginner practice coding.我尝试搜索我所有的资源,并且非常坚持这个初学者练习编码。 Any help is appreciated.任何帮助表示赞赏。

What I wrote and tried is above... googling and stackoverflow just confused me more.我写的和试过的都在上面……谷歌搜索和计算器让我更加困惑。

Honestly, there are many ways to do what you want.老实说,有很多方法可以做你想做的事。 But using your code as base, this is one possible solution.但是使用您的代码作为基础,这是一种可能的解决方案。

import random


Player_Name = input("What is your name?\n")
print(f"Hello {Player_Name}!\n")
random_num = random.randint(1, 10)



def number_game():
    guess = int(input("What is the number you want to pick? Guess one, 1-9\n"))
    if guess == random_num:
        print(f"You guessed right, the number is confirmed to be {random_num}.")
        return True
    else:
        print(f"You guessed the wrong number. Try again.\n")
        return False


while True:
    guessed_right = number_game()

    if guessed_right:
        quit()
    else:
        number_game()
while True:
    number_game()

Replace the last line of your script with this!用这个替换脚本的最后一行!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM