How do I make the code reapte such that users can guess the answer to the random number only three times, how do I make it stop at a point? Thanks. This is a random number guessing game, I'm a total beginner to python and can't find anything that helps me on the web [or it may be that I'm just dumb]
import random
print['what difficulty do you want? Type Easy or Hard accordingly']
difficulty = input['']
if difficulty == 'Hard':
print['your going to have a tough time']
hardrandomnum = random.randint[1,100]
def main[]:
print['try to guess the number']
playerguess = float [input[""]]
if playerguess > hardrandomnum:
print ["guess a lower number"]
if playerguess < hardrandomnum:
print["guess a higher number"]
if playerguess == hardrandomnum:
print["correct"]
restart = 4
if restart >4:
main[]
if restart == 4:
exit[]
main[]
doctorlove
18.4k2 gold badges47 silver badges60 bronze badges
asked Oct 12, 2021 at 12:54
2
Loops and breaks.
For example if you want to run the code three times wrap it in a for loop:
for i in range[3]:
[here goes your code]
or you could make a while loop and break:
while[True]:
[here goes your code]
if condition is met:
break
answered Oct 12, 2021 at 12:57
haxor789haxor789
5624 silver badges17 bronze badges
1
you could use a for loop:
for i in range[3]:
#your code
the number in range[] indicates how many times you visit the code inside there are also while loops but for your usecase a for loop should do the trick
answered Oct 12, 2021 at 13:00
R98R98
1091 silver badge9 bronze badges
1
Use a looping structure as below answer mentions.
Example with while
loop
def repeat_user_input[num_tries=3]:
tries = 0
result = []
while tries < num_tries:
tries += 1
result.append[float[input[]]]
return result
print[repeat_user_input[]]
Example with a list comprehension and range
def repeat_user_input[num_tries=3]:
return [float[input[]] for _ in range[num_tries]]
answered Oct 12, 2021 at 13:04
rv.kvetchrv.kvetch
7,2943 gold badges14 silver badges34 bronze badges
I believe you are looking for something like the below?
import random
import sys
guess_counter = 0
random_number = 0
easy_hard = input['Chose your difficulty lever by typing "easy" or "hard" ']
if easy_hard.lower[] == 'easy':
print['Your in luck! You are about to have fun']
random_number = random.randint[1,10]
elif easy_hard.lower[] == 'hard':
print['Woow this game is not going to be easy']
random_number = random.randint[1,100]
else:
print['You need to type either easy or hard and nothing else']
sys.exit[]
while guess_counter < 4:
user_number = int[input['Guess: ']]
if user_number < random_number:
print['Try higher number']
guess_counter += 1
elif user_number > random_number:
print['Trye lower number']
guess_counter += 1
else:
print['Congrats! You Won']
break
else:
print['Ooops! Looks like you luck run out.']
answered Oct 12, 2021 at 13:27
pyzerpyzer
1227 bronze badges