[英]Issue on my higher or lower number guessing game
import random
from random import randint
import string
computer = random.randint(0, 50)
player = False
while player == False:
player = input("Choose number 1-50: ")
if player == computer:
print("Well Done!")
elif player < computer:
print("Higher")
else:
print("Lower")
on the '<' part of the code, I get the message " TypeError: '<' not supported between instances of 'str' and 'int' ".在代码的“<”部分,我收到消息“TypeError: '<' not supported between instances of 'str' and 'int'”。 Any ideas on how to fix this?有想法该怎么解决这个吗?
This is one of the basic concepts of python.这是python的基本概念之一。 When you take a input in python it is stored as a string and not a number.当您在 python 中输入时,它将存储为字符串而不是数字。 Even though the user inputs a number it will get converted to string.即使用户输入了一个数字,它也会被转换为字符串。
For example if the random number is 5
and the user inputs 5 too, it'd be comparing 5 to "5" as they both are different datatypes(str and int).例如,如果随机数是5
并且用户也输入了 5,它会将 5 与“5”进行比较,因为它们都是不同的数据类型(str 和 int)。
In order for your program to work, change the line from为了使您的程序正常工作,请将行从
player = input("Choose number 1-50: ")
To至
player = int(input("Choose number 1-50: "))
By putting the input("Choose number 1-50: ")
into int()
you're converting it to the int
datatype.通过将input("Choose number 1-50: ")
放入int()
您将其转换为int
数据类型。
It would work now.它现在可以工作了。
You have two mistakes in your code.您的代码中有两个错误。
input
returns a raw string typed by user at the keyboard and variable player
gets this value .ie a str. input
返回用户在键盘上键入的原始字符串,变量player
获取此值。即 str。 Thus, TypeError is caused.因此,导致了 TypeError。player = input("Choose number 1-50: ")
player = int(input("Choose number 1-50: "))
player = int(input("Choose number 1-50: "))
, player = int(input("Choose number 1-50: "))
,player
will always contain an integer
value. player
将始终包含一个integer
数值。 While Loop can stop early if user types a non-zero number because non-zero int != False
.如果用户键入非零数字,则循环可以提前停止,因为non-zero int != False
。 You should add你应该添加player = (player==computer)
True
if it matches computer's value and False
otherwise.如果它与计算机的值匹配,则为True
,否则为False
。 Basically we will be using var player
for two purposes:基本上我们将 var player
用于两个目的:
integer
value typed by user at the keyboard.存储用户在键盘上键入的integer
数值。After these changes, your code should look like this:进行这些更改后,您的代码应如下所示:
...
while player == False:
player = int(input("Choose number 1-50: "))
... # if else blocks
player = (player == computer) # check if player == computer or not
Replace代替
input("Choose number 1-50: ")
With:和:
int(input("Choose number 1-50: "))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.