0
\$\begingroup\$

Is there a shorter way to write this?

discounted_price = original_ticket_price - discount_value
if discounted_price < 0:
    discounted_price = 0
\$\endgroup\$
5
  • 1
    \$\begingroup\$ Why would you want a shorter way to write it if you don't mind? Are you golfing or something? \$\endgroup\$ Nov 27, 2018 at 16:03
  • \$\begingroup\$ What's the connection to golfing? I just want to learn it the best, shortest way. Thought there might be a better way to write it. \$\endgroup\$
    – Joey Coder
    Nov 27, 2018 at 16:12
  • \$\begingroup\$ It's just that usually when people ask for the shortest way to write something it's for code golf \$\endgroup\$ Nov 27, 2018 at 16:19
  • 1
    \$\begingroup\$ Ahh, never heard of that. No, I actually just try to learn it the 'right' way. \$\endgroup\$
    – Joey Coder
    Nov 27, 2018 at 16:40
  • \$\begingroup\$ Keep asking question then ;) Next time you post here, copy a more sizeable snippet of code, feedbacks will be way more interesting. \$\endgroup\$ Nov 27, 2018 at 16:50

2 Answers 2

10
\$\begingroup\$

Use the built-in max() function:

discounted_price = max(0, original_ticket_price - discount_value)
\$\endgroup\$
3
\$\begingroup\$

Python has a syntax for ternary since 2.5.

Syntax for it is a if condition else b, where condition is Truthy or Falsy( see Graipher comment).

You can rewrite your code like:

discounted_price = original_ticket_price - discount_value
discounted_price if discounted_price >= 0 else 0

Personnaly I find it harder to read but it is another way to write your code.

EDIT you can find more info on ternary in this SO post

\$\endgroup\$
1
  • 1
    \$\begingroup\$ condition does not have to be a boolean (True or False), a truthy or falsy value is sufficient ([0] and [] also work), as almost always in Python. \$\endgroup\$
    – Graipher
    Nov 27, 2018 at 17:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.