Codecademy Logo

Python Fundamentals with AI

Related learning

  • Learn Python programming with AI tools. This course takes you from fundamentals to best practices using Codex CLI for serious development.
    • Includes 4 Courses
    • With Certificate
    • Beginner Friendly.
      7 hours

Variables

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 assignment
user_name = "codey"
user_id = 100
verified = False
# A variable's value can be changed after assignment
points = 100
points = 120

Integers

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 numbers
chairs = 4
tables = 1
broken_chairs = -2
sofas = 0
# Non-integer numbers
lights = 2.5
left_overs = 0.0

Floating Point Numbers

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 numbers
pi = 3.14159
meal_cost = 12.99
tip_percent = 0.20

Strings

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"

Boolean Values

Booleans are a data type in Python, much like integers, floats, and strings. However, booleans only have two values:

  • True
  • False

Specifically, 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 = True
is_false = False
print(type(is_true))
# will output: <class 'bool'>

if Statement

The Python if statement is used to determine the execution of code based on the evaluation of a Boolean expression.

  • If the if statement expression evaluates to True, then the indented code following the statement is executed.
  • If the expression evaluates to 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 Statement
test_value = 100
if test_value > 1:
# Expression evaluates to True
print("This code is executed!")
if test_value > 1000:
# Expression evaluates to False
print("This code is NOT executed!")
print("Program continues at this point.")

elif Statement

The 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 Statement
pet_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 performed
print("You have a fish")
else:
print("Not sure!")

Python for Loops

Python 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)

Python while Loops

In 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 time
hungry = True
while hungry:
print("Time to eat!")
hungry = False
# This loop will run 5 times
i = 1
while i < 6:
print(i)
i = i + 1

Returning Value from Function

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 = 2018
returned_value = check_leap_year(year_to_check)
print(returned_value) # 2018 is not a leap year.

Comments

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 line
user = "JDoe" # Comment after code

Learn more on Codecademy

  • Learn Python programming with AI tools. This course takes you from fundamentals to best practices using Codex CLI for serious development.
    • Includes 4 Courses
    • With Certificate
    • Beginner Friendly.
      7 hours