I'm not sure what is wrong with your code because of its poor indentation but here are some things to take note of:
- You need to have a variable which stores the total
- Python print function defaults all strings to print out with a newline.
Store total
This is simple, just add a variable outside of the for loop which adds the number:
def randnums():
# Add this new variable
total = 0
for num in range(0, 6):
num1 = random.randint(1, 9)
total += num1
# Print it out
print("The total is:", total)
Remove newline
For Python 3, it is simple to remove the newline. Just supply a new keyword argument to the print function and it will work:
def randnums():
total = 0
for num in range(0, 6):
num1 = random.randint(1, 9)
total += num1
# End the string with a space. Also removes newline
print(num1, end=" ")
# Add a newline before printing again.
print("\nThe total is:", total)
If you are using Python 2 in the future, you could do it two ways: Either import print_function
from __future__
or print
with a comma:
Import from __future__
:
# Note that this import must come first
from __future__ import print_function
import random
def main():
randnums()
def randnums():
total = 0
for num in range(0, 6):
num1 = random.randint(1, 9)
total += num1
print(num1, end=" ")
print("\nThe total is:", total)
main()
Or use a comma:
import random
def main():
randnums()
def randnums():
total = 0
for num in range(0, 6):
num1 = random.randint(1, 9)
total += num1
# The comma is put after what you want to print. It also adds a space
print num1,
print "\nThe total is:", total
main()
The output:
3 9 8 2 4 1
The total is: 27