首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不带中断或继续的Python Make函数

不带中断或继续的Python Make函数
EN

Stack Overflow用户
提问于 2015-04-09 01:16:20
回答 3查看 69关注 0票数 1

我有这个功能

代码语言:javascript
复制
def getInput(rows, cols, myList):
    myList = [[0]*(cols-2) for i in range(rows-2)] #creates the board
    for i in myList: # adds -1 to beginning and end of each list to make border
        i.append(-1)
        i.insert(0,-1)
    myList.insert(0,[-1]*(cols)) #adds top border
    myList.append([-1]*(cols)) #adds bottom border

    while True:
        rows = input("Please enter the row of a cell to turn on or 'q' to exit: ")
        if rows == 'q': # if q then end while loop
            break
        cols = input("Please enter the column of a cell to turn on: ")
        print()
        myList[int(rows)][int(cols)] = 1 # changes chosen cells from 0(dead) to 1(alive)
    return myList

我需要知道一种方法,让这个函数在不中断或继续的情况下。

EN

回答 3

Stack Overflow用户

发布于 2015-04-09 01:35:40

我认为这应该可以做到:

代码语言:javascript
复制
...
rows = ""
while rows != 'q':
    rows = input("Please enter the row of a cell to turn on or 'q' to exit: ")
    if rows != 'q': # if q then end while loop
        cols = input("Please enter the column of a cell to turn on: ")
        print()
        myList[int(rows)][int(cols)] = 1 # changes chosen cells from 0(dead) to 1(alive)
return myList

只有当rows不是True时才进入if块,如果在任何运行中,rows初始化为"q",那么while循环将在下一次运行时自动终止。

票数 1
EN

Stack Overflow用户

发布于 2015-04-09 01:21:26

您可以拥有一个保存布尔值True的变量,并且可以在所需的基本条件if rows == 'q':中转换为False

代码语言:javascript
复制
status = True
while status:
    rows = input("Please enter the row of a cell to turn on or 'q' to exit: ")
    if rows == 'q':
        status = False
        continue
    cols = input("Please enter the column of a cell to turn on: ")
    print()
    myList[int(rows)][int(cols)] = 1
return myList

如果您不想同时使用breakcontinue语句。然后,您应该返回myList,因为它将从终止while循环的函数中退出。

代码语言:javascript
复制
if rows == 'q':
    return myList
票数 0
EN

Stack Overflow用户

发布于 2015-04-09 02:21:59

如何使用else来避免需要continue。

代码语言:javascript
复制
def getInput(rows, cols, myList):
    myList = [[0]*(cols-2) for i in range(rows-2)] #creates the board
    for i in myList: # adds -1 to beginning and end of each list to make border
        i.append(-1)
        i.insert(0,-1)
    myList.insert(0,[-1]*(cols)) #adds top border
    myList.append([-1]*(cols)) #adds bottom border
    run = True

    while run:
        rows = input("Please enter the row of a cell to turn on or 'q' to exit: ")
        if rows == 'q': # if q then end while loop
            run = False
        else:
            cols = input("Please enter the column of a cell to turn on: ")
            print()
            myList[int(rows)][int(cols)] = 1 # changes chosen cells from 0(dead) to 1(alive)
    return myList
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29521184

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档