提示用户输入字符

时间:2019-03-27 15:22:45

标签: python

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的新手,不知道如何初始化用户输入的字符。它必须在-h范围内,并设置为1到8之间的数字。您能提示我一种方法吗?

1 个答案:

答案 0 :(得分:1)

您可以通过在需要的地方拨打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!")