#๐ 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)
Oh, that's why they're dangerous, any limitations though.
can you go over trhe boolean list return thing
no, they aren't dangerous because of that, it's just that they are so complex so that they can [more easily] cause bugs in the software that reads them and insert more or less any instructions into that computer
you might want to have your function start with an empty collection and then add to that collection after each check of a resource, then return the whole collection when each resource has been checked
fyi its already a huge win under ur belt to make this function like this
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
tbh i forgot why i wanted to return a list of booleans as well
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()

lets go with this kind of function, alright ? 
if we need a boolean list later on we can come back to this
if there's something better we can do it
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
there is some deduplication of code we can do but really, this way works so up to u if u want to improve it or just move on with doing coffee_machine part

Guys, another big problem I have is how to manipulate this to move them into another function and use it.
coffee_machine
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
if compare_resources == TRUE and money == 2.5:
return Here is your espresso. Enjoy!
whats the 2.5
the requirement to make the coffee
to move things out to separate functions you would use a technique called "extraction" where you take a block of code or some logic and move it to it's own function and then call it from the same place where that code was originally used
isnt that data already encoded in our MENU dictionary
go grab it from there instead of hardcoding it
yeah stop hardcoddding srtuff
don't hardcode stuff if you have the data
Should we make a new function also?
even if u have data usually hardcoded stuff is handled via constants
What do you mean via constants? What are the constants?
a sucessful transaction really only needs that 1 if check u sent
constants is a name we give to variables that u shouldnt change value of
in python its a convention more than a feature
oh
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
# constants
NUMBER = 5
# variables
x = 4
# hardcoded value check but its under a constant
if x > NUMBER:
print(x)
when i read magic values there were so many shivers sent down my spine from terraria modding days
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
You can code out Terraria mods; that's crazy.

i can also code down java minecraft mods, i sent this 1 modpack community into a frenzy for months cause when PR i made was accepted there was no bugs but then when players were playing there were a few issues that ye werent fun
4 problems
there is 1 major issue that needs solved first
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
do i make money gobal
no... the numbers...
agk_4760, var_24 were at every fucking corner. sometimes people even used them just out of spite ๐
u also did terraria modding ? lmfao
@wind thorn
If there are sufficient resources to make the drink selected, then the program should prompt the user to insert coins.
u shouldnt be checking money at same time as calling compare_resources
why
cause of instructions
if there is sufficient resources, then prompt user to insert coins
u wouldnt know about their money at time of resource checking 
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?
rather its a major logic flaw
how u gonna check their money if u dont know how much money they have
Use pass instead
Ty, but why pass and not none? Aren't they the same thing?
why do i keep coding out major flaws
pass does nothing, None is an expression.
nope. though there's the keyword pass that can be used as a placeholder.
So "pass" is a placeholder, and "none" is an expression. What do you mean by "expression"?
cause u a beginner, thats what beginners do
they set water on fire
that's my code
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
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.
the arrow pointing to the right
the one pointing to the left is reply
calling None returns a value of None, a value you then don't use, hence the warning
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.
(it complains because you don't do anything with the value, e.g. assigning it somewhere)
delete all the money related stuff, we making a handle_transactions function alright ? 
k
or rather move it out of there instead of deleting it
i find it easier to just delete then rewrite rather than confusing them with moving blocks of code up and down like a mad rollercoaster
due to instructions we already need to change it
we need to check if we got enough resources for coffee we making before we input any money amount
those the instructions 
select all lines u want to comment then ctrl /
ctrl +/
cool
you can select part of the line and it will still work
k
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
use the same shortcut to uncomment
Ooooooh, so that's why passing a statement does not complain because it's complete, while none of the expressions needs something else.
@pale kayak so what should i put inside handle_transactions
we need a variable for money
first of all, call compare_resources
if it returns true then u can go ahead and prompt user for their coins like u were doing
yes we do
handle_transacations needs the user input
not anything else
so it should go inside it
all coffee_machine needs to do is ask user what coffee they want then shove that answer into handle_transactions
that simple
no need for compare_resources since handle_transcations is already calling it

compare_resources i should delete it?
no no no
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

yeah
u should be returning booleans, would make ur life a whole lot easier
i didn't'change it
let me do that
but how do i make the code reachable
cause when i removed the inputs
well dont do that

its still dependent on wat user choose isnt it
we shouldnt be reading the global variable tho
pass whatever the user inputted into it
cool that should work near perfectly
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
i have pdf
its in a pdf so he cant
i see
best he could do ig is ctrl c entire pdf and ctrl v and send that .txt
but that might contain sensitive information
so ๐คท
yeah
- 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. - 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. - 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 - 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.
- 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 - 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. - 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.
ah see, 4b is the kicker
yeah printing
i knew the boolean lists was needed for something
@balmy ocean got any better idea than boolean list for that part ? 
we can do the boolean lists or just print than return true or false
ig could just not early return but um 
issue with that approach is 4c
if u print not enough water then return its not gonna check for coffee or milk
because return ends function execution
than we need a for loop right?
4c makes it so u need to print all u out of
wat for
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.
How about this: make a boolean variable then only return that once at very end
i think @tired sundial had a good suggestion in "A)" of #1415946194533744710 message
because with a boolean list you need to know which element position refers which which resource and do more tests against that list again
Issue is that 4c makes it so u need to print all thats lacking for it
Not just 1st thing u found thats put

Ig just dont early return
depends on how you read it
you could read it as if it should print for each missing resource every time
but you can also read it as it should check each resource and print whatever resource is missing
Ah yes the ambiguity of english
Good old friend
So just return True if everything else is there; if not, then print everything we don't have and refund the money.
Why refund
yeah, most human languages really, that's why code is so much better, when it's correct and error free ๐ ๐
Again we calling compare resources before we ever take user input for any coins
because we didn't make the coffee
There is no concept of money at this stage
yeah
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
@past nest are you watching?
Yup, I know. I was talking about the last steps.
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?
Shouldnt need any loops for this but go ahead and try
If it works it works 
no it's not working
can u send current compare_resources here
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
Hey @wind thorn!
```py
print('Hello, world!')
```
This will result in the following:
print('Hello, world!')```
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 ?
u did think of that we just said it didnt work like several times
but ignoring the reason it doesnt work
lets move forward

try adding the prints to the espresso block up here
where do i put the prints i'm not sure
inside the water check, print water is not enough
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
Hey @wind thorn!
```py
print('Hello, world!')
```
This will result in the following:
print('Hello, world!')```
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
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?
but wat 
shouldn't we remove the return false
indeed, with return there it will stop function execution
but if just simply remove line, how would function know that it needs to return false due to insufficient water/coffee/milk

it wouldn't know
Can I help ๐
yes
,,,,,,,
so how to fix it
if only we could save this information somewhere for function to use it later
and the code?
um
so yeah we use a list
Is that your current code? Can I point some of its problems out or are they already fixed?
current code
Ok
wait so i need a list
What are you discussing currently?
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
Hey @wind thorn!
```py
print('Hello, world!')
```
This will result in the following:
print('Hello, world!')```
improving this
Ok, I see
you have 2 versions of this in your code actually
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.
You can make a loop
I get it
tl;dr need to print all resources that are insufficient
but current code works by returning early
Aha
Then if you go with a loop then you have to store insufficient resources somewhere
A list probably
always good to get a break
k ill be back within 30-60mins will you still be here?
prob
nice how don't you get tried haven't you been here with me for the past 6 hours?
close to 7
have you just been looking at the same code or are you also coding something out
๐ 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
always have to match pace of OP yes
althought sometimes i go too slow but eh
for what?
better than too fast
for wanting to help
of course thank you Dagger
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.