0
votes

So I'm seriously struggling with this python assignment I've got. My assignment is to write a program that uses main and a void function named randnums that generates 6 random numbers between 0 and 10, Then prints them all on one line. Also, randnums needs to print the total of the 6 number on a new line.

Here's the code I've created so far:

import random

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

main()

I can't figure out how to sum the 6 numbers up.

3
please use proper indentation and formatted code. +1 for being honest that this is a homework. Not sure anyone will help though - ismailsunni
Use the builtin function aptly named sum. - Chris Martin
I made one comment but it was no good. Make a variable outside your for loop and set it to 0. Every time you make a new random number, add that random to your total variable. Check count to see when you are in the last iteration of your loop, and at that time output total to screen - WDS
n = 0 outside/before the loop, n +=randnums in the loop. print n outside/after the loop - Padraic Cunningham
You aren't following the instructions. There needs to be a randnums function. You can get the right output and it will still be marked wrong for not following the instruction. - Paul

3 Answers

0
votes

You are very close to finishing your assignment. Here is how to create a variable. Call it whatever you want. I call it sum_num and set it to 0. Then add the random number you generate to it. Follow the rest of the instructions about randnums function and let me know if you have any question.

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
votes

A more simplistic way to do it:

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
votes

you need to store the sums of the numbers in a variable then add each of the six numbers to the sum, your assignment also requires it to be in a function called 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()