【问题标题】:How do you print a function's result in python? [closed]如何在 python 中打印函数的结果? [关闭]
【发布时间】:2015-09-26 17:29:28
【问题描述】:
def add(a,b):
    return a+b
    print(a+b)
def subtract(a,b):
    return a-b
    print(a-b)
def multiply(a,b):
    return a*b
    print(a*b)
def divide(a,b)
    return a/b
    print(a/b)

print('Please select an operation:')
print('1.Add')
print(2.Subtract')
print(3.Multiply')
print(4.Divide')
choice=input('Enter a choice\'1/2/3/4\')
a=int(input('Enter first number')
b=int(input('Enter second number')
if choice=='1':
#these are the sections that arent working
    add(a,b)
elif choice=='2':
#when run, it wont print the function even though Ive called it
    subtract(a,b)
elif choice=='3':
    multiply(a,b)
elif choice=='4':
    divide(a,b)

如果有人能提供解决方案,我将不胜感激。谢谢

【问题讨论】:

  • return 立即离开一个函数。在前四个函数的 print 语句之后,您需要 return。
  • 哦,好的。谢谢;这帮助很大。

标签: python function boolean


【解决方案1】:

函数中return 语句之后的任何代码都不会运行。

如果你想让 print 成为函数的一部分,你必须这样做:

def add(a,b):
    print(a+b)
    return a+b
def subtract(a,b):
    print(a-b)
    return a-b
def multiply(a,b):
    print(a*b)
    return a*b
def divide(a,b):
    print(a/b)
    return a/b

但是,更好的方法是 print 函数在主函数中返回的数字。例如:

def add(a,b):
    return a+b
def subtract(a,b):
    return a-b
def multiply(a,b):
    return a*b
def divide(a,b):
    return a/b

print('Please select an operation:')
print('1.Add')
print('2.Subtract')
print('3.Multiply')
print('4.Divide')
choice = input("Enter a choice: '1/2/3/4'")
a = int(input('Enter first number'))
b = int(input('Enter second number'))    

if choice == '1':
    result = add(a, b)
elif choice == '2':
    result = subtract(a, b)
elif choice == '3':
    result = multiply(a, b)
elif choice == '4':
    result = divide(a, b)
print(result)

【讨论】:

  • 谢谢,我的代码现在可以使用了
  • @Davina 太好了,我很高兴能帮上忙。 :) 在那种情况下,你介意接受我的回答吗?您只需单击投票箭头旁边的复选标记。它让其他人知道这是有效的。
【解决方案2】:

在所有函数中切换print 和return 的顺序

def divide(a,b)
    print(a/b)
    return a/b

函数中的任何内容都不会在return 之后执行,因此您的任何print 语句都不会到达。

【讨论】:

    猜你喜欢
    • 2017-05-03
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    相关资源
    最近更新 更多