#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    1
    Rep Power
    0

    Post Really easy assignment... yet I can't do it.


    I'm new to python, and for my assignment, I have to write a program, that when the wrong number of digits is given (in this case anything but 4-digits), it prints an error message. I have to set the boolean variable set valid to false & then stop.

    It also has to give an error message if there are non-digits in my program. again, set valid to false & then stop.

    does anyone have any help that could get me started?
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,997
    Rep Power
    481
    Code:
    import sys
    import string
    
    class HomeWorkError(ValueError):
        pass
    
    sys.stdout.write('Please enter 4 digits.\n')
    a = sys.stdin.readline().strip()
    valid = set(a).issubset(set(string.digits)) and (4 == len(a))
    if not valid:
        raise HomeWorkError('Digits!  Four characters!')
    You're right, it's easy. Untested. Most of my untested codes fail.

    Note that I've written this in a style that works with python2 or python3.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    15
    Rep Power
    0
    Originally Posted by ika1020
    I'm new to python, and for my assignment, I have to write a program, that when the wrong number of digits is given (in this case anything but 4-digits), it prints an error message. I have to set the boolean variable set valid to false & then stop.

    It also has to give an error message if there are non-digits in my program. again, set valid to false & then stop.

    does anyone have any help that could get me started?
    Not sure if you still need help, or if the above reply helped, but I would do it like this:

    If given a number, and we want to return false if it is not 4 digits, then divide the number by 1000, and if the value is greater than or equal to 1, then we know it at least 4 digits, and if the value is greater than or equal to 10, we know it is more than 4 digits.

    Hope that can help!
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,997
    Rep Power
    481
    Yes,
    int(math.log10(x)) == 3
    is also a test.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo