当我运行我的程序时,“没有”总是出现

2024-10-17 08:24:03 发布

您现在位置:Python中文网/ 问答频道 /正文

每当我运行我创建的计算器程序时,它运行得很好,但是文本“None”总是出现,我不知道为什么。代码如下:

def add():
    print 'choose 2 numbers to add'
    a=input('add this')
    b=input('to this')
    print a+b
    return menu()
def sub():
    print 'choose 2 numbers to subract'
    a=input('subract this')
    b=input('from this')
    print b-a
    return menu()
def menu():
    print "hello, Welcome"
    print "these are your options"
    print "1. add"
    print "2. sub"
print menu()
loop=2
def sys():
    while loop==2:
        a=input("please choose")
        if a==1:
            print add()
        elif a==2:
            print sub()
        else:
            return menu(),sys()
print sys()

输出如下:

^{pr2}$

如果这对任何人有帮助的话,这里是我完成的计算器的代码(当我通过它时,它看起来一团糟,但当你复制和粘贴它时,它就起作用了)

def add():
    print 'choose 2 numbers to add'
    a=input('add this')
    b=input('to this')
    print a+b
def sub():
    print 'choose 2 numbers to subract'
    a=input('subract this')
    b=input('from this')
    print b-a
def mul():
    print 'choose 2 numbers to multiply'
    a=input("multiply this")
    b=input("by this")
    print b*a
def div():
    print 'choose what numbers your want to divide'
    a=input('divide this')
    b=input('by this')
    print a/b
def exp():
    print 'choose your number you want to exponentiate'
    a=input('multiply this')
    b=input('by the power of this')
    print a**b
def menu():
    print "hello, Welcome"
    print "these are your options"
    print "1. add"
    print "2. sub"
    print "3. mul"
    print "4. div"
    print "5. expo"
    print "0. to end"
menu()
def sys():
    while True:
        a=input("please choose")
        if a==1:
             add()
             menu()
        elif a==2:
             sub()
             menu()
        elif a==3:
             mul()
             menu()
        elif a==4:
             div()
             menu()
        elif a==5:
             exp()
             menu()
        elif a==0:
            break 
        else:
            return menu(),sys()
sys()

Tags: toaddinputyourreturndefsysthis
1条回答
网友
1楼 · 发布于 2024-10-17 08:24:03

这是因为函数menu()不返回任何内容,默认情况下,python中的函数返回None

>>> def func():pass
>>> print func()  #use `print` only if you want to print the returned value
None

只需使用:

^{pr2}$

从cd6{cd6}>中删除。不要在每个函数中使用return menu(),只需调用while loop本身末尾的menu()函数。在

def sys():
    while True:
        a = input("please choose")
        if a == 1:
            add()    # call add(), no need of print as you're printing inside add() itself
        elif a==2: 
            sub()  
        menu()       # call menu() at the end of the loop

while loop==2实际上首先计算loop==2表达式,如果它是True,则{}继续,否则立即中断。在您的例子中,因为您没有更改loop变量的值,所以您可以简单地使用while True。在

>>> loop = 2
>>> loop == 2
True

相关:a basic question about "while true"

相关问题 更多 >