Python随机数猜数字游戏问题:无论猜测对错均提示错误
问题分析与修复方案
你的代码存在两个核心问题,导致无论猜测正确与否都会提示错误:
没有正确获取用户输入
你写的guess = input是把input函数本身赋值给了guess变量,而非获取用户输入内容。后续的input("enter your guess here! ")仅触发了输入操作,但没有将用户输入的值存入guess,导致guess始终是函数对象,和整数类型的number永远不相等。输入类型不匹配
input()函数返回的是字符串类型,而number是random.randint生成的整数类型,直接用!=比较的话,字符串和整数永远不会相等(比如输入的"1"和数字1是不同类型的两个值)。
修改后的代码
import random amount_right = 0 number = random.randint(1, 10) # 你提示的是1-10,这里把范围改成1-10更符合提示 print(number) print( "welcome to this number guessing game!! I am going to think of a number from 1-10 and you have to guess it! Good luck!" ) # 正确获取输入并转换为整数 guess = int(input("enter your guess here! ")) if guess != number: print("Not quite!") amount_right -= 1 print("you have a score of ", amount_right) else: print("good Job!!") amount_right += 1 print("you have a score of ", amount_right, "!")
补充说明:你原来的random.randint(1,2)生成的是1或2,但提示文本里说明是1-10的数字,所以我把随机数范围改成了1-10,如果你确实想限定在1-2,可以改回原范围。
内容的提问来源于stack exchange,提问作者user21056488
相关产品推荐
相关产品推荐

