首页 > 解决方案 > 提示用户输入字符

问题描述

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 的数字。你能提示我一种方法吗?

标签: python

解决方案


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!")

推荐阅读