Question: Rewrite a for loop as a while loop. Mr Frodo is having second thoughts about the trip to Mordor. Being both a superstitious little chap
Rewrite a for loop as a while loop.
Mr Frodo is having second thoughts about the trip to Mordor. Being both a superstitious little chap and a Dungeons and Dragons fan, he carries a 20-sided dice wherever he goes. He decides that he will roll the dice a fixed number of times, and if his favourite number comes up, he will go to Mordor, and if not, he will return to the Shire. We will simulate the 20-sided dice through the use of the randint function from the random library (a topic that we will cover properly in Worksheet 13; for now, just accept that from random import randint gives you access to the function, which returns a random integer between the values of the first and second arguments, inclusive).
Given the provided function luck_tester(lucky_number,max_rolls, dice_size), which takes as arguments: (1) a lucky number lucky_number (3 in Mr Frodo's case: the number of trolls his uncle encountered in the Trollshaws); (2) the maximum number of dice rolls max_rolls; and (3) the dice size dice_size(in terms of the number of sides the dice has; 20 in Mr Frodo's case); all can be assumed to be integers. The function should return a string, of value depending on whether the lucky number comes up in the provided number of rolls of the dice or not; the precise strings are provided in the original code.
Note that rewritten function should behave identically to the original, and the only changes you should make are to the for loop and associated variables, to rewrite it as a while loop. Submissions which don't do this will be rejected, so be sure to follow the requirements of the problem carefully!
For loop
def luck_tester(lucky_number, max_rolls, dice_size): # import the `randint` function from random import randint
for _draws in range(1, max_rolls + 1): # simulate the rolling of the dice, and check whether it # is the provided lucky number if randint(1, dice_size) == lucky_number: return 'Off to Mordor!'
return 'Back to the Shire!'
>>> luck_tester(42, 10, 20) "Back to the Shire!"
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
