2015-09-10 73 views
0

所以我很认真地挣扎着我得到的这个python任务。我的任务是编写一个程序,该程序使用main和一个名为randnums的无效函数,该函数生成0到10之间的6个随机数,然后将它们全部打印在一行上。另外,randnums需要在新行上打印总数为6的数字。总和随机数

下面是我创建至今代码:

import random 

def main(): 
    for count in range(6): 
     randnums = random.randrange(1,10) 
     print(randnums, end='') 

main() 

我无法弄清楚如何总结了6个号码了。

+0

请使用正确的缩进和格式化代码。 +1为诚实,这是一项功课。不确定有人会帮忙,虽然 – ismailsunni

+1

使用恰当命名'sum'的内建函数。 –

+0

我发表了一条评论,但并不好。在for循环外创建一个变量并将其设置为0.每次创建一个新的随机数时,将该随机数添加到您的总变量中。检查计数以查看当你处于循环的最后一次迭代中时,此时输出的总数在循环之前/之前输出 – WDS

回答

0

你非常接近完成你的任务。这里是如何创建一个变量。随心所欲地调用它。我将它称为sum_num并将其设置为0.然后将生成的随机数添加到它。按照关于randnums函数的其余指示,并让我知道你是否有任何问题。

import random 

def main(): 
    sum_num = 0 
    for count in range(6): 
     randnums = random.randrange(1,10) 
     sum_num = sum_num + randnums 
     print(randnums, end='') 
    print(sum_num) 

main() 
0

一种更简单的方式做到这一点:

from random import randrange 

def randnums(): 
    nums = [str(randrage(1,10)) for i in range(6)] # list comprehension 
    print(' '.join(nums)) # use of join method of strings 
    print(sum(nums)) # use of built in method 

def main(): 
    randnums() 

main() 
0

你需要的数字的总和存储在一个变量,然后每六个数字的增加的总和,你的任务也需要它在函数中调用randnums

import random 

def randnums(): 
    # list for storing the list of numbers 
    number_list = [] 
    # the sum of each of the random numbers 
    number_sum = 0 
    for count in range(6): 
     # generate a random number 
     num = random.randrange(0, 10) 
     # convert the number to a string and add to the list 
     number_list.append(str(num)) 
     # add the random number to the sum 
     number_sum += num 
    # join together the numbers with a space and print to the console 
    print ' '.join(number_list) 
    # on a new line display the total 
    print number_sum 

def main(): 
    # call the void randnums function from main 
    randnums() 

main()