我怎样才能压缩这个简单的 python 程序以使其更有效率?
How can I condense this simple python program to make it more efficient?
这只是我尝试制作的一个简单游戏,它会问你几个问题,然后根据答案自动格式化一个新密码。
因为我是初学者,所以我想知道一些我可以使用的技术,这些技术可以提高这段代码的效率,并且可能会删除我声明的大量函数。谢谢!
minimum = 3
maximum = 10
name = input("What is your name? ")
def nameInput():
if len(name) < minimum:
print("Name is too small")
return nameInput()
elif len(name) > maximum:
print("Name is too large")
return nameInput()
nameInput()
food = input("What is your favorite food? ")
def foodInput():
if len(food) < minimum:
print("Enter a food name longer than " + (food))
return foodInput()
elif len(food) > maximum:
print("Enter a food name shorter than " + (food))
return foodInput()
foodInput()
birthday = input("What is your date of birth? (mmddyyyy) ")
nameIndex = name[0:2]
foodIndex = food[2: ]
birthIndex = birthday[0:3]
passcode = nameIndex + foodIndex + birthIndex
print("Your password is " + passcode)
如果您追求简洁,请尝试多次使用单个函数,而不是一次使用多个函数
def get_input(variable_name, min_size, max_size, begin, end):
data = input("What is your {}? ".format(variable_name))
if len(data) < min_size:
raise ValueError('{} is too small'.format(variable_name.capitalize()))
elif len(data) > max_size:
raise ValueError('{} is too big'.format(variable_name.capitalize()))
return data[begin:end]
name_index = get_input("name", 3, 10, 0, 2)
food_index = get_input("food", 3, 10, 2, 100)
birth_index = get_input("date of birth (mmddyyyy)", 3, 10, 0, 3)
passcode = name_index + food_index + birth_index
print("Your passcode is", passcode)
这只是我尝试制作的一个简单游戏,它会问你几个问题,然后根据答案自动格式化一个新密码。
因为我是初学者,所以我想知道一些我可以使用的技术,这些技术可以提高这段代码的效率,并且可能会删除我声明的大量函数。谢谢!
minimum = 3
maximum = 10
name = input("What is your name? ")
def nameInput():
if len(name) < minimum:
print("Name is too small")
return nameInput()
elif len(name) > maximum:
print("Name is too large")
return nameInput()
nameInput()
food = input("What is your favorite food? ")
def foodInput():
if len(food) < minimum:
print("Enter a food name longer than " + (food))
return foodInput()
elif len(food) > maximum:
print("Enter a food name shorter than " + (food))
return foodInput()
foodInput()
birthday = input("What is your date of birth? (mmddyyyy) ")
nameIndex = name[0:2]
foodIndex = food[2: ]
birthIndex = birthday[0:3]
passcode = nameIndex + foodIndex + birthIndex
print("Your password is " + passcode)
如果您追求简洁,请尝试多次使用单个函数,而不是一次使用多个函数
def get_input(variable_name, min_size, max_size, begin, end):
data = input("What is your {}? ".format(variable_name))
if len(data) < min_size:
raise ValueError('{} is too small'.format(variable_name.capitalize()))
elif len(data) > max_size:
raise ValueError('{} is too big'.format(variable_name.capitalize()))
return data[begin:end]
name_index = get_input("name", 3, 10, 0, 2)
food_index = get_input("food", 3, 10, 2, 100)
birth_index = get_input("date of birth (mmddyyyy)", 3, 10, 0, 3)
passcode = name_index + food_index + birth_index
print("Your passcode is", passcode)