我需要重复这段代码,以便第二位用户输入其详细信息
print ("Welcome to the Dice Game!")
username = input("please enter your Username... ")
f = open("L:/GCSE/Computer Science/Programming/username.txt","r")
# Creates a list. Each item in the list is a string of each line in the text files. It is stored in the variable lines
lines = f.readlines()
# the strings in the list (called lines), also contains escape charachters and whitespace. So this will create a new list, and for each string in the lines list will strip off white space before and after the string
users = [user.strip() for user in lines ]
# checks to see if the username input is also in the users list
if username in users:
password = input("Please enter your password: ")
else:
print("That is an incorrect username")
passwords = open("L:/GCSE/Computer Science/Programming/passwords.txt","r")
lines = f.readlines()
passwords = [passwords.strip() for users in lines ]
if password in ("F:/GCSE/Computer Science/Programming/passwords.txt"):
password = print ("Welcome to the Dice Game!")
else:
print("That is the wrong password")
答案 0 :(得分:2)
为了重复一段代码,可以使用循环。 一个非常简单的方法是:
for _ in range(2):
# (your code here)
为使代码更整洁,我建议将函数中的内容打包,然后从循环中调用该函数:
def get_user_input():
# your code here
for _ in range(2):
get_user_input()
或者类似的东西...
答案 1 :(得分:0)
为适应这种情况,您可以添加一个计数器,该计数器从0开始加星号,当玩家2需要添加详细信息时添加一个计数器,如下所示:
count = 0
def get_user_input():
if count == 0:
#player one code
else:
#player two code