#๐ Terminating code after wrong user input
52 messages ยท Page 1 of 1 (latest)
@hollow glade
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.
!code
oof it's too long for me to use that format
!paste
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.
What's the question? Your original message was nuked.
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
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.
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
And how is the program terminating? Gracefully? An error?
A screenshot/copy of a buggy session would be good.
Line 52 isn't in a try.
ah! that must be it!
also explains why I'm getting this
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.
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
I'll also try this. thanks
You aren't catching ValueError.
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.
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
Holy shit.
Lol
I only have a vague understanding of how eval() works
I'm not saying I didn't write the rest of the code myself x)
Exhibit One of why getting code from AI is bad.
i guess...
eval invokes the interpreter to run Python code while your program is running. It's pretty rare to need it.
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
r/unexpected korn
That somewhat sounds like a good use for eval. A better solution would be to use an actual parser/expression evaluator for your particular purpose, but that's complicated. Just know that if you're using eval, it should only ever run code that came from the current user. Running code taken from the disk or from the internet is dangerous.
this is mainly what i needed chatpgt for. It goes beyond my understanding
thanks for the heads up
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.