简体   繁体   English

将随机数猜谜游戏制作为一个小型 Python 项目,我想知道为什么这不起作用

[英]Making random number guessing game as a small python project and I'm wondering why this isn't working

This is the code I've written so far in IDLE.这是我目前在 IDLE 中编写的代码。 When I run it, the while loop doesn't break when it should.当我运行它时,while 循环不会在它应该中断的时候中断。 Why could this be?为什么会这样? What's wrong with my code?我的代码有什么问题? I'm very new to Python and have used C++ for years.我对 Python 非常陌生,多年来一直使用 C++。

import random

random.seed()
randomNumber=random.randint(0,20)

print("Try to guess the number between 0 and 20\n\n\n")

while 1==1:
    guess = input("What is your guess?\n")
    if guess==randomNumber:
        break

print("Guess correct")

Cast input to int将输入转换为 int

guess = int(input("What is your guess?\\n"))猜测 = int(input("你的猜测是什么?\\n"))

Your input is a string you need to convert it to an integer, so the the line您的输入是一个字符串,您需要将其转换为整数,因此该行

guess = input("What is your guess?\n")

should be应该

guess = int(input("What is your guess?\n"))

I have added the comment for the code: I think C++ has made you over-think some things.我已经为代码添加了注释:我认为 C++ 使您过度思考了一些事情。 Python does a lot of the work for you that you have to do yourself in lower level languages. Python 为您完成了许多工作,而这些工作您必须用低级语言自己完成。

import random

# random.seed() # you don't need a seed
randomNumber=random.randint(0,20)


print("Try to guess the number between 0 and 20")
# you must specify the datatype for the input
guess = int(input("What is your guess?")) # you don't need a line break

while guess != randomNumber: # no need for 1=1,
    guess = int(input("What is your guess?")) # data-type again
    if guess == randomNumber:
        print("Guess correct")
        break # exit condition

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

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