簡體   English   中英

提示用戶輸入字符

[英]Prompting the user to input a character

n = [0, 1, 2, 3, 4, 5, 6, 7, 8]    
c = [0, 1, 2, 3, 4, 5, 6, 7, 8]
num = int (input())
char = int (input())
if n[num] % 2 == 0 and c[char] % 2 == 0 or n[num] % 2 != 0 and c[char] % 2 != 0:
    print("Black") 
else: 
    print("White")

我目前正在解決一個問題,該問題應該根據用戶輸入的坐標打印出瓷磚的顏色。 我對 python 很陌生,不知道如何初始化用戶輸入的字符。 它需要在 a - h 范圍內,並設置為 1 到 8 之間的數字。你能提示我一種方法嗎?

您可以通過在需要詢問的地方放置input調用來等待用戶輸入。

number = input("Choose a number between 1 and 10\n")
print("You chose ", number)

但是輸入將只是用戶可以輸入的內容(字符串),因此您必須小心並驗證選擇

raw_number = input("Choose a number between 1 and 10\n")
number = int(raw_number, 10)
if number >= 0  and number <= 10:
    print("The next number is ", number + 1)
else:
    print("You clearly did not read the instructions!")

再次可能是用戶所做的選擇甚至不是一個數字

raw_number = input("Choose a number between 1 and 10\n")
try:
   number = int(raw_number, 10)
except ValueError:
   print("I said a number! You gave me " raw_number)
   exit(1)
if number >= 0  and number <= 10:
    print("The next number is ", number + 1)
else:
    print("You clearly did not read the instructions!")

但也許你真的需要一個號碼,想耐心等待一個用戶

number = None
while not number:
    raw_number = input("Choose a number between 1 and 10\n")
    try:
        number = int(raw_number, 10)
    except ValueError:
        print("I said a number! You gave me ", raw_number, " try again!")
if number >= 0  and number <= 10:
    print("The next number is ", number + 1)
else:
    print("You clearly did not read the instructions!")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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