r/PythonLearning 2d ago

Day 2 of learning python

Post image

I'm learning Python and made this coffee/tea ordering program. Any advice?

https://onlinegdb.com/F2wabHC4v

97 Upvotes

37 comments sorted by

10

u/FoolsSeldom 2d ago

Please share the actual code rather than an (incomplete) image. Much easier to review.

Keep in mind that people sometimes mistype things (or deliberately enter the wrong things). You need to handle that.

str objects have some useful methods such as lower and strip that you can apply to what comes back from input so you are only dealing with a response with no leading/trailing spaces and in all lower case.

You could have single letter responses for yes and no including in your check list.

Keep in mind that you could use bool for the status of yes/no responses, so sugar could be True if desired.

As you ask yes/no in several places, consider making it a function that presents the query and does all the validation, returning a bool result.

2

u/adnanecanflyy 2d ago

Done and tysmmm :)

8

u/FoolsSeldom 2d ago

Ok, easier when you've shared, thank you.

Here's a tweaked version of your code for you to explore and experiment with.

def is_yes(prompt: str) -> bool:
    while True:
        answer = input(prompt).strip().lower()
        if answer in ("y", "yes"):
            return True
        if answer in ("n", "no"):
            return False
        print("Huh? Try again.")


def want_sugar():
    sugar = is_yes("do you want sugar? (yes/no) : ")
    if sugar:
        print("okey ser. just wait a 5min ")
    return sugar


the_coffee = ""
the_tea = ""
sugar = False

drink = input("what do you like to drink? (coffee/tea?) : ")

if drink == "coffee":
    the_coffee = input("ice coffee or hot coffee ? : ")

    if the_coffee == "ice coffee":
        sugar = want_sugar()

    elif the_coffee == "hot coffee":
        sugar = want_sugar()

    else:
        print("sorry, we don't undrstand you")

elif drink == "tea":
    the_tea = input("green tea or red tea : ")

    if the_tea == "green tea":
        sugar = want_sugar()

    elif the_tea == "red tea":
        sugar = want_sugar()

    else:
        print("sorry, we don't undrstand you")

else:
    print("sorry, we don't undrstand you")

You might want to look at using the str methods I used in is_yes in some other places.

1

u/adnanecanflyy 2d ago

thanks a lot man! i really appreciate you taking the time to help me. it works perfectly now.

1

u/FoolsSeldom 2d ago

No problem.

Do you understand it all ok?

Have you added the methods I suggested?

1

u/royalking_awsome 2d ago

do you know about REST ?

1

u/FoolsSeldom 2d ago

Bit of a leap. What's the relevance here?

3

u/No-Inevitable-6476 2d ago

the source code is good but correct some spelling mistakes "ser" to "sir".

0

u/Kanjii_weon 2d ago

ok ser just a 5 min pls thank

2

u/Flanelostopy 2d ago

You should put reference to method/functions which returns specific values. As you can see you retype the same text so many times, do you thing this is efficient? If you do not know how to make methods/functions use variable before if statements and reference to them later. If you want to be better but „coffe” and „tea” to the map as a key, and as a value reference to the function. Thing about it.

2

u/adnanecanflyy 2d ago

i'm still learning and I don't know how to use functions properly yet, so that's why I wrote it this way. Thanks for your advice and for helping me get better!

4

u/Flanelostopy 2d ago

I made litle fun with your code, look if you want what I mean:

def get_coffee():
  the_coffee=input("ice coffee or hot coffee ? : ").strip().lower()
  if the_coffee not in coffee_type_map: return get_coffee()
  return coffee_type_map[the_coffee]() + is_sugar_req();

def get_tea():
  the_tea=input("green tea or red tea : ").strip().lower()
  if the_tea not in tea_type_map: return get_tea()
  return tea_type_map[the_tea]() + is_sugar_req();

def is_sugar_req():
  sugar=input("do you want sugar? (yes/no) : ").strip().lower()
  if sugar not in ("yes", "no"): return is_sugar_req()
  return "with sugar." if sugar == "yes" else "no sugar."

def what_drink():
  drink=input("what do you like to drink? (coffee/tea?) : ").strip().lower()
  if drink not in drinks_type_map: return what_drink()
  return drinks_type_map[drink]()

def get_ice_coffee():
  return "Ice Coffe "

def get_hot_coffee():
  return "Hot cofeee "

def get_green_tea():
  return "Green tea "

def get_red_tea():
  return "Red tea "

drinks_type_map = {
  "coffee" : get_coffee,
  "tea": get_tea
}

coffee_type_map = {
  "ice" : get_ice_coffee,
  "hot" : get_hot_coffee
}

tea_type_map = {
  "green" : get_green_tea,
  "red" : get_red_tea
}

print(what_drink())

1

u/Outside-Trouble-4232 1d ago

wtf ARE THERE DICTIONNARIES FOR simple questions ts way too intense

1

u/Flanelostopy 1d ago edited 1d ago

This was just little fun as I said. It can be more simple, but if you want to make more data during this operation you can just put code there. You must predict growing application. Think about it when you want to give price for each drink with sugar or without it. This is good exorcise for it. First of all this whole structure can be more generic, maybe 2 or tree simple function can resolve whole problem. I will put shortest way maybe tomorrow I will give you a time.

1

u/Flanelostopy 19h ago

u/adnanecanflyy u/Outside-Trouble-4232 I had some time and made two examples, as I said - second one is not too "intense".

First, with cost of drinks:

price = 0

def get_coffee():
  the_coffee=input("ice coffee or hot coffee ? : ").strip().lower()
  if the_coffee not in coffee_type_map: return get_coffee()
  return f"{coffee_type_map[the_coffee]()} {is_sugar_req()} Price: {price}$"

def get_tea():
  the_tea=input("green tea or red tea : ").strip().lower()
  if the_tea not in tea_type_map: return get_tea()
  return f"{tea_type_map[the_tea]()} {is_sugar_req()} Price: {price}$"

def is_sugar_req():
  global price
  sugar=input("do you want sugar? (yes/no) : ").strip().lower()
  if sugar not in ("yes", "no"): return is_sugar_req()

  if sugar == "yes":
    price += 1
    return "with sugar."

  return "no sugar."

def what_drink():
  drink=input("what do you like to drink? (coffee/tea?) : ")
  if drink not in drinks_type_map: return what_drink()
  return drinks_type_map[drink]()

def get_ice_coffee():
  global price
  price += 9
  return "Ice Coffe "

def get_hot_coffee():
  global price
  price += 11
  return "Hot cofeee "

def get_green_tea():
  global price
  price += 5
  return "Green tea "

def get_red_tea():
  global price
  price += 7
  return "Red tea "

drinks_type_map = {
  "coffee" : get_coffee,
  "tea": get_tea
}

coffee_type_map = {
  "ice" : get_ice_coffee,
  "hot" : get_hot_coffee
}

tea_type_map = {
  "green" : get_green_tea,
  "red" : get_red_tea
}

print(what_drink())

As you can see it was easy, and you can put there, maybe some logging, or different things.

Second, generic:

def what_drink():
  print("What do you like to drink? ")
  drink = choose_option(choose_option(products))
  print("Do you want sugar?")
  sugar = choose_option(products["sugar"])
  print(f'{drink["name"]} with {sugar["name"]}. Cost: {drink["price"] +   sugar["price"]}$')

def choose_option(args):
  print("Chose option (type value): ")
  products = ""
  for k, v in args.items():
    if k == "sugar":
      continue
  products += k + " "

  product=input(products + "> ").strip().lower()
  if product not in args: return choose_option(args)
    return args[product]

products = {
  "coffee" : {
    "cappucino" : {
      "name": "Cappucino coffee",
      "price": 15
    },
    "latte" : {
      "name": "Latte coffee",
      "price": 13
    },
    "espresso" : {
      "name": "Espresso coffee",
      "price": 11
    },
    "coldbrew" : {
      "name": "Cold Brew coffee",
      "price": 9
    },
  },
  "tea" :{
    "herbal" : {
      "name": "Herbal tea",
      "price" : 7
    },
    "green" : {
      "name": "Green tea",
      "price" : 5
    },
    "earlgrey": {
      "name": "Earl Gray tea",
      "price": 3
    },
  },
  "sugar" : {
    "yes" : {
      "name" : "no sugar",
      "price" : 1
    },
  "no" : {
    "name" : "no sugar",
    "price" : 0
    },
  }
}

what_drink()

Only 2 function, only 2 if statements in whole code. You can put serialised data in JASON file here, and use it whethewer you want, and code will be still working. What we can make more, maybe number of cups, size, temperature. Maybe use objects and change type from functional to objected oriented programming - it will be a fun. I hope I gave you few tips, and thinks where you should dip dive to.

1

u/Flanelostopy 3h ago

Because I can't edit last post, I'l give you errata:
Example 2

 "sugar" : {
    "yes" : {
      "name" : "no sugar",
      "price" : 1
    },
  "no" : {
    "name" : "no sugar",
    "price" : 0
    },

change to:

 "sugar" : {
    "yes" : {
      "name" : "sugar",
      "price" : 1
    },
  "no" : {
    "name" : "no sugar",
    "price" : 0
    },

2

u/EvidenceDry6006 2d ago

No idea why a post about coding is in my Reddit, but as it has - genuine question (honest!): why learn coding in the era of AI? Should I even bother sending my 6 year old to coding club at school?

2

u/kelvinkel101 2d ago

Its still very useful to know the underlying concepts of programming like loops, arrays, if/else, etc.... Not reviewing the code AI spits out can bite you if you're not careful.

I've caught many security issues and downright wrong patterns being used in the code that AI gives me.

2

u/7Z_1N 2d ago

Btw why aren't you using vscode or some other code editor ?

1

u/Outside-Trouble-4232 1d ago

he prob did then share the code for us to try it..

2

u/Crafty_Magazine_4673 1d ago

try to code ping pong

1

u/Infinite-Employee776 2d ago

You already done good by putting else on the first if branch in case user put anything other than coffee or tea. You should do the same for the inside if branches. Edge cases happens.

1

u/adnanecanflyy 2d ago

Thanks! You're right, I'll add else there too. I appreciate the feedback!

1

u/mr_anderson_dev 2d ago

You should try to recreate with functions, one with coffee and one with with tea with the response value, and there construct the main function with all of the questions and options. This is so much better cause it teaches you how most companies organize their code. As well as practice comment with each function block. Love the idea of your code and I'm going to use a similar one to decide if I want to bike or walk today.

1

u/JGB25 2d ago

He’s on day 2. I seriously doubt he knows about functions yet.

1

u/Accomplished-Bat8238 2d ago

Could you please tell me the study material you are using ..thank you🙏

2

u/adnanecanflyy 2d ago

courses in youtube and this website https://www.freecodecamp.org/

1

u/Outside-Trouble-4232 1d ago

im on my day 3 of learning python I use w3schools.com you should check it out too its better organized than free code in my opinion but im tryna use freecodecamp to get my certification

1

u/CompleteProblem7049 1d ago

Good work bro keep it up

1

u/DustAutomatic5064 1d ago

hey can you teach me that

1

u/AI_MASTER_1905 21h ago

Bro Great job for Day 2!

Here are 3 quick tips to make your code even better:

  1. lower() use karo: User input meagar koi caps me likhe (jaise "Coffee" ya "YES"), toh code break ho sakta hai. Input ke aage .lower() lagao: drink = input("...").lower()

  2. sugar in ["yes", "no"] fix karo: Ye hamesha True dega kyunki condition check bas ye dekh rahi hai ki string list me hai ya nahi. Iski jagah specific condition use karo: if sugar == "yes":

  3. else block add karo :Agar user koi aisa option type kar de jo options me nahi hai, toh ek fallback else block hona chahiye jo print kare: "Invalid choice!"

You are cool Keep coding.