繁体   English   中英

为什么这段代码不起作用(我是编程新手,python)

[英]Why is this code not working (i'm new to programming, python)

import random

guesses = 3
number = random.randint(1, 10)
print (number) #<- To test what number im supposed to write.

while guesses > 0: # When you have more than 0 guesses -> guess another number
    guess = input("Guess: ")

    if guess == number : # If guess is equal to number -> end game
        print ('Your guess is right!.')
        break


    if guess != number : # If not number -> -1 guess
        print ("Nope!")
        guesses -= 1

    if guesses == 0: #If all 3 guesses are made -> end game
        print("That was it! Sorry.")
        print(number,"was the right answer!")

我究竟做错了什么? 我想不通,希望你能帮忙^ - ^

如果你能教我如何改进我的编程,那么请随时写信给我如何做! 我开放学习新东西btw抱歉我的英语不好:3(编辑:当我猜对了正确的号码,它仍然说“不!”而且我不得不猜猜另一个号码。)

这看起来像Python3。 如果是这样,请改用guess = int(input("Guess: "))

在Python3中, input()返回一个字符串,你将该字符串与一个永远不会起作用的整数进行比较。 因此,将input()的返回值转换为整数,以确保您将苹果与苹果进行比较。

你需要在输入前放置int,所以:

guess = int(input("Guess: "))

这会将猜测变为整数,因此代码会识别它。

input()命令返回一个字符串,字符串不等于数字( "3" == 3计算结果为false )。 您可以使用int(...)函数将字符串(或浮点数)转换为整数。

我假设您正在使用Python 3.x,因为print是一个函数。 如果您使用的是Python 2.x,则应该使用raw_input() ,因为input()会使解释器将输入的内容视为Python代码并执行它(就像eval(...)函数那样)。

在99.999%的情况下,您希望执行用户输入。 ;-)

您的程序需要的另一个重要的事情是提示用户,以便他们知道他们将对您的程序做些什么。 我已相应地添加了提示。

import random

print ("Hello. We are going to be playing a guessing game where you guess a random number from 1-10. You get three guesses.")
number = random.randint(1, 10)
# print (number) #<- To test what number im supposed to write.
guesses = 3
while guesses > 0: # When you have more than 0 guesses -> guess another number
    guess = input("Enter your guess: ")

    if guess == number : # If guess is equal to number -> end game
        print ('Your guess is right!.')
        break


    if guess != number : # If not number -> -1 guess
        print ("Nope!")
        guesses -= 1

    if guesses == 0: #If all 3 guesses are made -> end game
        print("That was it! Sorry.")
        print(number, "was the right answer!")

暂无
暂无

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

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