如何使程序返回到代码顶部而不是关闭[重复]
- 2025-02-20 09:25:00
- admin 原创
- 21
问题描述:
我正在尝试弄清楚如何让 Python 返回代码顶部。在 SmallBasic 中,你可以这样做
start:
textwindow.writeline("Poo")
goto start
但我不知道如何用 Python 来实现这一点 :/ 有人有什么想法吗?
我试图循环的代码是这样的
#Alan's Toolkit for conversions
def start() :
print ("Welcome to the converter toolkit made by Alan.")
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
f1 = input ("Please enter your fahrenheit temperature: ")
f1 = int(f1)
a1 = (f1 - 32) / 1.8
a1 = str(a1)
print (a1+" celsius")
elif op == "2":
m1 = input ("Please input your the amount of meters you wish to convert: ")
m1 = int(m1)
m2 = (m1 * 100)
m2 = str(m2)
print (m2+" m")
if op == "3":
mb1 = input ("Please input the amount of megabytes you want to convert")
mb1 = int(mb1)
mb2 = (mb1 / 1024)
mb3 = (mb2 / 1024)
mb3 = str(mb3)
print (mb3+" GB")
else:
print ("Sorry, that was an invalid command!")
start()
因此,基本上,当用户完成转换时,我希望它循环回到顶部。我仍然无法将您的循环示例付诸实践,因为每次我使用 def 函数循环时,它都会说“op”未定义。
解决方案 1:
使用无限循环:
while True:
print('Hello world!')
这当然也可以适用于您的start()
函数;您可以使用 退出循环break
,或使用return
完全退出该函数,这也会终止循环:
def start():
print ("Welcome to the converter toolkit made by Alan.")
while True:
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
f1 = input ("Please enter your fahrenheit temperature: ")
f1 = int(f1)
a1 = (f1 - 32) / 1.8
a1 = str(a1)
print (a1+" celsius")
elif op == "2":
m1 = input ("Please input your the amount of meters you wish to convert: ")
m1 = int(m1)
m2 = (m1 * 100)
m2 = str(m2)
print (m2+" m")
if op == "3":
mb1 = input ("Please input the amount of megabytes you want to convert")
mb1 = int(mb1)
mb2 = (mb1 / 1024)
mb3 = (mb2 / 1024)
mb3 = str(mb3)
print (mb3+" GB")
else:
print ("Sorry, that was an invalid command!")
如果你还要添加退出选项,那么可以是:
if op.lower() in {'q', 'quit', 'e', 'exit'}:
print("Goodbye!")
return
例如。
解决方案 2:
Python 与大多数现代编程语言一样,不支持“goto”。相反,您必须使用控制函数。基本上有两种方法可以做到这一点。
1. 循环
如何准确执行 SmallBasic 示例所做的事情的示例如下:
while True :
print "Poo"
就这么简单。
2. 递归
def the_func() :
print "Poo"
the_func()
the_func()
递归注意事项:仅当您有特定次数想要返回开头时才这样做(在这种情况下添加递归应停止的情况)。像我上面定义的那样进行无限递归不是一个好主意,因为您最终会耗尽内存!
编辑以更具体地回答问题
#Alan's Toolkit for conversions
invalid_input = True
def start() :
print ("Welcome to the converter toolkit made by Alan.")
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
#stuff
invalid_input = False # Set to False because input was valid
elif op == "2":
#stuff
invalid_input = False # Set to False because input was valid
elif op == "3": # you still have this as "if"; I would recommend keeping it as elif
#stuff
invalid_input = False # Set to False because input was valid
else:
print ("Sorry, that was an invalid command!")
while invalid_input: # this will loop until invalid_input is set to be False
start()
解决方案 3:
你可以用循环轻松地做到这一点,有两种类型的循环
For循环:
for i in range(0,5):
print 'Hello World'
While循环:
count = 1
while count <= 5:
print 'Hello World'
count += 1
每个循环打印“Hello World”五次
解决方案 4:
Python 有控制流语句而不是goto
语句。控制流的一种实现是 Python 的while
循环。您可以为其指定一个布尔条件(在 Python 中布尔值为 True 或 False),循环将重复执行,直到该条件变为 false。如果您想永远循环下去,只需启动一个无限循环即可。
如果您决定运行以下示例代码,请务必小心。如果您想终止进程,请在运行时在 shell 中按 Control+C。请注意,进程必须位于前台才能正常工作。
while True:
# do stuff here
pass
这行# do stuff here
只是一条注释。它不执行任何操作。pass
只是 Python 中的一个占位符,基本上表示“嗨,我是一行代码,但请跳过我,因为我什么都不做。”
现在假设您想要无限重复地要求用户输入,并且只有当用户输入字符“q”表示退出时才退出程序。
你可以做这样的事情:
while True:
cmd = raw_input('Do you want to quit? Enter \'q\'!')
if cmd == 'q':
break
cmd
只会存储用户输入的内容(系统会提示用户输入内容并按回车键)。如果cmd
只存储字母“q”,代码将强制break
跳出其封闭循环。该break
语句可让您退出任何类型的循环。即使是无限循环!如果您想编写经常在无限循环中运行的用户应用程序,学习该语句非常有用。如果用户没有准确输入字母“q”,系统将不断重复提示用户,直到强制终止进程或用户决定他已经受够了这个烦人的程序并只想退出。
解决方案 5:
编写 for 或 while 循环并将所有代码放入其中?Goto 类型编程已成为过去。
https://wiki.python.org/moin/ForLoop
解决方案 6:
您需要使用 while 循环。如果您创建了 while 循环,并且循环后没有指令,它将变成无限循环,并且除非您手动停止它,否则它将不会停止。
解决方案 7:
def start():
Offset = 5
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Please be sensible try just the lower case')
def getMessage():
print('Enter your message wanted to :')
return input()
def getKey():
key = 0
while True:
print('Enter the key number (1-%s)' % (Offset))
key = int(input())
if (key >= 1 and key <= Offset):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
mode = getMode()
message = getMessage()
key = getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
if op.lower() in {'q', 'quit', 'e', 'exit'}:
print("Goodbye!")
return
- 2024年20款好用的项目管理软件推荐,项目管理提效的20个工具和技巧
- 2024年开源项目管理软件有哪些?推荐5款好用的项目管理工具
- 2024年常用的项目管理软件有哪些?推荐这10款国内外好用的项目管理工具
- 项目管理软件有哪些?推荐7款超好用的项目管理工具
- 项目管理软件有哪些最好用?推荐6款好用的项目管理工具
- 项目管理软件哪个最好用?盘点推荐5款好用的项目管理工具
- 项目管理软件排行榜:2024年项目经理必备5款开源项目管理软件汇总
- 项目管理软件有哪些,盘点推荐国内外超好用的7款项目管理工具
- 项目管理必备:盘点2024年13款好用的项目管理软件
- 2024项目管理软件排行榜(10类常用的项目管理工具全推荐)