Correct number or “end” 2

From the code of the previous post for the guessing game:

given = -1
while not(given >0 and given <= 100):
  given = input()
  try:
    given = int(given)
  except ValueError:
    if given == "end":
      break
    else:
      continue

I would proceed to add flags or use the variable given as a flag, e.g.:

theNumber = 50 #or random
given = -1
while given!=theNumber:
  given = -1
  while not(given >0 and given <= 100):
    given = input()
    try:
      given = int(given)
    except ValueError:
      if given == "end":
        break
      else:
        continue
if given="end":
  break
else:
  pass#do the following logic

But then I remembered that loops in python have else clauses so this can be:

theNumber = 50 #or random
while given!=theNumber:
  given = -1
  while not(given >0 and given <= 100):
    given = input()
    try:
      given = int(given)
    except ValueError:
      if given == "end":
        break
      else:
        continue
else:#if there is no break it's a number
  pass#do the following logic
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s