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 很陌生,不知道如何初始化用户输入的字符。它需要在 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!")
推荐阅读
- react-native - React Native 会执行 Tree Shaking 吗?
- ibm-cloud - softlayer 带宽池删除
- dart - 每隔一定时间间隔选择地理位置
- c - C - 检查主要参数
- android - 无法连接到 Android 模拟器 Windows 操作系统上的开发服务器?
- android - 当应用程序处于后台或在 android 中关闭时,FCM 通知未在通知栏中显示可扩展图像
- java - Activity 的 onCreate 方法上的 NullPointerException。必须在 setContentView() 之前动态添加视图
- jquery - 是否可以像'Jquery'附加元素一样在角度4中动态创建元素?
- javascript - 如何使用 jasmine 监视 localStorage 方法
- react-native - 如何在 React-Native 中导航?