Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
NEED HELP NEW TO PYTHON!!
#5
(Aug-14-2021, 07:09 AM)perfringo Wrote: It is always good to have names. This makes comprehending much more easier for humans (computer doesn't care :-).

So you first iteration could become (EDIT: rates are changed compared to your example):

>>> meal = 8
>>> tax_rate = 0.15
>>> tip_rate = 0.13
>>> first = meal + (meal * tax_rate) + (meal * tip_rate)
>>> print(first)
10.239999999999998


Simple enough. Second iteration requires that tip would be calculated on amount of meal with tax amount. So it would be:

>>> second = meal + (meal * tax_rate) + ((meal + (meal * tax_rate)) * tip_rate)
>>> print(second)
10.395999999999999
As you can observe that this is quite complicated and we calculated meal * tax_rate twice. Modern Python enables us to use assignment expression to avoid this. We calculate tax amount and give it a name and then use this name in next calcuation. So it can be written:

>>> second = meal + (tax_amount := meal * tax_rate) + ((meal + tax_amount) * tip_rate)
>>> print(second)
10.395999999999999
And... Please use Python code tags!
Key here was that you were thinking of programming, not thinking about the problem. The problem was clearly stated: compute the tip on the meal plus tax. Once you express that in English (or French), the answer is obvious. Don't get caught in the syntax trap. Work it out in your native language first, then write down how to do it so a seven-year-old could figure it out (well, maybe an 8-year-old). If you can't explain it to a small child, you can't program it (small children are much, much smarter than computers). That's one of the secrets of successful programming.

I was working with my intern a couple days ago. I wanted to leave him with a project to do a particular computation. We wrote about 30 lines of comments explaining what the algorithm was and how it had to work. His programming will be trivial now. Because everything is written down in simple English (our shared language).
Reply


Messages In This Thread
NEED HELP NEW TO PYTHON!! - by RZola - Aug-14-2021, 06:01 AM
RE: NEED HELP NEW TO PYTHON!! - by DPaul - Aug-14-2021, 07:02 AM
RE: NEED HELP NEW TO PYTHON!! - by perfringo - Aug-14-2021, 07:09 AM
RE: NEED HELP NEW TO PYTHON!! - by supuflounder - Aug-14-2021, 08:04 PM
RE: NEED HELP NEW TO PYTHON!! - by RZola - Aug-14-2021, 07:53 AM
RE: NEED HELP NEW TO PYTHON!! - by jefsummers - Aug-15-2021, 12:24 PM
RE: NEED HELP NEW TO PYTHON!! - by naughtyCat - Aug-24-2021, 08:20 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020