Python Forum
Would you prefer two 'if' statements or an 'if' and an 'else' statement?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Would you prefer two 'if' statements or an 'if' and an 'else' statement?
#1
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?
Reply
#2
Hey!

I would prefer and if statement and an elif statement.

With so few options it's not such a big deal though
Reply
#3
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"))
Reply
#4
(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.
Reply
#5
print("Hell Yes!") if answer =='yes' else print("I am not ready to go!")
Reply
#6
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?
Reply
#7
Usually you use IF statement if there is a default value. Otherwise use IF Else. For example
price=10
if number>=5:
  price = 8
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  SyntaxError: multiple statements found while compiling a single statement Kayode_Odeyinka 1 2,935 Mar-12-2020, 05:50 PM
Last Post: micseydel
  SyntaxError: multiple statements found while compiling a single statement DragonG 1 5,394 Nov-26-2018, 05:33 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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