我到处找遍,什么都试过了。我正在创建一个游戏,在这个游戏中,用户将输入一个预先分配的引脚,并且我希望根据Python中的.txt文件验证该引脚。我尝试了这么多不同的代码行,我的结果要么一切都是有效的,要么没有什么是有效的。我做错了什么?引脚是在每一行上格式化的,并且是alpha数字,如下所示.
1DJv3Awv5
1DGw2Eql8
3JGl1Hyt7
2FHs4Etz4
3GDn9Buf8
1CEa9Aty0
2AIt9Dxz9
5DFu0Ati4
3AJu9Byi4
1EAm0Cfn1
3BEr0Gwk0
7JAf8Csf8
4HFu0Dlf4以下是我所拥有的:
user_input = input('Please enter your PIN: ')
if user_input in open("PINs.txt").read():
print('Congratulations! Click the button below to get your Bingo Number.')
else:
print('The PIN you entered does not match our records. Please check your PIN and try again.')发布于 2022-05-06 23:01:06
尝试使用.readlines(),这样您必须匹配整个字符串:
user_input = input('Please enter your PIN: ') + "\n" # Adding \n to conform to readlines
if user_input in open("PINs.txt").readlines():
print('Congratulations! Click the button below to get your Bingo Number.')
else:
print('The PIN you entered does not match our records. Please check your PIN and try again.')小型重构:
with open("PINs.txt") as pinfile: # Make sure file is closed
user_input = input('Please enter your PIN: ')
for pin in pinfile: # Iterate line by line, avoid loading the whole file into memory.
if pin.rstrip() == user_input: # Remove newline using .rstrip()
print('Congratulations! Click the button below to get your Bingo Number.')
break
else: # Note the indentation, the 'else' is on the 'for' loop.
print('The PIN you entered does not match our records. Please check your PIN and try again.')实际上,您可以完全避免使用.readlines(),这利用了文件对象遍历行的事实,并且对内存也更好:
user_input = input('Please enter your PIN: ') + "\n" # Adding \n to conform to readlines
if user_input in open("PINs.txt"):
print('Congratulations! Click the button below to get your Bingo Number.')
else:
print('The PIN you entered does not match our records. Please check your PIN and try again.')https://stackoverflow.com/questions/72147585
复制相似问题