Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22907

Python Morsels: Python's "if" statements

$
0
0

You can use Python's if, elif, and else blocks to run code only when specific conditions are met.

Conditional code with if statements

If you'd like to run some code only if a certain condition is met, you can use an if statement.

Here we have a program called language.py:

value=input("What programming language are you learning? ")ifvalue=="Python":print("Cool! This program was written in Python.")

In this program, we're prompting a user to enter a value, and then we're printing out a response only if the value that they entered is Python:

$ python language.py
What programming language are you learning? Python
Cool! This program was written in Python.

If they enter anything else, we don't do anything at all:

$ python language.py
What programming language are you learning? JavaScript

We're using an if statement to do this. The if statement has a condition, and if that condition is true, the block of code just after that condition is run.

Using else with if in Python

What if we wanted to …

Read the full article: https://www.pythonmorsels.com/if-statements/


Viewing all articles
Browse latest Browse all 22907

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>