Home > Blockchain >  Python loops finding random number
Python loops finding random number

Time:10-27

import random
n=random.randint(1, 5)
i=int(input("Guess a number from one to ten"))
if i!=1 and i!=2  and i!=3 and i!=4 and i!=5:
    print("ERROR")
elif i<n:
    print("SMALL")
elif n<i:
    print
("BIG")
else:
    print("You're right!")

Tried to get a num from 1-5 and 3 tries but only got one

CodePudding user response:

The easiest way is a for-loop using the built-in range function.

Make sure to put the input function inside the loop to get repeated user input. The if-elif-else structure needs to be indented into the for loop as well.

The use of _ is just a placeholder for an unneeded value.

import random

n = random.randint(1, 5)

# User has 3 tries to get the right number
for _ in range(3):
    i = int(input("Guess a number from one to ten: "))
    if i not in (1, 2, 3, 4, 5):
        print("ERROR")
    elif i < n:
        print("SMALL")
    elif i > n:
        print("BIG")
    else:
        print("You're right!")
        break

By using break the loop gets terminated, if the user guessed the correct number before his third try.

CodePudding user response:

You can convert this code to following:

import random
n=random.randint(1, 5)
i=int(input("Guess a number from one to ten"))
if i not in ['1','2','3','4','5']:
   print("ERROR")
elif i<n:
   print("SMALL")
elif n<i:
   print("BIG")
else:
   print("You're right!")

CodePudding user response:

You can try the following code:

import random
  n=random.randint(1, 5)
  for _ in range(3):
    i=int(input("Guess a number from one to ten \n"))
    if i > n:
        print("ERROR")
    elif i < n:
        print("SMALL")
    elif n < i:
        print("BIG")
    else:
        print("You're right!")

Or you can try this:

 import random
 n=random.randint(1, 5)
  for _ in range(3):
    print("Random number is: ", n) # for testing...
    i=int(input("Guess a number from one to ten \n"))
    if i not in (1,2,3,4,5):
        print("ERROR")
    elif i < n:
        print("SMALL")
    elif n < i:
        print("BIG")
    else:
        print("You're right!")
  • Related