Question about python3 random number | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Question about python3 random number

This is the question: Generate a three digit number and compute the sum of the digits #This is my code: import random randomnum = random.randint(100,999) print (randomnum) value = 0 for x in randomnum: print (x) value += x print ("the num is", randomnum, "the sum is", value) The Error I'm getting is : Traceback (most recent call last): File "<ipython-input-55-0a3f61271835>", line 8, in <module> for x in randomnum: TypeError: 'int' object is not iterable Could someone please help me find my mistake would appreciate it greatly. Thank you in advance!

28th Dec 2019, 7:22 PM
Eda Bozkurt
Eda Bozkurt - avatar
4 Answers
+ 5
# change:- for x in randomnum: print (x) value += x # to:- for x in str(randomnum): print(x) value += int(x)
28th Dec 2019, 7:44 PM
rodwynnejones
rodwynnejones - avatar
+ 1
I'm new to this but had a similar problem myself, I changed the number into a string then you can treat each digit as a separate item.
28th Dec 2019, 7:49 PM
teresa hinkley
teresa hinkley - avatar
+ 1
The "for x in str(randomnum):" converts it to a string so as to make it iterable... The "value += int(x)" then converts each element (x) back to an int and adds it to "value".
28th Dec 2019, 8:02 PM
rodwynnejones
rodwynnejones - avatar
0
Oh amazing ! it worked now. @rodwynejones thank you very much! :) could you also explain to me please why the randomnum has to be changed to a string? why couldn't it add the value of zero + the necessary numbers?
28th Dec 2019, 7:52 PM
Eda Bozkurt
Eda Bozkurt - avatar