There is a problem on my code, can you fix it please?

I need help fixing this code:

end = None
if __name__ == "__main__":
    while True:
        i = input("NUMBER [=-")
        try:
            if i == int(i):
                        print(f"Your number is {i}")
            else:
                continue
                print("End initalized!")
                end
                    
        except (ValueError, e):
            raise e

When i place a letter on my prompt, i get this error:


NUMBER [=-y
Traceback (most recent call last):
  File "Documents/ender.py", line 6, in <module>
    if i == int(i):
ValueError: invalid literal for int() with base 10: 'y'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "Documents/ender.py", line 13, in <module>
    except (ValueError, e):
NameError: name 'e' is not defined

Anyways that was a test of making the snippet ‘end’

I think you meant this:

except ValueError as e:
1 Like

It showed up this:


NUMBER [=-y
Traceback (most recent call last):
  File "Documents/ender.py", line 14, in <module>
    raise e
  File "Documents/ender.py", line 6, in <module>
    if i == int(i):
ValueError: invalid literal for int() with base 10: 'y'

If you type “y” in your prompt it is going to fail as int(i) will be int(“y”), which raises this exception.

That seems to be normal output when you just re-raise the exception. What are you trying to achieve?

Note that lines 9 and 10 (following the continue) never get executed.

1 Like

I am trying to achieve this by printing the number that the user asks to print.

if a user prints a valid number, that should be accomplished in line 7. But an invalid number will stop the loop and thereby the program. If you don’t want that, don’t reraise the exception.

Question: Do we have to include pass?

you could use pass instead of reraising the exception, if you don’t need to tell the user that the input is wrong

Ok! Thanks for giving an idea!

It does not print out ”Your number is <insert number here>” and ”End initialised!”
EDIT:
Can you fix it?

RE BY ‘Aaron1233378’ from ‘Albert Visser’:
Albert Visser:

you could use pass instead of raising the exception, if you don’t need to tell the user that the input is wrong

Aaron1233378:

It’s not printing out the things i need to print. Please fix it for me.

input returns a string and int returns a number, and asking whether a string is equal to a number will always return False. Why are you doing that anyway? If you want to know whether the string is numeric, int itself will tell you that - if int raises ValueError then the string isn’t numeric, otherwise it is.

Don’t worry, it is fixed by:

Mr. Copilot :smiley:

Always check what Copilot tells you. It and other AI systems aren’t truly intelligent; they can give you answers that are convincing, but wrong.

1 Like

Please read:

THIS IS FIXED!
NEXT PROBLEM ON THE print_() FUNCTION:

def print_(*args, **kwargs):
    """The new-style print function from py3k."""
    fp = kwargs.pop("file", sys.stdout)
    if fp is None:
        return
    def write(data):
        if not isinstance(data, basestring):
            data = str(data)
        fp.write(data)
    want_unicode = False
    sep = kwargs.pop("sep", None)
    if sep is not None:
        if isinstance(sep, unicode):
            want_unicode = True
        elif not isinstance(sep, str):
            raise TypeError("sep must be None or a string")
    end = kwargs.pop("end", None)
    if end is not None:
        if isinstance(end, unicode):
            want_unicode = True
        elif not isinstance(end, str):
            raise TypeError("end must be None or a string")
    if kwargs:
        raise TypeError("invalid keyword arguments to print()")
    if not want_unicode:
        for arg in args:
            if isinstance(arg, unicode):
                want_unicode = True
                break
    if want_unicode:
        newline = u"\n"
        space = u" "
    else:
        newline = "\n"
        space = " "
    if sep is None:
        sep = space
    if end is None:
        end = newline
    for i, arg in enumerate(args):
        if i:
            write(sep)
        write(arg)
    write(end)

I downloaded the ZIP file from GitHub Gist then this error happened:


>>> a = None;print_(a)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/var/mobile/Containers/Data/Application/01715243-B8B7-4B4C-AC1F-2B7565340CB0/Documents/pypy-print.py", line 3, in print_
    fp = kwargs.pop("file", sys.stdout)
NameError: name 'sys' is not defined

I need EXTRA help on this because this may be tricky for you :slight_smile: :open_mouth:
Edit:
Good luck :slight_smile:

By Aaron

Yeah @MRAB, we know that but he is correct on me.
Even tho AI gets wrong, i can make it easier for it. Thanks for the reply anyways!

By @Aaron1233378

The error is pretty explicit:

NameError: name 'sys' is not defined

Line 3 you have:

kwargs.pop("file", sys.stdout)

sys.stdout is used as a default value here, but sys is not defined. This is a stdlib module you need to import, so just add import sys at the top of your script.

2 Likes

This is stuff from nine years ago. Why not just use the built in print function?

2 Likes