In: Computer Science
Code in python
Write a while loop code where it always starts form 2. Then it randomly chooses a number from 1-4. If the number 4 is hit then it will write “TP” if the number 1 is hit then it will write”SL”. It will rerun the program every time the numbers 1 and 5 are hit. The code should also output every single number that is randomly chosen. 2 of the same numbers can't be chosen back to back as well, so the program can't choose 2 and then 2 again.
The output should look like this:
Code Started, at number 2
Chosen number is 3
Chosen Number is 2
Chosen Number is 5
TP
Rerunning program
Code Started, at number 2
Chosen Number 1
Sl
Rerunning program
def run():
print("code started at number 2")
num = int(input("Choosen number is"))
first_num = 0
while(num <=5 and num != first_num):
if num == 4 :
print("TP")
first_num = num
num = int(input("Choosen number is"))
elif num == 1:
print("SL")
first_num = num
print("Rerunning program")
run()
elif num == 5:
first_num = num
print("Rerunning program")
run()
elif (num == 2 or num == 3):
first_num = num
num = int(input("Choosen number is"))
else:
break
run()
Output -
Given Test cases:
this is the given case tested.
In the given output when 5 is hit , it prints TP and in question you gave that TP will print when hit 4. That's why I am not printing TP when hit is 5.
If you want the case, you can add print("TP") under the condition if num == 5:
Next test cases:
if same two numbers are given and given a number other than 1 to 5:
I coded the program if these two conditions happen, program just end. but if we want to rerun the program again, simply it can run as:
def run():
print("code started at number 2")
num = int(input("Choosen number is"))
while(num <=5 and ):
if num == 4 :
print("TP")
num = int(input("Choosen number is"))
elif num == 1:
print("SL")
print("Rerunning program")
run()
elif num == 5:
print("Rerunning program")
run()
elif (num == 2 or num == 3):
num = int(input("Choosen number is"))
else:
break
I think you get my points, if you need more clarification or want to satisfy more conditons please COMMENT, I will update it too.