簡體   English   中英

關於我的更高或更低數字猜謎游戲的問題

[英]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數據類型。

它現在可以工作了。

您的代碼中有兩個錯誤。

  1. input返回用戶在鍵盤上鍵入的原始字符串,變量player獲取此值。即 str。 因此,導致了 TypeError。
  2. 這是一個邏輯錯誤。 即使你改變
    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)
    在最后一個 else 塊下 while 之后。 該行會將玩家的 int 值與計算機的猜測進行比較,並覆蓋現在將是布爾值的玩家 var。 如果它與計算機的值匹配,則為True ,否則為False

基本上我們將 var player用於兩個目的:

  1. 存儲用戶在鍵盤上鍵入的integer數值。
  2. 作為一個布爾標志來檢查用戶的值是否等於計算機的猜測。

進行這些更改后,您的代碼應如下所示:

...
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM