D
D
daria200220012021-11-26 19:15:09
Python
daria20022001, 2021-11-26 19:15:09

How to make an infinite loop but only when the answer is "yes"?

while True:
 import random
 print("-------Guess my number-------")
 print("You need to guess the number picked by enigmatic computer!")
 print("Number is in range from 1 to 10")
 magic_number = random.randint(1, 10)
 count = 0
 user_number = 0
 while user_number != magic_number:
  user_number = int(input("Your number: "))
  count+=1
  if magic_number > user_number:
   print("The magic number is greater than yours!")
  elif magic_number < user_number:
   print("The magic number is less than yours!")
 print("You Win! You guessed it on the", count,
 "try")
 while True:
   print ("Want to play again?")
   answer = str(input())
   if answer == ("no"):
     print ("Okay, see you later")
     break
   if answer == ("yes"):
     import random
     print("-------Guess my number-------")
     print("You need to guess the number picked by enigmatic computer!")
     print("Number is in range from 1 to 10")
     magic_number = random.randint(1, 10)
     count = 0
     user_number = 0
     while user_number != magic_number:
      user_number = int(input("Your number: "))
      count+=1
      if magic_number > user_number:
       print("The magic number is greater than yours!")
      elif magic_number < user_number:
       print("The magic number is less than yours!")
   print("You Win! You guessed it on the", count,
   "try")

it is necessary that the loop continues only when the answer is "yes"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nvlveu, 2021-11-26
@daria20022001

No need to create a loop within a loop)
Something like this:

import random


count = 0


print("-------Guess my number-------")
print("You need to guess the number picked by enigmatic computer!")
print("Number is in range from 1 to 10")

user_number = None


magic_number = random.randint(1, 10)


while user_number != magic_number:
    magic_number = random.randint(1, 10)

    user_number = int( input("Your number: ") )
    count += 1

    if magic_number > user_number:
        print("The magic number is greater than yours!")
    elif magic_number < user_number:
        print("The magic number is less than yours!")
        print("You Win! You guessed it on the", count, "try")

    print("Want to play again?")
    answer = input()
    if answer == "no":
        print("Okay, see you later")
        break

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question