As discussed in An Introduction to Learning Python Programming, a variable is like a container that stores data values.
Think of it as a label you put on a box where you can store something (like a number or text).
You can change the contents of this box at any time.
Creating Variables:
- Python has no command for declaring a variable.
- A variable is created the moment you first assign a value to it.
x = 5
name = "Alice"
Here, x
is a variable containing the number 5, and name
is a variable containing the string “Alice”.
Numbers
Numbers in Python are used to store numerical values.
They can be integers (whole numbers), floating-point numbers (numbers with a decimal point), or even complex numbers.
Types of Numbers
- Integers: Whole numbers without a decimal point. Example:
5
,-3
. - Floats: Numbers with a decimal point. Example:
3.14
,-0.001
. - Complex: Numbers with a real and imaginary part. Example:
3 + 4j
.
age = 30 # An integer
temperature = -4.5 # A floating-point number
Think of integers and floats as different measuring tools.
Integers are like a ruler without fractions, measuring only in whole units.
Floats are like a digital scale that can measure down to tiny fractions.
Strings
Strings in Python are used to store textual data.
They are a sequence of characters enclosed in quotes (either single, double, or triple quotes).
greeting = "Hello, World!"
description = 'Python is fun.'
You can think of a string as a necklace made up of letters. Each letter is a bead, and when strung together, they form a message.
Booleans
Boolean represents one of two values: True
or False
.
In Python, booleans are often the result of a condition in a comparison or logical operation.
is_adult = True
test_passed = False
Booleans are like the light switches. They can be either on (True
) or off (False
).
Putting It All Together
Here’s a small example that uses these concepts:
# Variables and Data Types
name = "Alice" # String
age = 25 # Integer
temperature = 98.6 # Float
is_student = True # Boolean
# Displaying the values
print(name) # Outputs: Alice
print(age + 5) # Outputs: 30 (integer operation)
print(temperature - 0.6) # Outputs: 98.0 (float operation)
print(not is_student) # Outputs: False (boolean operation)
In this code snippet:
name
,age
,temperature
, andis_student
are variables."Alice"
is a string,25
is an integer,98.6
is a float, andTrue
is a boolean.
Understanding these basic types will help you manipulate data effectively in Python, forming the foundation for more complex programming tasks.