0

I've been trying to get this piece of code to work:

    last_bits_repeat= "yes"
    while last_bits_repeat== "yes":
        try:
            another_number_repeat= input("do you have another number to add??")
            another_number_repeat= str(another_number_repeat)
        except TypeError as e:
            if not repeat:
                print("You left this empty, please write something!")   
                last_bits_repeat= "yes"
            else:
                print("This is not empty, but invalid")

It doesn't work and I think its because of TypeError.

My question is which exception should I use to validate the string? The user should input either "yes" or "no".

miraculixx
  • 10,034
  • 2
  • 41
  • 60
gbdcal1
  • 21
  • 5

2 Answers2

1

It doesn't work and I think its because of TypeError.

If this is python2 (with from __future__ import print_function), it doesn't work because input doesn't do what you expect it to - namely it doesn't assign the value entered to the another_number_repeat variable Use raw_input instead.

In python3, input is just fine, but it doesn't raise an exception.

My question is which exception should I use to validate the string? (another_number_repeat) if I can at all.

You don't need an exception. Try this:

def get_choice(prompt, choices):
    valid = False
    while not valid:
        answer = raw_input(prompt).strip()
        valid = answer in choices
    return answer

answer = get_choice('do you have another number to add?', ['yes', 'no'])

I've used this code for a integer earlier on so I think it should work with the correct exception.

If you want to use the same code for arbitrary input (numbers, text, choices), a regular expression helps to avoid cumbersome exception checking, and keeps the code slick:

import re
def get_input(prompt, regexp, convert=str):
    valid = False
    while not valid:
        answer = raw_input(prompt).strip()
        valid = re.match(regexp, answer)
    return convert(answer)

get_input('add a number? (yes or no)', r'(yes)|(no)')
get_input('number?', r'^[0-9]*$', int)
miraculixx
  • 10,034
  • 2
  • 41
  • 60
  • 1
    It's python3 - note the `print()` - so `input` is correct – NightShadeQueen Jul 12 '15 at 16:03
  • @NightShadeQueen if this was python3, why use something like `str(another_number_repeat)`? – miraculixx Jul 12 '15 at 16:09
  • Because he or she is confused. On the other hand, he or she *isn't* getting a syntax error, which means the `print()` is likely correct. – NightShadeQueen Jul 12 '15 at 16:11
  • You would not get syntax error for `print("You left this empty, please write something!")` in Python 2 either. Though I am guessing you are correct, the code maybe python 3. – Anand S Kumar Jul 12 '15 at 16:13
  • Its python 3, I used `str(another_number_repeat)` simply because my previous validation (which was validating a integer) didn't work when I did `new_number= int(input("give me a number")` but did when I did `new_number= input("Give me a number")` then `new_number= int(new_number)`. Sorry for the confusion! – gbdcal1 Jul 12 '15 at 16:15
  • @DarrenO'Callaghan: Python3's `input` already gives you a string. Casting a string to a string will never error. – NightShadeQueen Jul 12 '15 at 16:25
0

What I normally do in these Exception "figure out" issues:

  1. Remove the whole try: except: clause
  2. Run the script and produce the invalid data
  3. Watch the error message which will print the Exception name If you expect multiple error type, run the test case for each test case: --blank entry (where user hits ) --User enters an Octal code, etc
  4. Recreate the try: except: ,specifying the Exception name(s) from step #3

Example code to figure out the Exception code :

    last_bits_repeat= "yes"
    while last_bits_repeat== "yes":

            another_number_repeat= input("do you have another number to add??")
            another_number_repeat= str(another_number_repeat)
Fragtzack
  • 373
  • 1
  • 5
  • 13