[英]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")
在代碼的“<”部分,我收到消息“TypeError: '<' not supported between instances of 'str' and 'int'”。 有想法該怎么解決這個嗎?
這是python的基本概念之一。 當您在 python 中輸入時,它將存儲為字符串而不是數字。 即使用戶輸入了一個數字,它也會被轉換為字符串。
例如,如果隨機數是5
並且用戶也輸入了 5,它會將 5 與“5”進行比較,因為它們都是不同的數據類型(str 和 int)。
為了使您的程序正常工作,請將行從
player = input("Choose number 1-50: ")
至
player = int(input("Choose number 1-50: "))
通過將input("Choose number 1-50: ")
放入int()
您將其轉換為int
數據類型。
它現在可以工作了。
您的代碼中有兩個錯誤。
input
返回用戶在鍵盤上鍵入的原始字符串,變量player
獲取此值。即 str。 因此,導致了 TypeError。player = input("Choose number 1-50: ")
player = int(input("Choose number 1-50: "))
player = int(input("Choose number 1-50: "))
,player
將始終包含一個integer
數值。 如果用戶鍵入非零數字,則循環可以提前停止,因為non-zero int != False
。 你應該添加player = (player==computer)
True
,否則為False
。 基本上我們將 var player
用於兩個目的:
integer
數值。進行這些更改后,您的代碼應如下所示:
...
while player == False:
player = int(input("Choose number 1-50: "))
... # if else blocks
player = (player == computer) # check if player == computer or not
代替
input("Choose number 1-50: ")
和:
int(input("Choose number 1-50: "))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.