Chapter 3: Talking to Python - Variables and Data Types
In the last chapter, you successfully set up your Python environment and even ran your first simple programs. You learned how to make Python display messages like "Hello, World!". That's a great start, but to write more interesting and useful programs, we need a way to store and work with information.
Think about it: most useful tasks involve handling some kind of data. If you're calculating a shopping bill, you need to store prices. If you're writing a game, you need to keep track of the player's score or name. This is where variables and data types come into play.
What are Variables? Like Labeled Jars
Imagine you have a collection of jars in your kitchen. Instead of just throwing things in randomly, you label each jar: "Sugar," "Flour," "Coffee," etc. This way, you know what's inside each jar and can easily find what you need.
In Python, variables are like those labeled jars. They are names you give to specific storage locations in your computer's memory where you can keep pieces of information (data). When you want to use that information, you just use the variable's name.
Assigning Values to Variables
To put something in our "labeled jar" (our variable), we use the assignment operator, which is the equals sign (=).
Here's how it looks in Python:
# Assigning the number 10 to a variable named 'apples'
apples = 10
# Assigning the text "Alice" to a variable named 'student_name'
student_name = "Alice"
# Assigning a price to a variable
price_per_item = 4.99
Let's break down apples = 10:
applesis the variable name.=is the assignment operator.10is the value being assigned to the variable.
Now, whenever you use the name apples in your Python code, Python will know you're referring to the value 10 (until you change it).
You can then use these variables with the print() function we learned about:
This would output:
Naming Your Variables: Rules and Good Practices
Python has a few rules for naming variables:
Allowed Characters: Variable names can contain letters (a-z, A-Z), numbers (0-9), and the underscore character (
_).Starting Character: They must start with a letter or an underscore. They cannot start with a number.
my_variable(Good)_another_var(Good)2variables(Bad - starts with a number)
Case-Sensitivity: Python is case-sensitive. This means
myVariable,MyVariable, andmyvariableare all considered different variables.age = 30Age = 40(This is a different variable thanage)
Reserved Words (Keywords): You cannot use Python's keywords as variable names. Keywords are words that have special meaning in Python (like
print,if,for,while, etc.). We'll learn many of these throughout the book. If you try to use a keyword as a variable name, Python will give you an error. (Don't worry about memorizing them all now; you'll get used to them.)
Good Practices for Naming Variables:
Be Descriptive: Choose names that clearly indicate what the variable represents.
student_nameis much better thansnorx.Use "snake_case": This is the most common convention in Python for variable names that are made up of multiple words. Words are lowercase and separated by underscores (e.g.,
item_price,total_students).Be Consistent: Stick to a consistent naming style throughout your program.
Common Data Types: The Kind of Information
Variables can hold different types of data. Think back to our jars: one might hold a solid (sugar), another a liquid (oil). The type of jar (and how you handle it) might depend on what's inside. Similarly, Python handles different types of data in specific ways.
Here are some of the most common and fundamental data types in Python:
1. Integers (int)
int)Integers are whole numbers, without any decimal points. They can be positive, negative, or zero.
These are all integers.
2. Floating-Point Numbers (float)
float)Floating-point numbers, or "floats," are numbers that do have a decimal point, or are represented in a way that might require one (like using scientific notation). They are used for values that require more precision than whole numbers.
These are all floats. Even 2.0 is a float, while 2 is an integer.
3. Strings (str)
str)Strings are sequences of characters, used to represent text. You create strings by enclosing the text in either single quotes ('...') or double quotes ("..."). It's good practice to be consistent with your choice.
You can also create multi-line strings using triple quotes ("""...""" or '''...'''):
Simple String Operations:
Concatenation (Joining Strings): You can join strings together using the
+operator.Repetition: You can repeat a string by multiplying it with an integer using the operator.
4. Booleans (bool)
bool)Booleans represent truth values. A boolean can only have one of two values: True or False. (Note the capital 'T' and 'F'). Booleans are extremely important for making decisions in your programs, which we'll cover in a later chapter on "control flow."
Finding Out a Variable's Type: type()
type()Sometimes, you might want to know what type of data a variable is holding. Python has a built-in function called type() that can tell you this.
The output <class 'int'> just means that the variable count belongs to the class of integers. Don't worry too much about the word "class" for now; just focus on int, str, float, or bool.
Changing Types: Type Conversion (Casting)
Sometimes you have data in one type, but you need it in another. For example, if you get input from a user, it often comes in as a string, even if they typed numbers. If you want to do math with it, you'll need to convert it to an integer or a float. This process is called type conversion or type casting.
Python provides built-in functions to do this:
int(): Converts a value to an integer.float(): Converts a value to a float.str(): Converts a value to a string.
Be Careful! You can only convert values that make sense. Trying to convert "hello" to an integer using int("hello") will cause an error because "hello" doesn't represent a number.
Putting It All Together: A Mini Program
Let's write a small program that uses variables of different types:
Try typing this into your Python editor, saving it as a .py file, and running it!
Summary and What's Next
In this chapter, you've learned about two fundamental concepts in Python:
Variables: Named containers for storing data.
Data Types: The kind of data a variable can hold (like integers, floats, strings, and booleans).
You also learned how to assign values, name variables wisely, check a variable's type, and even convert between types. These are the absolute basics you'll use in almost every Python program you write.
Now that you know how to store data, the next step is to learn how to perform operations with that data (like addition, subtraction, comparison) and how to make your programs do different things based on different conditions. We'll start exploring that in the next chapter when we look at operators!
Practice Time! Before moving on, try these:
Create a few variables of your own. Assign them different names and values of type integer, float, string, and boolean.
Use the
print()function to display their values.Use the
type()function to check the type of each variable you created.Try converting a string that looks like a number (e.g.,
"50") into an integer and then add another integer to it. Print the result.Try concatenating (joining) two strings together.
Last updated