1

python valueerror

#!/usr/bin/env python

# getting user input
height = int(raw_input("height: "))

while (height < 0 or height > 23):
    height = int(raw_input("height: "))

# building the "pyramid"
spaceCount = height
hashCount = 1

for i in range(height):
    assert height != 0
    hashCount += 1
    spaceCount -= 1
    print " " * spaceCount,
    print "#" * hashCount

The code should keep prompting user if input is not an integer. But how?

1
  • Do not copy and paste images here. Copy the code. Commented Feb 24, 2015 at 17:29

2 Answers 2

1

You need to catch the exception.

 height = 24
 while (height < 0 or height > 23):
     try:
        height = int(raw_input("heightL "))
     except ValueError:
        print "Height needs to be an integer. Try again."
Sign up to request clarification or add additional context in comments.

Comments

0

You can read the input in an endless loop, waiting until the user enters a valid integer. For example:

while True:
  try:
    val = int(raw_input("Enter an integer:"))
  except ValueError:
    print "I said an integer"
  else:
    # ValueError was not thrown, which means the user entered a valid integer
    break

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.