gpt4 book ai didi

python - 一旦满足条件,循环将无法终止

转载 作者:太空宇宙 更新时间:2023-11-04 10:05:54 24 4
gpt4 key购买 nike

我试图让我的函数在遇到 return 子句时结束循环,但它没有这样做。解释而不是直接代码编辑将不胜感激。

def Menu():
UserMenu = True
print ("""
U.Create a Username
E.Run Exponential Calculator
Q.Exit/Quit
""")
while UserMenu not in ("U", "E", "Q"):
print("\n Error: Choice must be U, E or Q")
return UserMenu

# Function designed to retrieve first name only from fullname entry.
def get_first_name(name):
first=[""]
i = 0
while i < len(name) and name[i] !=" ":
first += name[i]
i += 1
return name[:i]

# Function designed to retrieve first initial of last name or first initial of first name if only one name input.
def get_last_initial(name):
j = len(name) - 1
while j >= 0 and name[j] !=" ":
j-=1
return name[j+1]


# Function that generates username based upon user input.
def get_username():
name = raw_input("Please enter your Full Name: ")
username = get_first_name(name) + get_last_initial(name)
return username.lower()



# Function to generate exponential numbers based upon usser input.
def print_exponential():
base = int(raw_input("Please select a base number: \n"))
power = int(raw_input("Please select a power number: \n"))
exponential = 1
while power>0:
exponential = exponential * base
print base
if power >1:
print "*",
power = power -1
return "=%d" % exponential

print Menu()
while UserMenu != "Q":
if UserMenu is "U":
UserMenu = raw_input("Please enter your Full Name: ")
print "your username is %s" % get_username()
else:
print print_exponential()
print Menu()

这就是整个程序,希望对您有所帮助!

最佳答案

需要在循环内更新UserMenu的值,否则进入循环本身就是死循环:

def Menu():
UserMenu = raw_input("""
U.Create a Username
E.Run Exponential Calculator
Q.Exit/Quit
""")
while UserMenu not in ("U", "E", "Q"):
UserMenu = raw_input("\n Error: Please input only U, E or Q:")
return UserMenu


...
all your other functions
...

user_choice = Menu()
while user_choice != "Q":
if user_choice == "U":
print "your username is %s" % get_username()
else:
print_exponential()
user_choice = Menu()

通过在循环中获取新的输入,它将能够满足控制循环的条件。您编写的循环将只打印然后再次检查 UserMenu 而不更改它,因此循环永远不会退出。

关于python - 一旦满足条件,循环将无法终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41061239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com