#๐Ÿ”’ Terminating code after wrong user input

52 messages ยท Page 1 of 1 (latest)

scarlet kindleBOT
#

@hollow glade

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

wintry iron
#

!code

scarlet kindleBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

hollow glade
#

oof it's too long for me to use that format

icy ore
#

!paste

scarlet kindleBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

hollow glade
#

ty

#

function at line 31

wintry iron
hollow glade
#

oh!

#

why does my code terminate instead of asking the user to reinsert a valid input when I purposely assign a wrong (float / negative) value to n or k?

#

to test it

#

probably the case for p as well, but I haven't tried

wintry iron
#

First, know that isinstance(k, int) isn't a useful check. k for example is the direct result of a call to int, so it must contain an int. If the input wasn't valid, int would throw and the line under it would never be reached.

hollow glade
#

I suspected as much, I added it as an overkill measure because I was still getting that problem even before when isinstance(k, int) wasn't there

#

but it does seem useless

wintry iron
#

And how is the program terminating? Gracefully? An error?

#

A screenshot/copy of a buggy session would be good.

hollow glade
#

like so:

#

interesting. scenario 1 does work as expected...

wintry iron
#

Line 52 isn't in a try.

hollow glade
#

ah! that must be it!

hollow glade
wintry iron
#

Ya, the error handling is only present in one branch. You would likely benefit from writing some standardized function to take and validate input so you don't need while loops with trys all over the place every time you need to take input.

#

It looks like the only actual validation (besides that int doesn't throw) is that the number is in a range, so maybe write a function with a signature like:

def get_validated_input(prompt: str, min_n: int, max_n: int) -> str:
#

And then this function handles the looping, try, range check, and returns the validated input.

hollow glade
#

I'm not too familiar with try-except blocks yet. Why am I still getting the problem where scenario 5 doesn't work? I thought I made it work the same way as 1-4

#
def get_user_input(scenario):
    print(f"\nPlease provide the parameters for scenario {scenario}:")
    if scenario in range(1, 4):
        while True:
            try:
                n = int(input("Enter the value of n (number of trials): "))
                if not (n >= 1):
                    raise ValueError("Invalid value for n. It must be a positive integer.")
                k = int(input("Enter the value of k (number of successes): "))
                if not (0 <= k <= n):
                    raise ValueError("Invalid value for k. It must be an integer between 0 and n.")
                p = float(input("Enter the value of p (success rate): "))
                if not (0 <= p <= 1):
                    raise ValueError("Invalid value for p. It must be between 0 and 1.")
                break
            except ValueError as e:
                print(f"Invalid input: {e}")
        return k, n, p
    elif scenario in range(4, 7):
        while True:
            try:
                n = int(input("Enter the value of n: "))
                if not (n >= 1):
                    raise ValueError("Invalid value for n. It must be a positive integer.")
                k = int(input("Enter the value of k: "))
                if not (0 <= k <= n):
                    raise ValueError("Invalid value for k. It must be an integer between 0 and n.")                
                p_func = input("Enter the function p(n) or p(k) as a valid Python expression (e.g., 'lambda n: n/10'): ")
                p_func = eval(p_func)
                if not callable(p_func):
                    raise ValueError("Invalid input. Please enter a valid callable function.")
                break
            except (SyntaxError, NameError) as e:
                print(f"Invalid input: {e}")
        return k, n, p_func
    else:
        return None
wintry iron
#

You aren't catching ValueError.

hollow glade
#

ah right

#

nice catch

wintry iron
#

Also, catching SyntaxErrors is pretty sketchy. That has the potential to hide real bugs. If you really want to do that to handle eval failures (why are you using eval?), eval should have its own try that only wraps the call to eval.

#

Wait, actually, no it won't.

#

Still odd, but actual syntax errors will happen before the code runs.

hollow glade
#

i was wondering why I'm still catching those two errors. Since It's the first time i'm trying to work with try-except, I asked chatgpt for a template. It was the AI that added the eval function and error handling

hollow glade
#

I only have a vague understanding of how eval() works

hollow glade
wintry iron
#

Exhibit One of why getting code from AI is bad.

hollow glade
#

i guess...

wintry iron
hollow glade
#

okay, I just needed something that would allow me to create a function via user input

#

it's a binomial distribution and this would be the case where the success rate for the trials varies with either k or n

wintry iron
hollow glade
scarlet kindleBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.