简体   繁体   中英

Can someone show me a more efficient/shorter way to write this python random # program?

I am new to python and I am eager to learn a shorter way of writing a random number program I made.

import random

a = random.randint(1,100)

for x in range(5):
  num = int(input("Guess my random number:\n"))
  if(num < a):
    print("Your guess is too small!")
    continue
  elif(num > a):
    print("Your guess is too big!")
    continue
  else:
    print("You got it!")
    break
  if (num == a):
    print("Hooray!")
  else:
    print("You ran out of guesses!")
print("The random number was:", a)
print("Your last guess was:", num)
print("It took you this many tries:", x+1)
import random

a = random.randint(1,100)

for x in range(5):
    num = int(input("Guess my random number:\n"))
    if num < a:
        print("Your guess is too small!")
    elif num > a:
        print("Your guess is too big!")
    else:
        print("You got it!")
        print("Hooray!")
        break
else:
    print("You ran out of guesses!")

print(f"The random number was: {a}")
print(f"Your last guess was: {num}")
print(f"It took you {x+1} tries.")

For loop in python supports else keyword. The code after else is executed, if loop is exited normally (without break ). Your 'Hoorray,' is printed only right after 'You got it.' or not printed at all, so they can be merged.

As @Chris_Rands mentions, the code is overall ok (except for the indentation, which I assume is an error when pasting. The continues are not needed though, and the extra parenthesis either.

import random

a = random.randint(1, 100)

for x in range(5):
    num = int(input("Guess my random number:\n"))
    if num != a:
        print("Your guess is too %s!" % 'small' if num < a else 'big')
    else:
        print("You got it!\nHooray!")
        break
else:
    print("You ran out of guesses!")

print("The random number was:", a)
print("Your last guess was:", num)
print("It took you %s many tries" % x+1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM