Requirements:
Linux Distribution
python3
A Shell Interface
My Setup:
Debian GNU/Linux for some examples, ArchLinux for others.
python3
BASH
Normally within a program, when you want to do something if a condition is met, you would use conditional statements. There are a couple conditional statements that python supports. This includes :
- if – “If this statement is true, do this”
- elif – “If the statement previous is false and this statement is true, do this”
- else – “If the previous statements have failed, do this”
The syntax for these are as followed:
if condition :
#do something
elif condition :
#do something else
else:
#do something
Python supports the following conditionals:
- Equals: a == b
- Not Equals: a != b
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to: a >= b
These can be strung together with either “and” and “or” like followed:
if condition and condition:
#do something
elif condition or condition:
#do something
else:
#do something
Lets put this in a working example :
firstNum = 10
secondNum = 30
if firstNum < secondNum and (secondNum % firstNum) == 0 :
print("First number is smaller, and the second number is a multiple of the first.")
elif firstNum < secondNum :
print("First number is smaller")
else:
print("Second number is smaller")
clim@debian:~/Desktop/tests/pytests/conditionals$ python3 conditionals.py
First number is smaller, and the second number is a multiple of the first.
clim@debian:~/Desktop/tests/pytests/conditionals$
When using if statements, there needs to be atleast 1 statement within each branch. You cannot leave an if statement empty. If there is a time where nothing is to be executed within an if statement, you may use the pass keyword as such:
if condition:
pass
else:
pass
The most important thing to remember is the indentation. When using conditional statements, you must indent four spaces (or a tab).
Python project : Checking whether or not a year is a leap year
For this project, we input a year, and calculate whether or not it is a leap year. To determine whether or not a year is a leap year, you must divide the year by 4. If the remainder is 0, and the year is divisible by 100, it is not a leap year. However, if it is divisible by 4 or 400 , it is a leap year.
#input our year
year = int(input("Enter a year:"))
if year%4==0 and year%100!=0 or year%400==0:
print("The year is a leap year!")
else:
print("The year isn't a leap year!")
[clim@archnet:~/Desktop/cspcsite/PythonTutorials/examples/3]$ python3 leap.py
Enter a year:2000
The year is a leap year!
[clim@archnet:~/Desktop/cspcsite/PythonTutorials/examples/3]$ python3 leap.py
Enter a year:1900
The year isn't a leap year!
[clim@archnet:~/Desktop/cspcsite/PythonTutorials/examples/3]$ python3 leap.py
Enter a year:2020
The year is a leap year!
[clim@archnet:~/Desktop/cspcsite/PythonTutorials/examples/3]$