Python: 如何要求一个输入与前一个输入对应?
Python: How to require an input to correspond with a previous input?
全部。 Python这里是新手。
简单来说就是我的基本思路:
我想创建一个“登录”功能,用户必须从预设元组中输入有效的用户名。
接下来,一旦输入了有效名称,他们将被要求输入相应的代号,并将其保存到字典中。 (我觉得我把这个复杂化了,或者字典可能完全是错误的想法,所以任何关于如何简化的建议都会很好)。
real_names = ("JD", "JM" "JC")
player_ids = {"JD":"Arrow","JM":"Bullet","JC":"Blade"}
while True:
# user must input a name from the real_names tuple
name = input("User unidentified. Please input your name: ")
# if username is not in tuple, rerun script
if not name in real_names:
print("Invalid username detected")
continue
print(f"Positive ID! Welcome, {name}")
break
上面的代码工作得很好。但接下来,我想进行一个新的输入,要求玩家 ID 与之前输入的名称相匹配。在伪代码中,是这样的:
# While True Loop:
id = input("Please confirm user Code Name: ")
#ID must correspond to keyword in dictionary
if ID value does not match username Keyword:
print("Invalid ID")
continue
print("Identity confirmed!")
break
我走的路对吗?如果是这样,我将如何语法第二部分?如果字典完全是错误的想法,请提供一个好的替代方案。非常感谢!
player_ids[name]
是您要查找的值。所以,你想要这样的东西:
if id != player_ids[name]:
print("invalid ID")
另外,字典已经记录了球员的名字,所以你不需要 real_names
元组。
之前的答案很完美,因为您是根据字典中的键查找值。最后,一个小提示,避免在保留变量和关键字之后命名变量始终是一个好习惯,也就是说,使用另一个变量名以防万一您要在程序中再次使用 id()
函数.
全部。 Python这里是新手。
简单来说就是我的基本思路:
我想创建一个“登录”功能,用户必须从预设元组中输入有效的用户名。 接下来,一旦输入了有效名称,他们将被要求输入相应的代号,并将其保存到字典中。 (我觉得我把这个复杂化了,或者字典可能完全是错误的想法,所以任何关于如何简化的建议都会很好)。
real_names = ("JD", "JM" "JC")
player_ids = {"JD":"Arrow","JM":"Bullet","JC":"Blade"}
while True:
# user must input a name from the real_names tuple
name = input("User unidentified. Please input your name: ")
# if username is not in tuple, rerun script
if not name in real_names:
print("Invalid username detected")
continue
print(f"Positive ID! Welcome, {name}")
break
上面的代码工作得很好。但接下来,我想进行一个新的输入,要求玩家 ID 与之前输入的名称相匹配。在伪代码中,是这样的:
# While True Loop:
id = input("Please confirm user Code Name: ")
#ID must correspond to keyword in dictionary
if ID value does not match username Keyword:
print("Invalid ID")
continue
print("Identity confirmed!")
break
我走的路对吗?如果是这样,我将如何语法第二部分?如果字典完全是错误的想法,请提供一个好的替代方案。非常感谢!
player_ids[name]
是您要查找的值。所以,你想要这样的东西:
if id != player_ids[name]:
print("invalid ID")
另外,字典已经记录了球员的名字,所以你不需要 real_names
元组。
之前的答案很完美,因为您是根据字典中的键查找值。最后,一个小提示,避免在保留变量和关键字之后命名变量始终是一个好习惯,也就是说,使用另一个变量名以防万一您要在程序中再次使用 id()
函数.