from tkinter import *
import tkinter.messagebox
root = Tk()
tkinter.messagebox.showinfo("This is the window title!","This is some important info!")
answer = tkinter.messagebox.askquestion("What a dumb box!","Do you want this dumb little window to go away?")
if answer =='yes':
print("Hell Yes!")
if answer =='no':
print("I am not ready to go!")
root.mainloop()
When you look at this code, do you prefer it with two 'if' statements or an 'if' and an 'else' statement?
Hey!
I would prefer and if statement and an elif statement.
With so few options it's not such a big deal though
Agreed. If the choices are supposed to be disjoint, then if/elif/else seems preferable.
For something this simple, I might even prefer a dict lookup.
print(d.get(answer, "unknown"))
(Dec-09-2020, 10:46 PM)AnunnakiKungFu Wrote: [ -> ]When you look at this code, do you prefer it with two 'if' statements or an 'if' and an 'else' statement?
They don't produce the same behaviour. Consider what happens if
answer
has the value
"green"
for example.
print("Hell Yes!") if answer =='yes' else print("I am not ready to go!")
You cannot do this:
if answer =='yes':
print("Hell Yes!")
if answer =='no':
print("I am not ready to go!")
with a ternary expression or if/else. You can do it with if/elif.
if answer =='yes':
print("Hell Yes!")
elif answer =='no':
print("I am not ready to go!")
There is a tiny performance boost from using if/elif because the second condition is not tested every time. It also shows that there is some relationship between the two print commands.
A better question is if the code in question is a valid solution. As has been mentioned, the original code doesn't print anything if the answer is not 'yes' or 'no'. Is that the desired outcome?
Usually you use IF statement if there is a default value. Otherwise use IF Else. For example
price=10
if number>=5:
price = 8