1
toss_number = input("How many times do you want to toss the coin?\n")

while True:
    if toss_number.isdigit():
        break
    else:
        toss_number = input("Please input NUMBER of times you want to toss a coin.\n")

These lines of code essentially make sure that toss_number contains a string of numbers. Is there a better/more efficient way of doing this?

jpp
  • 159,742
  • 34
  • 281
  • 339
StrangeRanger
  • 299
  • 1
  • 2
  • 10

1 Answers1

1

An alternative way is to use try / except. This will be more efficient if, more often than not, a number is input.

while True:
    try:
        toss_number = int(input("How many times do you want to toss the coin?\n"))
        break
    except ValueError:
        print('You have not entered a NUMBER.')

When ValueError is raised, a message is printed, but the loop is not broken, so we return to beginning of the while loop and the try section.

jpp
  • 159,742
  • 34
  • 281
  • 339