【问题标题】:Python: How do I return strings in def's that contain if/else funtionsPython:如何在包含 if/else 函数的 defs 中返回字符串
【发布时间】:2019-02-26 21:09:45
【问题描述】:

所以,我一直在研究这个问题一段时间,并进行了研究并仔细检查了我的代码,但我不知道哪里出了问题。

我遇到的问题是当我尝试打印或返回一个字符串时它什么也没做。如果我单独取出琴弦,它们就可以正常工作。这是我的代码的一部分。 (我有两段这样的代码,第一段有 if 和 elif 和第二段 if 和 else 都没有做任何事情)

speed=int(input("Expected average speed in MPH?"))

def response(speed):

    if speed > 80:


        return "Your travelling dangerously fast, as well as breaking the law. Slow down."


    elif speed < 60:


        return "Your going slow. Please speed up to not be a hinderance to other traffic."

我的这部分代码没有出现在最终结果中。我想不出我做错了什么。而如果我只是这样做,它就可以正常工作。

enter=int(input("Enter I-15 at what mile marker?"))

exit=int(input("Exit I-15 at what mile marker?"))

def milestotravel(exit, enter):
    return abs(exit-enter)

print ("You will travel: "+str(milestotravel(exit, enter))+" miles.")

到目前为止我的整个代码:(仍在处理其中的一些)

enter=int(input("Enter I-15 at what mile marker?"))

exit=int(input("Exit I-15 at what mile marker?"))

goal=float(input("How many hours from now do you want to arrive?"))

speed=int(input("Expected average speed in MPH?"))


def milestotravel(exit, enter):
    return abs(exit-enter)

def traveltime(speed, goal):
    return goal/speed

def response(speed):

    if speed > 80:

        print "Your travelling dangerously fast, as well as breaking the law. Slow down."

    elif speed < 60:
        print "Your going slow. Please speed up to not be a hinderance to other traffic."


print ("You will travel: "+str(milestotravel(exit, enter))+" miles.")


def response2(traveltime, goal, speed):

    if traveltime(speed, goal) > goal:
        print "You will be "+str(traveltime(speed, goal)-goal)+" hours late."

   else:
        print "Leave in the next "+str(traveltime(speed, goal))+" hours to be on time."

【问题讨论】:

  • 嗨,您根本没有调用 response(speed),它没有理由打印这些消息 :)
  • 你在哪里调用response函数?换句话说,你在哪里做speed=...; response(speed)
  • 我试过退货和打印。我把它改回来了。我将发布其余的代码。也非常感谢您的帮助! :D

标签: python string python-2.7 if-statement


【解决方案1】:

你真的在任何地方调用你的函数吗?看起来不像你。您已经定义了它(def 代码块),但要真正对它做一些事情,您必须调用它。

把它放在你的文件中(在你的 def 代码块之后):

response(speed)

然后运行您的文件。定义一个函数(def 等...)不会运行该函数,它只会让您稍后通过调用它来运行它(就像您通过说 print('some text') 来调用 print 一样

此外,根据您的编辑,由于您现在要返回字符串,因此您需要将以下内容添加到您的文件中(而不是我上面写的):

print(response(speed))

【讨论】:

  • 谢谢! :D 成功了!我没有意识到我需要在 def 之外打印它
猜你喜欢
  • 1970-01-01
  • 2013-01-16
  • 1970-01-01
  • 2014-10-30
  • 2014-05-20
  • 1970-01-01
  • 2020-01-08
  • 2021-10-23
  • 1970-01-01
相关资源
最近更新 更多