A variable is used to store data that will be used by the program. This data can be a number, a string, a Boolean, a list or some other data type. Every variable has a name which can consist of letters, numbers, and the underscore character _.
The equal sign = is used to assign a value to a variable. After the initial assignment is made, the value of a variable can be updated to new values as needed.
# These are all valid variable names and assignmentuser_name = "codey"user_id = 100verified = False# A variable's value can be changed after assignmentpoints = 100points = 120
An integer is a number that can be written without a fractional part (no decimal). An integer can be a positive number, a negative number or the number 0 so long as there is no decimal portion.
The number 0 represents an integer value but the same number written as 0.0 would represent a floating point number.
# Example integer numberschairs = 4tables = 1broken_chairs = -2sofas = 0# Non-integer numberslights = 2.5left_overs = 0.0
Python variables can be assigned different types of data. One supported data type is the floating point number. A floating point number is a value that contains a decimal portion. It can be used to represent numbers that have fractional quantities. For example, a = 3/5 can not be represented as an integer, so the variable a is assigned a floating point value of 0.6.
# Floating point numberspi = 3.14159meal_cost = 12.99tip_percent = 0.20
A string is a sequence of characters (letters, numbers, whitespace or punctuation) enclosed by quotation marks. It can be enclosed using either the double quotation mark " or the single quotation mark '.
If a string has to be broken into multiple lines, the backslash character \ can be used to indicate that the string continues on the next line.
user = "User Full Name"game = 'Monopoly'longer = "This string is broken up \over multiple lines"
Booleans are a data type in Python, much like integers, floats, and strings. However, booleans only have two values:
TrueFalseSpecifically, these two values are of the bool type. Since booleans are a data type, creating a variable that holds a boolean value is the same as with other data types.
is_true = Trueis_false = Falseprint(type(is_true))# will output: <class 'bool'>
if StatementThe Python if statement is used to determine the execution of code based on the evaluation of a Boolean expression.
if statement expression evaluates to True, then the indented code following the statement is executed. False then the indented code following the if statement is skipped and the program executes the next line of code which is indented at the same level as the if statement.# if Statementtest_value = 100if test_value > 1:# Expression evaluates to Trueprint("This code is executed!")if test_value > 1000:# Expression evaluates to Falseprint("This code is NOT executed!")print("Program continues at this point.")
elif StatementThe Python elif statement allows for continued checks to be performed after an initial if statement. An elif statement differs from the else statement because another expression is provided to be checked, just as with the initial if statement.
If the expression is True, the indented code following the elif is executed. If the expression evaluates to False, the code can continue to an optional else statement. Multiple elif statements can be used following an initial if to perform a series of checks. Once an elif expression evaluates to True, no further elif statements are executed.
# elif Statementpet_type = "fish"if pet_type == "dog":print("You have a dog.")elif pet_type == "cat":print("You have a cat.")elif pet_type == "fish":# this is performedprint("You have a fish")else:print("Not sure!")
for LoopsPython for loops can be used to iterate over and perform an action one time for each element in a list.
Proper for loop syntax assigns a temporary value, the current item of the list, to a variable on each successive iteration: for <temporary value> in <a list>:
for loop bodies must be indented to avoid an IndentationError.
dog_breeds = ["boxer", "bulldog", "shiba inu"]# Print each breed:for breed in dog_breeds:print(breed)
while LoopsIn Python, a while loop will repeatedly execute a code block as long as a condition evaluates to True.
The condition of a while loop is always checked first before the block of code runs. If the condition is not met initially, then the code block will never run.
# This loop will only run 1 timehungry = Truewhile hungry:print("Time to eat!")hungry = False# This loop will run 5 timesi = 1while i < 6:print(i)i = i + 1
A return keyword is used to return a value from a Python function. The value returned from a function can be assigned to a variable which can then be used in the program.
In the example, the function check_leap_year returns a string which indicates if the passed parameter is a leap year or not.
def check_leap_year(year):if year % 4 == 0:return str(year) + " is a leap year."else:return str(year) + " is not a leap year."year_to_check = 2018returned_value = check_leap_year(year_to_check)print(returned_value) # 2018 is not a leap year.
A comment is a piece of text within a program that is not executed. It can be used to provide additional information to aid in understanding the code.
The # character is used to start a comment and it continues until the end of the line.
# Comment on a single lineuser = "JDoe" # Comment after code