Python Problems Guess the Number Game(猜数字游戏)

bq3bfh9z  于 2023-04-04  发布在  Python
关注(0)|答案(3)|浏览(93)

此问题在此处已有答案

How can I read inputs as numbers?(10个答案)
六年前关闭了。
我做了一个猜数的python游戏的终端,但游戏不承认当玩家赢了,我不明白为什么。这里是我的代码:

from random import randint

import sys

def function():

    while (1 == 1):

        a = raw_input('Want to Play?')

        if (a == 'y'):

            r = randint(1, 100)

            print('Guess the Number:')
            print('The number is between 1 and 100')

            b = raw_input()

            if (b == r):

                print(r, 'You Won')

            elif (b != r):

                print(r, 'You Lose')    

        elif (a == 'n'):

            sys.exit()  

        else:

            print('You Did Not Answered the Question')          

function()
e1xvtsh3

e1xvtsh31#

FujiApple's answer中所述:默认情况下输入的类型是字符串。
因此:

>>>b = raw_input("Enter a number : ")
Enter a number : 5
>>>print b
'5'
>>>type(b)
<type 'str'>

您需要将字符串转换为整数,以使其等于randint数:

if int(b) == r:
g9icjywg

g9icjywg2#

raw_input()返回一个字符串,您正在与randint返回的int进行比较

nnt7mjpx

nnt7mjpx3#

这是我为您的问题编写的正确代码版本。

import random
while (1 == 1):
   a = raw_input('Want to Play?')
   if (a == 'y'):
     r = random.randint(1, 100)
     print('Guess the Number:')
     print('The number is between 1 and 100')
     b = int(raw_input()) 
     if (b == r):
        print(r, 'You Won')
     elif (b != r):
        print(r, 'You Lose')    
  elif (a == 'n'):
    break   
else:
    print('You Did Not Answered the Question')

希望这个有用。

相关问题