Help! What’s the difference? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
0

Help! What’s the difference?

#1 Import random For x in range(5): value=random.randint(1,6) print(value) #2 Import random For x in range(5): x=random.randint(1,6) print(x) What is the difference between the first and second? Why is x used in #1 when it is not referred to anywhere else in the next lines of code? Shouldn’t the random integer generated in #2 be in the range of (0,5) how can 6 appear? Thanks for the much needed help!

25th Oct 2018, 1:33 AM
Wai Kye Pang
Wai Kye Pang - avatar
4 Réponses
+ 2
There is no difference, that is, the printed result is the same. for x in range (5): means that it will loop from 0 to 4. In the first loop x will be 0, 1, 2, 3 and 4, and value gets random values between 1 and 6. In the second one x will also be 1, 2, 3, 4 and 5 but in between it also gets the random values. If you run the samples like this you will see a difference: #1 import random for x in range(5): print(x) value=random.randint(1,6) print(value) #2 import random for x in range(5): print(x) x=random.randint(1,6) print(x)
25th Oct 2018, 2:07 AM
Paul
Paul - avatar
+ 2
It is for the number of loops indeed.
25th Oct 2018, 5:01 AM
Paul
Paul - avatar
0
Thanks for the reply, so the “for x in range(5):” is actually redundant? Or is it required to tell how many loops the print should run for?
25th Oct 2018, 4:58 AM
Wai Kye Pang
Wai Kye Pang - avatar
0
Alright thanks for the help!
25th Oct 2018, 7:34 AM
Wai Kye Pang
Wai Kye Pang - avatar