Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Solving simple bug in Jupyter
#1
I'm a newbie/amateur trying to go back and refresh my basic python after getting too excited and carried away with looking at a few other things. I'm working on a simple python prompt in Jupyter: create a program that asks for an age and then prints out the year they'll be 100 years old.

I'm running into a weird problem that I don't quite get: I'm practicing planning for errors in the code, and if the 'except' clause never runs the code functions properly, i.e returns a value, but if the except clause does run no value is returned.

Here's the code:


def askAge():

age = input("How old are you?\n")

try:

return int(age)

except:

print('You must enter a number!')
askAge(


and the output:

age = askAge()

How old are you?
three
You must enter a number!
How old are you?
3

type(age)

NoneType

Again, running the code with no error successfully returns a value.
Quote
#2
Hi, I'm also a noob but i tried it this way and it works fine. Let me know if this helps.

def askAge():
	age = input("how old are you?")
	try:
		print(int(age))
	except:
		print("You Must enter a number!")
		askAge()
I couldn't tell from the way your post formatted but the last "askAge()" needs to be part of the except
Quote
#3
def ask_for_int(question):
    while True:
        try:
            age = int(input(question + " "))
        except ValueError:
            print("You Must enter a integer!")
        except KeyboardInterrupt:
            # return -1 if someone press CTRL + C
            # it's optional
            return -1
        else:
            # this block is executed, when there was no
            # exception
            break
    # the function reaches this point only
    # if the user has entered a valid integer
    # then the function returns the integer
    return age
I extended your function a little bit, to get rid of the recursive call.
Your recursive call will fail, if the user enters more than 1000 times the wrong number.
In Ipython the recursion limit is set a bit higher. Generalizing a function, is better for code reuse.
Now you can use this function also, to ask how many Dogs or Cats someone has.

The try...except...else is explained here: https://docs.python.org/3.7/tutorial/err...exceptions
The concept behind this piece of code is: Don't ask for permission, ask for forgiveness.
Sometimes it's better to let fail something. If you instead try to convert a string with a valid float into a float, you have many different representations for floats. To handle them all, is like reinventing the wheel. Instead you can use the well implementation of float. This function does know how to interpret the float from the string. If he can't interpret it, he will fail of course. Catching this error, saves you against checking the value in the string by yourself. Isn't it good?

EDIT: Never use a blank except:. This will lead at some point to a very strange behavior, because all errors are suppressed.

You need to recognize some Exceptions.
The most important for Numbers:
  • ValueError: happens, if the function can not convert the string into the value
  • TypeError: happens if you try an operator on types, which are incompatible. '5.0' + 5 will raise a TypeError
Sequences:
  • IndexError: Happens if you try to access an index of a sequence (list, tuple), which does not exist.
Mappings:
  • KeyError: Happens, if you try to access a Key of a mapping (dict e.g.), which does not exist.

If you don't know which Exception could happen, then catch those you know and let the other one fail. Then you can decide if you catch the other exceptions also explicit or you say, that this is not the problem of the function, it should be the problem of the caller. There many talks about Exception handling. It's very important to use them right, if you want to produce reliable code.

@WatcherMagic
Please use code tags if you post code, otherwise you'll lose the indentation and without it, the code is wrong.
Output:
[python]your code[/python]
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Quote
#4
Thank you so much! This is the reason I have to practice. :) I really appreciate how thorough you were (and thank you for the working code!) I'll be coming back here to reference your answer quite a bit I think.

(I'll keep the code tags in mind for next time, thanks!)
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Simple code works in Jupyter but not VS Code Matt_O 2 175 Nov-17-2019, 01:15 AM
Last Post: Matt_O
  Error executing Jupyter command 'notebook': [Errno 'jupyter-notebook' not found] 2 Newtopython123 10 17,027 Apr-25-2019, 07:30 AM
Last Post: banu0395

Forum Jump:


Users browsing this thread: 1 Guest(s)