Conditional Statements
Module 3
What are the three conditional statements?
Open-source software (OSS) is computer software with its source code made available with a license in which the copyright holder provides the rights to study, change, and distribute the software to anyone and for any purpose.
iCodeCamp is a great example of the open source community. All of our source code and materials are accessible for free from practically anywhere to be used for practically any purpose. Github is a platform that stores your code, but also lets other people access it and build off of it.
Today we are going to fork this project: https://github.com/icodecamp/module3_snake
This project uses an external dependency called pygame. Be sure to install pygame with python’s package manager by typing in pip install pygame in either terminal or GitBash.
What is Flow Control?
Conditional statements allow us to run some code only if a condition is met
if statements
if {BOOLEAN EXPRESSION}:
{STATEMENTS}
example:
a = 5
if a == 5:
print("a is 5")
print("this will totally print")
return
if a != 5:
print("a is not five")
print("this will totally not print")
return
if else statements
if {BOOLEAN EXPRESSION}:
{STATEMENTS_1} # executed if condition evaluates to True
else:
{STATEMENTS_2} # executed if condition evaluates to False
example:
a = 5
if a == 5:
print("a is 5")
print("this will totally print")
return
else:
print("a is not five")
print("this will totally not print")
return
chained conditionals
if {BOOLEAN EXPRESSION1}:
{STATEMENTS_A}
elif{BOOLEAN EXPRESSION2}:
{STATEMENTS_B}
else:
{STATEMENTS_C}
example:
a = 5
if a == 1:
print("a is 1")
elif a != 300:
print("a is not equal to 300")
elif a > 5:
print("a is greater than 5")
elif a < 5:
print("a is less than 5")
else:
print("a is 5")
Project Snake
This project is an open source game in which a hungry snake roams around a field in search of sparkling food. Your task is to implement the conditional statements required to make the snake move around.
- If you haven’t done so already, fork the project and clone it to your desktop
- The project depends on an open source package called “pygame.” Use the command
pip install pygamein either GitBash or Terminal to install it. - Open up the file
snake.pyin sublime text. - Notice that the first line of the file is
import pygamethis allows us to use the pygame in our game - Scroll to the bottom of the file. Fill in the missing segments using if, elif, and else statements. The function should either return
move_up,move_down,move_left, ormove_right. - Run the game by typing in
python game.pyin the directory of the project on either GitBash or Terminal
If you are having trouble with the code, you can find the solutions here