python if
By: Ashley J
Often, you need to execute some statements only when some condition is
true. Or in some cases you would need to execure different blocks of
code based on a condition. The compound statement if —comprising if,
elif, and else clauses—lets you conditionally execute blocks of
statements. The syntax for the if statement is:
if expression:
statement(s)
elif expression:
statement(s)
elif expression:
statement(s)
...
else:
statement(s)
The elif and else clauses are optional. Note that, unlike some
languages, Python does not have a “switch†statement. Use if, elif, and
else for all conditional processing.
Example python if code:
if x < 0: print('x is negative')
elif x % 2: print('x is positive and odd')
else: print('x is even and non-negative')
When there is just a single simple statement, as here, it can follow the : on the same logical line as the header but when there are multiple statements in a clause (i.e., the clause controls a block of statements), place the statements on separate logical lines indented rightward from the header line. The block terminates when the indentation returns to that of the clause header (or further left from there).
if x < 0:
print('x is negative')
print('this will also be printed if
x<0 is true')
elif x % 2:
print('x is positive and odd')
print('this will also be printed if x%2
is true')
else:
print('x is even and non-negative')
When the if clause’s condition evaluates as true, the statements after the if clause execute, then the entire if statement ends. Otherwise, Python evaluates each elif clause’s condition, in order. The statements after the first elif clause whose condition evaluates as true, if any, execute, and the entire if statement ends. Otherwise, when an else clause exists it is executed, and then the statements after the entire if construct execute.
Archived Comments
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
How to install Jupyter in Ubuntu and make it accessible through Apache Reverse Proxy
Python Basics - Setting up your Python Development Environment
Schwartzian Transform in python
Multidimensional list (array) in python
Remove duplicates from a list in python
Convert number to string in python
Perl's chomp() equivalent for removing trailing newlines from strings in python