从循环python 3出口3



im新的ish to python和我得到了此代码,我希望它允许在输入时随时输入"退出"一词。一旦完成,它就会关闭脚本。

任何帮助将不胜感激。

import sys
while True:
    def inputs():   
        first=input("Enter your first name: ")
        last=input("Enter your last name: ")
        gender=input("Enter your gender: ")
        form=input("Enter your form: ")
        file = open("signup.txt", "a")
        #Records the user's details in the file
        file.write("nFirst name: "+first+", Last name: "+last+", Gender: "+gender+", Form: "+form)
        #Closes the file
        file.close()
        if input(inputs) == "exit":
            sys.exit()
    inputs()

您可以将输入函数封装在"退出"字上:

import sys
def exitInput(prompt):
  pInput = input(prompt)
  return pInput if pInput != "exit" else sys.exit()
def inputs():
  first = exitInput("Enter your first name: ")
  last = exitInput("Enter your last name: ")
  gender = exitInput("Enter your gender: ")
  form = exitInput("Enter your form: ")
  file = open("signup.txt", "a")
  file.write("nFirst name: "+first+", Last name: "+last+", Gender: "+gender+", Form: "+form)
  file.close()
inputs()

您可以在输入后每次检查它是 exit >是否。如果是 exit ,则终止程序。作为您的代码,您可以在每次服用输入后都放置给定的Bellow

if input(inputs) == "exit":
        sys.exit()

最新更新