从1个单个函数中分配5个不同的变量

时间:2017-03-28 03:22:09

标签: python

我有功能得分,我必须用它来创建5个变量,这些变量是用整数随机选择的, scores1 是第一个变量。我希望能够分配新变量 scores2 scores3 scores4 scores5 ,这些都遵循与 scores1 相同的路径。下面的代码没有错误;这只是我试图解释的一个例子。如何使用或编辑此函数来创建这5个随机整数变量?

import simplegui

import random

A_plus = 3
A = 3
B = 36
C = 58

def scoring():
    global scores

    score = random.randint(1, 100)
    if score < 4:

        scores = ['97', '98', '99', '100']
        scores1 = random.choice(scores)


    if 3 < score < 7:

        scores = ['93','94','95','96'] 
        scores1 = random.choice(scores)


    if 6 < score < 45:

        scores = ['83','86','87','89']
        scores1 = random.choice(scores)


    if 44 < score < 101:

        scores = ['70','72','76','79']
        scores1 = random.choice(scores)


scoring()

3 个答案:

答案 0 :(得分:1)

最直接的方法是在功能之外进行分配。然后很容易将结果放在任何所需的变量中:

def scoring():
    score = random.randint(1, 100)
    if score < 4:
        scores = ['97', '98', '99', '100']
        score = random.choice(scores)
    if 3 < score < 7:
        scores = ['93','94','95','96'] 
        score = random.choice(scores)
    if 6 < score < 45:
        scores = ['83','86','87','89']
        score = random.choice(scores)
    if 44 < score < 101:
        scores = ['70','72','76','79']
        score = random.choice(scores)
    return score

score1 = scoring()
score2 = scoring()
score3 = scoring()
score4 = scoring()
score5 = scoring()

答案 1 :(得分:-1)

我不知道你要做什么,但是下面的代码会为你做的工作

import random

A_plus = 3
A = 3
B = 36
C = 58

def scoring():
    global scores

    score = random.randint(1, 100)
    if score < 4:

        scores = ['97', '98', '99', '100']
        scores1 = random.choice(scores)


    if 3 < score < 7:

        scores = ['93','94','95','96'] 
        scores1 = random.choice(scores)


    if 6 < score < 45:

        scores = ['83','86','87','89']
        scores1 = random.choice(scores)


    if 44 < score < 101:

        scores = ['70','72','76','79']
        scores1 = random.choice(scores)

    return scores1
score_list = []
for each in range(5):
    score_list.append(scoring())
print score_list

output : ['87', '79', '79', '89', '86']

您只需将其绑定到变量即可。由您决定,您可以将其放在列表或字典或个别变量中

答案 2 :(得分:-1)

我认为这就是你想要的:

import random

def scoring(score):
    if 0 <= score < 4:
        scores = ['97', '98', '99', '100']
        return random.choice(scores)
    elif 4 <= score < 7:
        scores = ['93','94','95','96'] 
        return random.choice(scores)
    elif 7 <= score < 45:
        scores = ['83','86','87','89']
        return random.choice(scores)
    elif 45 <= score <= 100:
        scores = ['70','72','76','79']
        return random.choice(scores)

l = [3, 3, 57, 70, 99] # these are the list of variables
scores = [scoring(score) for score in l]
print(scores)

输出:

['100', '97', '89', '72']

由于输出是随机的,因此上面的输出供您参考。