#๐Ÿ”’ New to programming, I hate my code. How do I improve myself? I know I'm doing so many things wrong

1281 messages ยท Page 2 of 2 (latest)

balmy ocean
#

PDFs are built on PS (PostScript) which is really more like a programming language
i have even seen a web server written in postscript that you could send to old networked printers that lacked security and they became a web server

wind thorn
wind thorn
balmy ocean
balmy ocean
pale kayak
#

fyi its already a huge win under ur belt to make this function like this

balmy ocean
#

but i'm not even sure if this is the way i would personally build it, but then again, i don't have all the background information for this thread, because it was way to long to read through it all when i first looked at it

pale kayak
tired sundial
#

wow, this forum is still open ^.^

a few things to note,
A) you don't actually use any of the feedback coming from compare_resources(). perhaps have it print the statments, and return True/False instead.

a general outline (not actual code) โ€“

def compare_resources(...):
   if water < resource[water]:
      print("Not enough water")
      return False
   
   if coffee < resources[coffee]:
      ...
      return False

   print("Resources found.")
   return True

interacting with it like this -

if compare_resources(...) is not True:
   print("Missing Resources for Coffee.")
   break  # return 

if question == "off":
   ...

B) I'd also suggest to make one or a few functions that handle all the money logic, like grabbing the total from the user, subtracting and keeping count.

C) additionally, it may be a nice time to move onto classes.
for example, a class to deal and handle all the resources.
having a builtin report & comparison functions.

a quick example (with dataclass) โ€“

@dataclass
class Resources:
   water: int
   milk: int
   coffee: int

   def report(self):
      return f"""
      ==== Report ====
      water:  {self.water:,}ml
      milk:   {self.milk:,}ml
      coffee: {self.coffee:,}g
      ================
      """.strip("\n")

   def has_enough(self, other) -> bool:
      ...

   def __str__(self):
      return self.report()
res = Resources(15, 7, 12)

print(res)  # res.report()
pale kayak
#

oh hi classes

#

surprise OOP bomb

tired sundial
pale kayak
#

lets go with this kind of function, alright ? pithink

#

if we need a boolean list later on we can come back to this

wind thorn
pale kayak
#
def greater_than_five(x, y):
    return [x > 5, y > 5]

a boolean list return would be for something like this function, since it needs to return 2 booleans but return is a single statement

pale kayak
wind thorn
#

Guys, another big problem I have is how to manipulate this to move them into another function and use it.

pale kayak
#
5. Process coins. 
a. If there are sufficient resources to make the drink selected, then the program should 
prompt the user to insert coins.
b. Remember that quarters = $0.25, dimes = $0.10, nickles = $0.05, pennies = $0.01 
c. Calculate the monetary value of the coins inserted. E.g. 1 quarter, 2 dimes, 1 nickel, 2 
pennies = 0.25 + 0.1 x 2 + 0.05 + 0.01 x 2 = $0.52 
#

so first off

#

lets do 5a

#

we already made compare_resources

#

now is time to use it

wind thorn
#

if compare_resources == TRUE and money == 2.5:
return Here is your espresso. Enjoy!

wind thorn
#

the requirement to make the coffee

balmy ocean
pale kayak
#

go grab it from there instead of hardcoding it

wind thorn
#

yeah stop hardcoddding srtuff

#

don't hardcode stuff if you have the data

#

Should we make a new function also?

pale kayak
#

even if u have data usually hardcoded stuff is handled via constants

wind thorn
#

transaction_successful

#

this right?

wind thorn
pale kayak
pale kayak
#

in python its a convention more than a feature

wind thorn
#

oh

balmy ocean
#

hardcoding stuff like that is called "magic values" (which is something you don't want in your code) and you don't want that, because later on it will be hard to understand what that value is really doing there and also hard to change if the same value is used multiple times through out the code

pale kayak
#
# constants
NUMBER = 5

# variables
x = 4

# hardcoded value check but its under a constant 
if x > NUMBER:
    print(x)
pale kayak
#

its not fun reading decompiled C# code man

#

i think craziest thing i saw was var_1337 or watever the name

#

there was so many

wind thorn
#

You can code out Terraria mods; that's crazy.

pale kayak
wind thorn
pale kayak
#
5. Process coins. 
a. If there are sufficient resources to make the drink selected, then the program should 
prompt the user to insert coins.
b. Remember that quarters = $0.25, dimes = $0.10, nickles = $0.05, pennies = $0.01 
c. Calculate the monetary value of the coins inserted. E.g. 1 quarter, 2 dimes, 1 nickel, 2 
pennies = 0.25 + 0.1 x 2 + 0.05 + 0.01 x 2 = $0.52 
wind thorn
#

do i make money gobal

tired sundial
#

no... the numbers...
agk_4760, var_24 were at every fucking corner. sometimes people even used them just out of spite ๐Ÿ’€

pale kayak
pale kayak
#

u shouldnt be checking money at same time as calling compare_resources

wind thorn
#

why

pale kayak
#

if there is sufficient resources, then prompt user to insert coins

#

u wouldnt know about their money at time of resource checking pithink

wind thorn
#

So it's redundant, right?

#

Why is there a yellow line under "none"? Can't I use "none" as a placeholder for my function until I can come up with something?

pale kayak
#

how u gonna check their money if u dont know how much money they have

wind thorn
wind thorn
umbral pike
#

pass does nothing, None is an expression.

tired sundial
wind thorn
#

So "pass" is a placeholder, and "none" is an expression. What do you mean by "expression"?

pale kayak
#

they set water on fire

wind thorn
#

rather its a major logic flaw
how u gonna check their money if u dont know how much money they have

#

i don't know how to forward

umbral pike
#

An expression is a value, and values shouldn't be on their own. E.g. you could also just write 5 there. It would complain the same way.

pale kayak
#

the one pointing to the left is reply

balmy ocean
wind thorn
#

Um, I need to code something out to check how much money they have using my money variable, but my money variable can't get referenced because of the scope.

umbral pike
pale kayak
wind thorn
#

k

balmy ocean
#

or rather move it out of there instead of deleting it

wind thorn
#

But if I do that, then we need to change the way we account for money.

pale kayak
wind thorn
#

them ๐Ÿ™

#

hhhhhh

pale kayak
#

we need to check if we got enough resources for coffee we making before we input any money amount

#

those the instructions pithink

wind thorn
#

what's the fast way to add # to many lines of code

pale kayak
latent flame
wind thorn
latent flame
#

you can select part of the line and it will still work

wind thorn
#

k

tired sundial
# wind thorn So "pass" is a placeholder, and "none" is an expression. What do you mean by "ex...

Python is generally split to 2 tokens, statments and expressions.

statments are kinda like complete sentences, that perform actions.
expressions are like parts of a sentence. thing that yield a result.

it gets more complicated than this, obviously. it's well defined for each keyword & special characters in the langauge.

https://docs.python.org/3/reference/simple_stmts.html

https://docs.python.org/3/reference/expressions.html#grammar-token-python-grammar-starred_expression

from an old discussion -
#python-discussion message

latent flame
#

use the same shortcut to uncomment

wind thorn
#

@pale kayak so what should i put inside handle_transactions

#

we need a variable for money

pale kayak
#

if it returns true then u can go ahead and prompt user for their coins like u were doing

pale kayak
wind thorn
#

it needs a user_input

#

should i use coffee_machine or my own

pale kayak
#

handle_transacations needs the user input

#

not anything else

#

so it should go inside it

pale kayak
#

that simple

wind thorn
#

So coffee_machine then compare_resources then handle_transactions

pale kayak
wind thorn
#

compare_resources i should delete it?

pale kayak
#

we only need to call compare_resources right before we handle a transacation

#

so we either do it inside the function

#

or in coffee_machine right before we call handle_transcation

#

speaking of compare_resources

#

u back to retuning strings

wind thorn
#

yeah

pale kayak
#

u should be returning booleans, would make ur life a whole lot easier

wind thorn
#

i didn't'change it

#

let me do that

#

but how do i make the code reachable

#

cause when i removed the inputs

pale kayak
#

its still dependent on wat user choose isnt it

#

we shouldnt be reading the global variable tho

#

pass whatever the user inputted into it

wind thorn
pale kayak
#

cool that should work near perfectlypithink

balmy ocean
#

just a quick question
did you ever post the full instructions/requirements for the task somewhere?
because this looks like it's just a small part of it

wind thorn
#

i have pdf

balmy ocean
#

i see

pale kayak
#

best he could do ig is ctrl c entire pdf and ctrl v and send that .txt

#

but that might contain sensitive information

#

so ๐Ÿคท

balmy ocean
#

yeah

wind thorn
#
  1. Prompt user by asking โ€œ
    What would you like? (espresso/latte/cappuccino):โ€‹โ€
    a. Check the userโ€™s input to decide what to do next.
    b. The prompt should show every time action has completed, e.g. once the drink is
    dispensed. The prompt should show again to serve the next customer.
  2. Turn off the Coffee Machine by entering โ€œ
    offโ€‹โ€ to the prompt.
    a. For maintainers of the coffee machine, they can use โ€œoffโ€ as the secret word to turn off
    the machine. Your code should end execution when this happens.
  3. Print report.
    a. When the user enters โ€œreportโ€ to the prompt, a report should be generated that shows
    the current resource values. e.g.
    Water: 100ml
    Milk: 50ml
    Coffee: 76g
    Money: $2.5
  4. Check resources sufficient?
    a. When the user chooses a drink, the program should check if there are enough
    resources to make that drink.
    b. E.g. if Latte requires 200ml water but there is only 100ml left in the machine. It should
    not continue to make the drink but print: โ€œโ€‹Sorry there is not enough water.โ€‹โ€
    c. The same should happen if another resource is depleted, e.g. milk or coffee.
#
  1. Process coins.
    a. If there are sufficient resources to make the drink selected, then the program should
    prompt the user to insert coins.
    b. Remember that quarters = $0.25, dimes = $0.10, nickles = $0.05, pennies = $0.01
    c. Calculate the monetary value of the coins inserted. E.g. 1 quarter, 2 dimes, 1 nickel, 2
    pennies = 0.25 + 0.1 x 2 + 0.05 + 0.01 x 2 = $0.52
  2. Check transaction successful?
    a. Check that the user has inserted enough money to purchase the drink they selected.
    E.g Latte cost $2.50, but they only inserted $0.52 then after counting the coins the
    program should say โ€œโ€‹Sorry that's not enough money. Money refunded.โ€‹โ€.
    b. But if the user has inserted enough money, then the cost of the drink gets added to the
    machine as the profit and this will be reflected the next time โ€œreportโ€ is triggered. E.g.
    Water: 100ml
    Milk: 50ml
    Coffee: 76g
    Money: $2.5
    c. If the user has inserted too much money, the machine should offer change.
    E.g. โ€œHere is $2.45 dollars in change.โ€ The change should be rounded to 2 decimal
    places.
  3. Make Coffee.
    a. If the transaction is successful and there are enough resources to make the drink the
    user selected, then the ingredients to make the drink should be deducted from the
    coffee machine resources.
    E.g. report before purchasing latte:
    Water: 300ml
    Milk: 200ml
    Coffee: 100g
    Money: $0
    Report after purchasing latte:
    Water: 100ml
    Milk: 50ml
    Coffee: 76g
    Money: $2.5
    b. Once all resources have been deducted, tell the user โ€œHere is your latte. Enjoy!โ€. If
    latte was their choice of drink.
wind thorn
#

yeah printing

pale kayak
#

i knew the boolean lists was needed for something

#

@balmy ocean got any better idea than boolean list for that part ? pithink

wind thorn
#

we can do the boolean lists or just print than return true or false

pale kayak
#

ig could just not early return but um pithink

pale kayak
#

if u print not enough water then return its not gonna check for coffee or milk

#

because return ends function execution

wind thorn
#

than we need a for loop right?

pale kayak
#

4c makes it so u need to print all u out of

pale kayak
wind thorn
#

nah it won't work i think its making problems than solving them ( if user_input == "latte":
if resources["water"] < MENU["latte"]["ingredients"]["water"]:
return False)

I was thinking maybe adding a for loop in the middle of this to check the other stuff.

pale kayak
balmy ocean
#

because with a boolean list you need to know which element position refers which which resource and do more tests against that list again

pale kayak
#

Not just 1st thing u found thats put

#

Ig just dont early return

balmy ocean
pale kayak
#

Good old friend

wind thorn
#

So just return True if everything else is there; if not, then print everything we don't have and refund the money.

balmy ocean
pale kayak
#

Again we calling compare resources before we ever take user input for any coins

wind thorn
pale kayak
#

There is no concept of money at this stage

wind thorn
#

yeah

balmy ocean
#

we have not asked the user for any money at this point, that comes after we know if the resources in the machine is enough to make the type of coffee they asked for

wind thorn
#

@past nest are you watching?

wind thorn
#

Um, so how do I do this? Print them all out.

#

Maybe a while loop and a list outside that's trying to collect the infinity stones, and if you have them all, it breaks and prints them all out one by one.

#

@pale kayak what do you think?

pale kayak
#

If it works it works pithink

wind thorn
#

no it's not working

pale kayak
wind thorn
pale kayak
#

as text

wind thorn
#

def compare_resources(user_input):
if user_input == "espresso":
if resources["water"] < MENU["espresso"]["ingredients"]["water"]:
return False
if resources["coffee"] < MENU["espresso"]["ingredients"]["coffee"]:
return False
return True
if user_input == "latte":
if resources["water"] < MENU["latte"]["ingredients"]["water"]:
return False
if resources["coffee"] < MENU["latte"]["ingredients"]["coffee"]:
return False
if resources["milk"] < MENU["latte"]["ingredients"]["milk"]:
return False
return True
if user_input == "cappuccino":
if resources["water"] < MENU["cappuccino"]["ingredients"]["water"]:
return False
if resources["coffee"] < MENU["cappuccino"]["ingredients"]["coffee"]:
return False
if resources["milk"] < MENU["cappuccino"]["ingredients"]["milk"]:
return False
return True

lofty stirrupBOT
#

Hey @wind thorn!

Please edit your message to use a code block

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

This will result in the following:

print('Hello, world!')```
pale kayak
#
def compare_resources(user_input):
    if user_input == "espresso":
       if resources["water"] < MENU["espresso"]["ingredients"]["water"]:
            return False
       if resources["coffee"] < MENU["espresso"]["ingredients"]["coffee"]:
            return False
       return True
#

lets focus on espresso bit for now

#

so we want to print when we out of a resource for all resources

#

the simple solution would be adding print to those resource check if statements

#

right ?

wind thorn
#

yeah

#

but i couldn't think of that

pale kayak
#

but ignoring the reason it doesnt work

#

lets move forward

pale kayak
wind thorn
#

print all of it

#

if it's false? right

wind thorn
pale kayak
wind thorn
#

def compare_resources(user_input):
if user_input == "espresso":
if resources["water"] < MENU["espresso"]["ingredients"]["water"] and print("Sorry there is not enough water."):
return False
if resources["coffee"] < MENU["espresso"]["ingredients"]["coffee"]:
return False
return True

lofty stirrupBOT
#

Hey @wind thorn!

Please edit your message to use a code block

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

This will result in the following:

print('Hello, world!')```
pale kayak
#

thats not inside the water check

#

thats modifying the water check

wind thorn
#

def compare_resources(user_input):
if user_input == "espresso":
if resources["water"] < MENU["espresso"]["ingredients"]["water"]:
print("Sorry there is not enough water.")
return False

pale kayak
#

there we go

#

now do same for coffee

wind thorn
#

def compare_resources(user_input):
if user_input == "espresso":
if resources["water"] < MENU["espresso"]["ingredients"]["water"]:
print("Sorry there is not enough water.")
return False
if resources["coffee"] < MENU["espresso"]["ingredients"]["coffee"]:
print("Sorry there is not enough coffee.")
return False
return True

#

But won't it return false?

pale kayak
wind thorn
#

shouldn't we remove the return false

pale kayak
#

but if just simply remove line, how would function know that it needs to return false due to insufficient water/coffee/milk

wind thorn
#

it wouldn't know

latent flame
#

Can I help ๐Ÿ™‚

wind thorn
#

yes

pale kayak
#

if only we could save this information somewhere for function to use it later

latent flame
wind thorn
pale kayak
latent flame
wind thorn
#

current code

latent flame
#

Ok

wind thorn
latent flame
#

What are you discussing currently?

wind thorn
#

def compare_resources(user_input):
if user_input == "espresso":
if resources["water"] < MENU["espresso"]["ingredients"]["water"]:
print("Sorry there is not enough water.")
return False
if resources["coffee"] < MENU["espresso"]["ingredients"]["coffee"]:
print("Sorry there is not enough coffee.")
return False
return True

lofty stirrupBOT
#

Hey @wind thorn!

Please edit your message to use a code block

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

This will result in the following:

print('Hello, world!')```
wind thorn
#

improving this

latent flame
#

you have 2 versions of this in your code actually

wind thorn
#

we need it to print out b. E.g. if Latte requires 200ml water but there is only 100ml left in the machine. It should
not continue to make the drink but print: โ€œโ€‹Sorry there is not enough water.โ€‹โ€
c. The same should happen if another resource is depleted, e.g. milk or coffee.

latent flame
#

You can make a loop

pale kayak
#

but current code works by returning early

latent flame
#

Aha

#

Then if you go with a loop then you have to store insufficient resources somewhere

#

A list probably

wind thorn
#

my brain has turned off

#

i think i need a break

pale kayak
wind thorn
#

k ill be back within 30-60mins will you still be here?

wind thorn
#

nice how don't you get tried haven't you been here with me for the past 6 hours?

wind thorn
#

have you just been looking at the same code or are you also coding something out

pale kayak
#

im multitasking sorta of kinda

#

but ye its been fun doing this pithink

wind thorn
#

๐Ÿ™‚ that's nice

#

If I were not here, I could easily code it out, or are you just going slow because of me?

#

ty saad

#

ill back be back later

pale kayak
#

althought sometimes i go too slow but eh

latent flame
pale kayak
#

better than too fast

wind thorn
wind thorn
lofty stirrupBOT
#
Python help channel closed using Discord native close action

This help channel has been closed. 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.