Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Hara Gopal K
Courses Plus Student 10,027 Pointsrandom choices
I managed to do this the following way, but couldn't understand why i had to put the b-1 (why minus) as the condition for the loop. Can someone please help:
- a is an iterable
- b is an integer
import random
def nchoices (a, b):
lst = []
i = 0
while i <= b-1:
lst.append (random.choice(a))
i += 1
print (lst)
nchoices(['hello', 'prost', 'merci', 'ahoy'], 10)
1 Answer
tobiaskrause
9,160 PointsWell...every run in this loop i will increment by 1 So the first loop-statement is
- 0 <= 10 - 1 = true
- 1 <= 10-1 = true
- 2 <= 10-1 = true
- 3 <=10-1 = true
- 4 <=10-1 = true
- 6<=10-1 = true
- 7<=10-1 = true
- 8<=10-1 = true
- 9<=10-1 = true
- 10<=10-1 = FALSE
if you would do i <= b you would print the solution 11 times not 10 times. Because your first value of i = 0. If you would do i = 1 in the beginning would could go i <= b. Also you have to understand, that while i will increment every time, b will not change. b will always be 10 since you dont assign values in statements.
Hara Gopal K
Courses Plus Student 10,027 PointsHara Gopal K
Courses Plus Student 10,027 PointsThank you very much Tobias :)