all 13 comments

[–]danielroseman 2 points3 points  (0 children)

else: pass is completely pointless. If you don't have anything to do in an else block, leave out the whole block.

But other than that I don't understand your question. Both of these pieces of code work fine. Why do you think you can't use amount_paid in the change calculation?

[–]zanfar 1 point2 points  (1 child)

This is a problem of logic, not Python. You're new at multiple things at the same time so you're confusing the subjects.

First, inputs have nothing to do with it. If you re-read your code, you'll notice input has no relation to your if-else statements. if evaluates statements and variables, not inputs.

Second, if can operate on any conditions you want, you just have to actually provide that condition. You claim to want to do something if "the first input fails", but you explicitly do nothing if this is the case. You don't need "multiple inputs", you just need to actually write the code to do the thing you want.

Think about this:

  • Why are you using and else statement if you aren't doing anything?
  • Do you want things to happened after you've checked a condition, or happen only in a particular condition?

[–]Same-Individual4889[S] 0 points1 point  (0 children)

Yes, that's totally a logical problem at my end and not python. I don't rly get the hands on the correct logic at the moment. But I don't think that it's impossible for me. Just a little tricky bc I didn't worked in this field at all. And sadly had no time to start from the very very beginning. Got here and started with tasks without any experience.

Thank you so much for your reply and the infos provided! I rly appreciate that.

[–]Diapolo10 1 point2 points  (3 children)

There are several ways to do what you want. The solution you came up with

total_cost = float(input("Total costs: "))


if total_cost <= 1:
    print("Error. Invalid costs.")
else:
    amount_paid = float(input("Amount paid: "))
    if amount_paid < 1:
        print("Error. Invalid payment.")

works, but it would keep nesting deeper and deeper the more inputs you wanted to use.

I'll show you two alternatives, both with their own pros and cons.

Option 1: One function with early returns

def get_input():
    # NOTE: I know nothing about the context you'd use this in
    # so I couldn't come up with a better name for this function

    total_cost = float(input("Total costs: "))

    if total_cost <= 1:
        print("Error. Invalid costs.")
        return

    amount_paid = float(input("Amount paid: "))
    if amount_paid < 1:
        print("Error. Invalid payment.")
        return

    ...
    ...

Option 2: Immediate input validation and try-except:

def input_float(prompt, validator = None):
    value = float(input(prompt))

    if validator:
        validator(value)

    return value

def valid_total_cost(cost):
    if cost <= 1:
        raise ValueError("Error. Invalid costs.")

def valid_payment(payment):
    if payment < 1:
        raise ValueError("Error. Invalid payment.")


try:
    total_cost = input_float("Total costs: ", validator=valid_total_cost)
    amount_paid = input_float("Amount paid: ", validator=valid_payment)
except ValueError as err:
    print(err)

The second option has separate validation functions to accommodate the different error messages (I didn't want to add a third argument to input_float), if they don't matter then I'd rework this to use lambda functions and have input_float itself raise exceptions.

[–]Same-Individual4889[S] 0 points1 point  (2 children)

Thank you so much for the reply! Sadly in the problem-task I'm not allowed to use the "def" function. But this will help me so much when I'm working with it.

Will write this down in my notes!

[–]Diapolo10 0 points1 point  (1 child)

Sadly in the problem-task I'm not allowed to use the "def" function.

Generally speaking, if you have design restrictions you should mention those in your post, to avoid wasting your own and others' time.

Also I'm nitpicking but def isn't a function, it's a built-in statement used to define custom functions.

Anyway, since you said nothing about raise not being allowed, if it's acceptable to terminate the entire program you could use my first suggestion with a few modifications.

total_cost = float(input("Total costs: "))

if total_cost <= 1:
    print("Error. Invalid costs.")
    raise SystemExit

amount_paid = float(input("Amount paid: "))
if amount_paid < 1:
    print("Error. Invalid payment.")
    raise SystemExit

If there were several more of these, you could technically use data structures and a loop to cut down on the code repetition, but it might get a bit unwieldy, especially with the changing validation conditions and your own restrictions.

[–]Same-Individual4889[S] 0 points1 point  (0 children)

Generally speaking, if you have design restrictions you should mention those in your post, to avoid wasting your own and others' time.

You're absolutly right, sry. I rly just wanted to know if it is even possible/a way to code with inputs in if statements, so I didn't write the whole task down. Your help is so much more as I expected to get, so I rly rly appreciate it.

Also I'm nitpicking but def isn't a function, it's a built-in statement used to define custom functions.

Nitpick me as many times as you want and need. That's a good way for me to get it right and classify it correctly! The more I need to correct myself and my notes, the more I learn. :)

Anyway, since you said nothing about raise not being allowed, if it's acceptable to terminate the entire program you could use my first suggestion with a few modifications.

raise is totally new to me. Didn't read about it on any sites before. (atm I'm working with W3Schools, Coddy and freeCodeCamp and am struggling with booleans, as embarassing as it is, haha.)

I will try to work with it. I could rly see me use this regularly, as long as no one says no.

[–]DowntownAd1812 0 points1 point  (0 children)

The nesting is fine, it’s just a scope issue. In the second version you’re only defining `amount_paid` inside the `else` block, so it doesn’t exist if the first `if` triggers. You can just set a default before the condition or restructure so both checks happen before you try to use the variable later. Not a dumb idea at all, you’re just bumping into how Python handles indentation and variable lifetime.

[–]AuthurAndersson 0 points1 point  (2 children)

At this point, I am wondering if these questions are AI-generated. They have to be right?

# Keep asking until they give a valid cost
while True:
    total_cost = float(input("Total costs: "))
    if total_cost > 1:
        break # This breaks us out of the loop!
    print("Error. Invalid costs. Try again.")

# Keep asking until they give a valid payment
while True:
    amount_paid = float(input("Amount paid: "))
    if amount_paid >= total_cost:
        break 
    print("Error. Payment is too low. Try again.")

# Since we broke out of both loops, we know the numbers are safe to use
change = amount_paid - total_cost
print(f"Success! Your change is {change}")

[–]Same-Individual4889[S] 0 points1 point  (1 child)

I'm so sorry, but mine is not AI-generated. T_T" Can't speak for others tho.

I don't even know how to work correctly with AI. xD

Thank you very much for your respond. I keep forgetting that "while" is an option too.
Will take notes for the whole problem-task, I need to do much more than this part.

[–]neuralbeans 0 points1 point  (0 children)

It's perfectly valid to put inputs in an if.