Python Forum
Having issues with some 'if' statements
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Having issues with some 'if' statements
#1
The goal here is to have the if statements check the time and date and if those conditions are met I want to subtract $15 off the rental price

def ski_save_click():
    #Setting rental_period as a variable 'days'
    days = rental_period.get()
    price = int(days) * 15 + 10
    save_label = Label(root,
                       text="Saved!"
                       )
    save_label.grid(row=17,
                    column=4
                    )
    save_label.after(3000,
                     save_label.destroy
                     )
    t = datetime.datetime.now().hour
    tmwk = False
    tmwkend = False
    wday = False
    wkend = False
    eligible = False

    if price > 25:
        eligible = True

    if t > 17:
        tmwk = True

    if t > 16:
        tmwkend = True

    if weekday == (["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]):
        wday = True

    else:
        wkend = True

    if eligible and tmwk and wday:
        int(price - 15)

    else:
        int(price)

    if eligible and tmwkend and wkend:
        int(price - 15)

    else:
        int(price)

    renter = open("C:\\Users\\blake\\PycharmProjects\\newb\\out\\ski_renter_"
                  + str(flname.get()) + "_"
                  + str(year) + "-"
                  + str(month) + "-"
                  + str(day), "w"
                  )
    renter.write(paid_dropdown.get())
    renter.write("\n")
    renter.write("=========================================")
    renter.write("\n")
    renter.write("Employee: " + employee_dropdown.get())
    renter.write("\n")
    renter.write("=========================================")
    renter.write("\n")
    renter.write("Renter's Full Name: " + flname.get())
    renter.write("\n")
    renter.write("Rented on: "
                 + str(year) + "-"
                 + str(month) + "-"
                 + str(day) + " "
                 + (weekday[intDay]) + " @ "
                 + str(hour) + ":"
                 + str(minute)

                 )
    renter.write("\n")
    renter.write("Renting for: " + days + " days")
    renter.write("\n")
    renter.write("Return Equipment On: "
                 + will_be_returned_on_year_dropdown.get() + "-"
                 + will_be_returned_on_month_dropdown.get() + "-"
                 + will_be_returned_on_day_dropdown.get()
                 )
    renter.write("\n")

    #Setting 'days' as an integer called 'price'
    #Creating a label instead of using 'print' function so as to print on GUI and not console
    price_label = Label(root,
                        text="Rental Cost $" + str(price),
                        font='Helvetica 12 bold',
                        bg="#CDB580"
                        )
    price_label.grid(row=17,
                     column=5
                     )

    renter.write("Cost $" + str(price))
    renter.write("\n")
    renter.write("Home Address: " + address.get())
    renter.write("\n")
    renter.write("Phone Number: " + phone_number.get())
    renter.write("\n")
    renter.write("Credit Card Type: " + credit_card_type_dropdown.get())
    renter.write("\n")
    renter.write("Credit Card #: " + credit_card_number.get())
    renter.write("\n")
    renter.write("Expiry: " + credit_card_exp.get())
    renter.write("\n")
    renter.write("Ski #: " + ski_number.get())
    renter.write("\n")
    renter.write("Ski Condition Good: " + str(ski_condition.get()))
    renter.write("\n")
    renter.write("Boot #: " + boot_number.get())
    renter.write("\n")
    renter.write("Boot Condition Good: " + str(boot_condition.get()))
    renter.write("\n")
    renter.write("Pole #: " + pole_number.get())
    renter.write("\n")
    renter.write("Pole Condition Good: " + str(pole_condition.get()))
    renter.write("\n")
    renter.write("Destination: " + destination.get())
    renter.write("\n")
    renter.write("Notes: " + additional_notes.get())
    renter.write("\n")
    renter.write("Extended Rental Notes: ")
    renter.write("\n")

    renter.close()


save_button = Button(root,
                     text="Save",
                     command=ski_save_click,
                     fg="blue"
                     )
save_button.grid(row=17,
                 column=3
                 )


root.mainloop()
Reply
#2
You are not having problems with "if" statements. You are having a problem with assignment. What do you expect this to do?
int(price - 15)
How can this change the price? Where is the assignment? Python does not guess what you want. If you want to change price there better be an assignment somewhere. This is the same magic thinking I see where "print" is used in place of "return" in a function. Did you want to do this?
price = price-15 # or price -= 15
The way you implement your logic is odd. Why do this:
eligible = False
if price > 25:
    eligible = True
instead of this?
eligible=price>25
And why do you have variables for wday and wkend? Is there a third choice?
if weekday == (["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]): # This is an error
    wday = True
else:
    wkend = True
How about this
wkend = weekday in ("Saturday", "Sunday")
if eligible and tmwk and not wkend:
    price -= 15
if eligible and tmwkend and wkend:
    price -= 15[\python]
And maybe it would be better to cascade the logic.  I find this clearer.  Not only do I not have to lookup what eligible, wkend, tmwk and tmwkend mean, but I can see that I only discount prices > 25 and that I have different rules for weekday and weekend rentals.  Maybe this is just personal preference.
[python]if price > 25:
    if weekday in ("Saterday", "Sunday"):
        if t > 16:
            price -= 15
    elif t > 17:
        price -= 15
Reply
#3
A few more suggestions.
base_directory = ''

def ski_save_click():
    #Organize code so like things are together.  This calculates price
    t = datetime.datetime.now().hour
    days = rental_period.get()
    price = int(days) * 15 + 10
    if price > 25:
        if weekday in ("Saterday", "Sunday") and  t > 16:
            price -= 15
        elif t > 17:
            price -= 15

    # This draws some labels
    save_label = Label(root, text="Saved!" )
    save_label.grid(row=17, column=4)
    save_label.after(3000, save_label.destroy)
    price_label = Label(root, text=f"Rental Cost ${price}", font='Helvetica 12 bold',
                        bg="#CDB580")
    price_label.grid(row=17, column=5 )
 
    # This writes info to a file
    filename = f'{base_directory}ski_renter_{flname.get()}_{year}_{month}_{day}'
    with open(filename, 'w') as renter:
        renter.writelines([
            f"{paid_dropdown.get()}\n",
            "=========================================\n",
            f"Employee: {employee_dropdown.get()}\n",
            "=========================================\n",
            f"Renter's Full Name: {flname.get()}\n",
            f"Rented on: {year}-{month}-{day} {weekday[intDay]} @ {hour}:{minute}\n",
            f"Renting for: {days} days\n",
            #...
            f"Notes: {additional_notes.get()}\n"
            ])
 
root = Tk()
save_button = Button(root, text="Save", command=ski_save_click, fg="blue" )
save_button.grid(row=17, column=3)
root.mainloop()
You code is easier to read if you don't toss things together like a salad. Functions should only do one thing, but if you do three things, at least group the like things together.

Use context managers when doing things that require cleanup like files that have to be closed. Notice the code above doesn't have a close because the file is automatically closed when you step outside the context of the "with open(..) as renter:". If something caused your program to throw an exception the context manager would still close the file automatically.

After typing your tenth renter.write("\n") why didn't you think "This is stupid! There has to be a better way." Trust those feelings and look to see if there is a better way. f-string formatting is cleaner and more compact than concatenation. writelines lets you write multiple lines at a time.

Another way to write a bunch of strings is use the join method.
line = '\n'.join([
    paid_dropdown.get(),
    "=========================================",
    f"Employee: {employee_dropdown.get()}",
    "=========================================",
    f"Renter's Full Name: {flname.get()}",
    f"Rented on: {year}-{month}-{day} {weekday[intDay]} @ {hour}:{minute}",
    f"Renting for: {days} days",
    #...
    f"Notes: {additional_notes.get()}"
    ])
This makes one string that you can write using renter.write(line). It joins the individual strings using linefeeds.
Reply


Forum Jump:

User Panel Messages

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