首页 > 解决方案 > 代码结束时在 Python 中再次启动函数

问题描述

我创建了一些代码

def Basket(): #the  start of the code

    items1=[]

    items1=input("type items\n")

    options=int(input("choose options\n"))

    if options==1:
        print("items on basket are:\n", items1)

    elif options==2:
        print(items1.count(',')+1) #the end

Basket() 

我想一次又一次地使用该程序而不关闭它,所以我需要程序在结束帮助后始终转到代码的开头?

标签: python

解决方案


简单地 :

def Basket(): #the  start of the code

    while True:
        items1=[]

        items1=input("type items\n")

        options=int(input("choose options\n"))

        if options==1:
            print("items on basket are:\n", items1)

        elif options==2:
            print(items1.count(',')+1) #the end

Basket() 

或者(正如@zvone 评论的那样)

def Basket(): #the  start of the code

    items1=[]

    items1=input("type items\n")

    options=int(input("choose options\n"))

    if options==1:
        print("items on basket are:\n", items1)

    elif options==2:
        print(items1.count(',')+1) #the end

while True: Basket()

或(优雅地)

def Basket(): #the  start of the code

    while input("add an item ? (y:Yes or n:No) \n") == "y":
        items1=[]

        items1=input("type items\n")

        options=int(input("choose options\n"))

        if options==1:
            print("items on basket are:\n", items1)

        elif options==2:
            print(items1.count(',')+1) #the end

Basket()

推荐阅读