w3resource

Python: Perform an action if a condition is true

Python Basic: Exercise-89 with Solution

Write a Python program to perform an action if a condition is true.

Given a variable name, if the value is 1, display the string "First day of a Month!" and do nothing if the value is not equal.

Sample Solution-1:

Python Code:

n=1
if n == 1:
   print("\nFirst day of a Month!")
print()

Sample Output:

First day of a Month! 

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Sample Solution-2:

Python Code:

n = float(input("Input a number: "))
if (n == 1):
   print("First day of a Month!")
else:
   print()

Sample Output:

Input a number:  1
First day of a Month! 

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Given variables x=30 and y=20, write a Python program to print "30+20=50".
Next: Write a Python program to create a copy of its own source code.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Try-catch-else construct:

try:
  foo() 
except Exception: 
  print("Exception occured")
else:
  print("Exception didnt occur")
finally:
  print("Always gets here")