DEV Community

Veera Ganapathi
Veera Ganapathi

Posted on Edited on

Conditional Statements (Python)

Conditional Statements

  • Conditional statements are used to control the flow of execution in a program based on specific conditions.
  • They allow programs to execute different blocks of code depending on whether a condition evaluates to True or False.

If Statement

If statement is used to execute a block of code only when a specified condition evaluates to True.

mark1=90
mark2=89
if mark1 > mark2:
    print("Mark1 is greater")
Enter fullscreen mode Exit fullscreen mode

Short Hand if

Short-hand if is used to write if statements in a single line. It is useful when only one statement needs to be executed.

if mark1 > mark2:print("Mark1 is greater")
Enter fullscreen mode Exit fullscreen mode

If else Statement

If Else statement is used to execute one block of code when the condition is True and another block when the condition is False.

if mark1 > mark2:
    print("Mark1 is greater")
else:
    print("Mark2 is greater")
Enter fullscreen mode Exit fullscreen mode

Elif Statement

The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition".

mark1=90
mark2=90
if mark1 > mark2:
    print("Mark1 is greater")
    print("Hi")
    print("hello")
elif mark2 > mark1:
    print("Mark2 is greater")
else:
    print("Both Are Equal")

Output:
Both Are Equal
Enter fullscreen mode Exit fullscreen mode

Programming Rules:

  • Never say "I don't know", say "Let me try"
  • Known to unknown
  • Don't think about entire output
  • think about very next step
  • Introduce a variable only when it simplifies the solution
  • Micro to macro
  • Dry run before you run
  • Every big problem split three part input, progress, output
  • Logic first and syntax next

Top comments (0)