如何在一个函数中返回字符串然后打印它? [英] How do I return string in one function and then print it?

查看:251
本文介绍了如何在一个函数中返回字符串然后打印它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Python 3.7,我对我的代码有一些疑问。

仅返回字符串是什么意思?如果一个函数只是返回字符串,我如何在代码末尾打印返回的字符串?

例如,如果我写下面的代码:



I am using Python 3.7 and I have some questions about my code.
what does "returning the string only" mean? If a function is just returning the string, how can I print that - returned string at the end of my code?
For example, if I write the following code:

def word(num):
  d1= {0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',5:'Five',6:'Six',7:'Seven',8:'Eight',9:'Nine',10:'Ten',11:'Eleven',12:'Twelve',13:'Thirteen',14:'Fourteen',15:'Fifteen',16:'Sixteen',17:'Seventeen',18:'Eighteen',19:'Ninteen',20:'Twenty',30:'Thirty',40:'Fourty',50:'Fifty',60:'Sixty',70:'Seventy',80:'Eighty',90:'Ninty'}

  if num >= 100 or num <= -100:
    return "This number is out of range"
  elif num < 0:
    return "This number is less than 0 and it's spelling is Minus " + word(-num)
  elif num < 20:
    return d1[num]
  else:
    if num % 10 == 0:
      return d1[num]
    else:
      return d1[num // 10 * 10] + ' ' + d1[num % 10]



print (word(- 100))
print (word(- 42))
print (word(13))







这里的功能是印刷也是如此。但是如果我想从这个函数返回字符串并想要在这个函数之外打印返回的字符串,我该怎么办呢?

我试过的方式,是不是?



我尝试了什么:



def main():

print(word(-100))

print(word(-42))

print(word(13))




Here the function is printing as well. But if I want to return the string from this function and want to print the returned string outside of this function, how can I do that?
The way I tried, is it right?

What I have tried:

def main():
print (word(-100))
print(word(-42))
print(word(13))

推荐答案

引用:

print(word( - 100))

print(word( - 42))

print(word(13))

print (word(- 100))
print (word(- 42))
print (word(13))



上面的代码不是 word 函数的一部分,它在全局范围内(它不是缩进的)。





如果你定义


The above code is not part of the word function, it is in the global scope (it is NOT indented).


If you define

def main():
  print (word(-100))
  print(word(-42))
  print(word(13))

然后你必须在全局范围内调用它,以便看到任何输出:

then you have to call it in the global scope, in order to see any output:

main()


这篇关于如何在一个函数中返回字符串然后打印它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆