Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Declaring and Assigning Variables

Welcome to your first lesson! We're kicking off your journey into Python with the most fundamental building block of any program: variables. Your goal is to build sophisticated AI and NLP applications, and mastering these basics is the essential first step on that path. Just like an engineer needs to understand materials before building a structure, a programmer needs to understand how to store and manage data.

In this lesson, you will learn how to declare variables and assign them values of different fundamental types: integers, floats, strings, and booleans. This knowledge will form the foundation for everything we build in the subsequent modules.

What Are Variables?

In programming, a variable is a named location in the computer's memory used to store a piece of data. Think of it as a labeled box where you can put information, retrieve it later, or replace it with new information. We give these boxes descriptive names so we can easily remember what's inside.

To get a clear picture of this concept, let's watch a short segment from a tutorial by Programming with Mosh.

Python Variables - Python Tutorial for Beginners with Examples | Mosh

This video provides a concise explanation of what variables are and their purpose in programming.

Watch the beginning of the video, where the instructor defines variables and demonstrates how to declare one to store a number. Focus on the idea of a variable as a "label for a memory location." Please watch from the start.

As you saw, creating a variable is straightforward. In Python, we use the assignment operator, the equals sign (=), to do this.




# The variable is 'student_count', the operator is '=', the value is 1000.
student_count = 1000

Here, Python reserves a piece of memory, stores the number 1000 in it, and attaches the label student_count to that location. We can now use the name student_count anywhere in our program to refer to the value 1000.

Naming Variables: The Rules and Conventions

Choosing good variable names is crucial for writing clean, readable code. While there are a few strict rules, there are also community-agreed conventions that make code easier for you and others to understand.

The main rules are:

  • Variable names must start with a letter or an underscore (_).
  • They cannot start with a number.
  • They can only contain letters, numbers, and underscores (A-z, 0-9, and _).
  • Variable names are case-sensitive (age, Age, and AGE are three different variables).

Beyond these rules, the Python community follows a style guide called PEP 8. Let's watch another clip from the same video, which explains the best practices for naming variables. Adopting these habits early will make your code much more professional.

Python Variables - Python Tutorial for Beginners with Examples | Mosh

This part of the video explains four key conventions for writing clean code, focusing on how to name variables effectively.

Watch the section on variable naming best practices. Pay close attention to the points about using descriptive names, lowercase letters, and underscores to separate words. Please watch from the explanation of best practices.

To summarize, your variable names should be:

  1. Descriptive: user_name is better than un.
  2. Lowercase: Use user_name, not UserName or USER_NAME.
  3. Snake Case: Use underscores to separate words, as in user_name.

Python's Basic Data Types

A variable can hold different types of data. The data type determines what kind of values a variable can have and what operations you can perform on it. For this lesson, we will focus on four fundamental types: integers, strings, floats, and booleans.

The following video from the Bro Code channel provides a very clear, step-by-step introduction to each of these types.

Python variables for beginners ❎

This video walks through the four basic data types with simple, practical examples for each.

We will watch this video in segments as we cover each data type. For now, you can get it ready.

1. Integers (int)

Integers are whole numbers, without any fractional part. They can be positive, negative, or zero. They're perfect for counting things.

  • Examples: 10, -5, 42, 0



# Declaring integer variables
user_age = 28
items_in_cart = 5

Now, let's watch the segment on integers from the Bro Code video.

Python variables for beginners ❎

This segment introduces integer data types.

Watch from the beginning of the data types section, focusing on the examples for integers like age and quantity.

2. Floats (float)

Floats, or floating-point numbers, are numbers that have a decimal point. They are used for values that require fractional precision.

  • Examples: 3.14, -0.001, 99.99



# Declaring float variables
price = 19.99
pi_value = 3.14159
temperature = -5.5

Let's see the video's take on floats.

Python variables for beginners ❎

This segment explains floating-point numbers.

Continue watching from the section on floats, noting the examples like GPA and price.

3. Strings (str)

Strings are used to store text. A string is a sequence of characters enclosed in either single quotes ('...') or double quotes ("...").

  • Examples: "Hello, world!", 'Python', "user_123"



# Declaring string variables
user_name = "Alice"
greeting_message = 'Welcome to the course!'

Now for the video segment on strings.

Python variables for beginners ❎

This segment covers string data types.

Watch the part explaining strings, from this timestamp. Notice that strings can contain numbers and symbols, but they are treated as text.

4. Booleans (bool)

Booleans represent one of two values: True or False. They are fundamental for logic and decision-making in programs. Note that in Python, the first letter must be capitalized.




# Declaring boolean variables
is_logged_in = True
has_premium_access = False

Finally, let's look at the segment on booleans.

Python variables for beginners ❎

This last segment introduces boolean values.

Watch the final section on booleans from this timestamp. Pay close attention to the capitalization and the common mistake of putting True or False in quotes, which would make them strings.

The article "Day 2: Variables, Data Types, and Type Conversion in Python" uses helpful analogies to explain these types. Reading through these can help solidify your understanding.

Master Python Variables, Data Types, and Type Conversion

This article uses simple stories to illustrate the purpose of each data type.

Please read the following subsections within the "Data Types in Python" section: The story for integers, about a bakery counter. The story for floats, about a grocery store scale. The story for strings, about a library catalog. The story for booleans, about an online order status.

Dynamic Typing and Checking Types

One of Python's key features is dynamic typing. This means you don't have to explicitly declare a variable's data type. Python automatically detects the type based on the value you assign to it.

You can check the type of any variable using the built-in type() function.




# Python infers the type from the value
item_count = 10
price = 19.99
user_name = "Alice"
is_logged_in = True




# Let's check their types
print(type(item_count))
print(type(price))
print(type(user_name))
print(type(is_logged_in))

Expected output:

<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>

This image provides a great summary of the variable types we've discussed.

A table summarizing common Python data types, including Integer, Float, String, and Boolean, with a code example for assigning a value of each type to a variable `x`.

Practice Time

Now it's time to write your first piece of Python code. Your task is to create variables to store some information and then print their values. This will help you get comfortable with the concepts we've covered.

Task:

  1. Create a new Python file (e.g., user_profile.py).
  2. Declare a variable named user_name and assign it your name (as a string).
  3. Declare a variable named age and assign it your age (as an integer).
  4. Declare a variable named account_balance and assign it a fictional balance (as a float), for example, 150.75.
  5. Declare a variable named is_active_user and set it to True (as a boolean).
  6. Use the print() function to display the value of each variable.

Starter Code:




# 1. Declare a string variable for the user's name
user_name = "Your Name"




# 2. Declare an integer variable for the user's age
age = 30 # Change this to your age




# 3. Declare a float variable for the account balance
account_balance = 150.75




# 4. Declare a boolean variable for the user's status
is_active_user = True




# 5. Print the value of each variable
print("User Name:", user_name)
print("Age:", age)
print("Account Balance:", account_balance)
print("Is Active:", is_active_user)

Try to write this code from scratch yourself. If you get stuck, you can refer to the starter code above. Running this simple program will be your first successful step in Python programming!

Conclusion

In this foundational lesson, you've learned how to declare variables and work with Python's four basic data types: integers, floats, strings, and booleans. You also learned about Python's dynamic typing and the importance of using clean, descriptive variable names. These concepts are the bedrock upon which all your future Python and AI projects will be built.

In the next lesson, we will make our programs interactive. You'll learn how to use the print() function in more detail to display formatted output and how to use the input() function to get data from a user.

Can't find a good explanation? Sign up and we'll make it for you

Sign up