2

I have a homework assignment that I am very confused about. I have to write a program allowing users to input the number of eggs that they are buying. The program will then tell them how many boxes (of six eggs) that they can fill and how many eggs are left over.

I need to make sure that if the user enters a non integer value, an error message will be displayed. I can't figure out how to do this and any help would be much appreciated! Is it something to do with while loops or am I completely wrong?

1
  • 2
    What have you got so far? Commented Feb 26, 2014 at 16:57

5 Answers 5

6

Let the user enter anything he wishes, and warn only if it wasn't an integer:

try:
    num = int(input("enter number: "))
except ValueError:
    print("you must enter an integer")

This is the Pythonic way to do it, after all it's "Easier to ask forgiveness than permission".

Sign up to request clarification or add additional context in comments.

2 Comments

You can also wrap this in a while loop to allow the user to re-enter a value until they give one that's valid.
@ÓscarLópez thank you so much! This has sorted everything out and my program now works perfectly. Thanks for your help.
1

Yes this could be a while loop such as

while 1:
  instr = input('Enter an integer')
  try:
    val = int(instr)
    print 'integer entered', val
    break
  except ValueError:
    print instr, ' is not an integer'

1 Comment

@'Janne Kanla' Thanks fixed. That is what happens when typing while thinking of the next line (:-)
0

[EDIT] My comment and code is valid only for python 2.x.

Contrary to other answers you should almost never use 'input()' when asking users, but rather 'raw_input()'.

'input()' evaluates string that it got from user, like it was part of program. This is not only security issue, but is unpredictable and can raise almost any exception (like NameError if python will try to resolve a letter as variable name).

num = None
while num is None:
    try:
        num = int(raw_input("Enter an integer: "))
    except ValueError:
        print 'That was not an integer!'
        affirmations = ('YES', 'Y')
        answer = raw_input("Do you want to continue? (Yes/Y/y):\n")
        if answer.strip().upper() in affirmations:
            continue
        else:
            break
print num

1 Comment

Which is somewhat difficult using Python 3 (see tags) where raw_input doesn't exist....
0
while True:
    try:
       amount=int(input("how many do you want to buy"))
       break
    except ValueError:
       print("Please Enter An Amount")
       continue
    else:
        break

This is a simple way of making the user inputs an integer in python 3. This can also be for making sure the user inputs a string all you need to do for this is just change int(.into str(

Comments

0

I normally put the text outside and wrap it like a function to make it similar to the standard input. Maybe someone likes it:

def int_input(text):
    """Makes sure that that user input is an int"""
    while True:
        try:
            num = int(input(text))
        except ValueError:
            print("You must enter an integer.")
        else:
            return num

user_int = int_input("Enter a number: ")

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.