在Python中,检查用户输入通常涉及以下几个步骤:
1. 使用`input()`函数获取用户输入。
2. 对输入进行必要的验证,确保它符合预期的格式或范围。
3. 如果输入有效,则处理该输入;否则,提示用户重新输入。
检查整数输入
while True:
try:
num = int(input("Enter an integer between 1 and 10: "))
if 1 <= num <= 10:
print(f"You entered: {num}")
break
else:
print("The integer must be in the range 1-10")
except ValueError:
print("Please enter a valid integer between 1 and 10")
检查字符串输入
while True:
password = input("Enter your password: ")
if len(password) < 5:
print("Password too short")
else:
print(f"You entered: {password}")
break
实时检测键盘输入
import sys
import tty
import termios
def readchar():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def readkey(getchar_fn=None):
getchar = getchar_fn or readchar
c1 = getchar()
if ord(c1) != 0x1b:
return c1
c2 = getchar()
if ord(c2) != 0x5b:
return c1
c3 = getchar()
return chr(0x10 + ord(c3) - 65)
while True:
key = readkey()
if key == 'w':
go_forward()
pass
elif key == 'a':
go_back()
pass
elif key == 's':
go_left()
pass
elif key == 'd':
go_right()
pass
获取用户输入并转换为特定类型
name = input("Please enter your name: ")
print(f"Welcome, {name}")
以上示例展示了如何使用`input()`函数获取用户输入,并通过异常处理和条件语句来验证输入的有效性。对于更复杂的输入验证,可能需要使用正则表达式或其他高级验证技术