繁体   English   中英

如何在 python 中使用 function 之外的递增变量?

[英]How do you use an incremented variable outside of function in python?

这可能是一个愚蠢的问题; 也许我的过程完全错误(如果是,请指出),但是如何在自定义 function 中提取三个递增变量(c_char、c_word、c_sentence)并将其用于其他用途?

def length_finder(x):
    #variables counting character,word,sentnece  
    c_char = 0
    c_word = 1
    c_sentence = 0

    for i in x:
        if (i >= 'a' and i <= 'z') or (i >= 'A' and i <= 'Z'):
            c_char += 1
        if i == " ":
            c_word += 1
        if i == '.' or i == '!' or i == '?' :
            c_sentence += 1

length_finder(input("Enter the text you wish to analyze: "))

L = 100/c_word*c_char
S = 100/c_word*c_sentence

#formula to get readability
index = 0.0588 * L - 0.296 * S - 15.8

print("This text is suitable for grade " + str(index))

您可以从 function 中return多个变量:

def length_finder(x):
    ...
    return (c_char, c_word, c_sentence)


(c_char, c_word, c_sentence) = length_finder('input string')

你有两个选择。

  1. 将这三个变量设为全局变量,并在 function 中引用它们。 您可以将它们设为全局,然后在 function 中将它们作为全局引用。

  2. 从 function 中返回它们。 您可以将所有 3 个值作为字典或列表返回。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM