Variables and basic Data Types (Strings, Integers, Floats).

In Python, variables and data types are the fundamental building blocks of any program. You can think of a variable as a labeled container that stores information, and the data type as the specific kind of information you are putting inside that container.

Here is a detailed breakdown of how they work.

1. Variables

Unlike some other programming languages, Python has no command for declaring a variable before you use it. A variable is created the moment you first assign a value to it using the equals sign (=).

Python is also “dynamically typed,” meaning you don’t have to tell it what kind of data you are storing; it figures it out automatically.

Creating Variables

Python

# Creating variables
player_name = "Alex"
score = 100
is_alive = True

# Python evaluates the right side first, then stores it in the left side
new_score = score + 50  

Variable Naming Rules

Python has strict rules for what you can name your variables:

  • Must start with a letter or an underscore character (_).
  • Cannot start with a number.
  • Can only contain alpha-numeric characters and underscores (A-z, 0-9, and _).
  • Are case-sensitive (age, Age, and AGE are three different variables).
  • Best Practice: Python developers use snake_case (all lowercase words separated by underscores) for variable names to make them readable (e.g., high_score instead of highscore).

2. Basic Data Types

While Python handles types automatically, you still need to know the four basic, primitive data types to use them correctly.

Strings (str)

Strings are used to store text. You must wrap the text in either single quotes ('...') or double quotes ("...").

Python

greeting = "Hello, World!"
user_id = 'A194'

# Strings can even be numbers, as long as they are in quotes.
# You cannot do math with a string number!
fake_number = "42" 

Integers (int)

Integers are whole numbers, positive or negative, without decimals. They have unlimited length in Python.

Python

age = 25
temperature = -10
population = 8000000000

Floating-Point Numbers (float)

Floats are numbers that contain a decimal point. They are used when you need precise measurements or fractions.

Python

price = 19.99
pi = 3.14159
weight = 0.5

Booleans (bool)

Booleans represent one of two values: True or False. They are heavily used in programming logic and decision-making (like if statements). Note: The ‘T’ and ‘F’ must be capitalized in Python.

Python

is_game_over = False
has_key = True

# Booleans are often the result of a comparison
is_adult = (age >= 18)  # This will evaluate to True if age is 18 or higher

3. Checking and Changing Data Types

Sometimes you need to know what kind of data is stored in a variable, or you need to convert it from one type to another.

The type() Function

You can wrap any variable in the type() function to see exactly what data type it is holding.

Python

x = 10.5
print(type(x))  

# Output:
# <class 'float'>

Typecasting (Converting Data)

You will frequently need to change data from one type to another. For example, if you ask a user for their age using input(), Python always stores that answer as a String (str). If you want to do math with it, you must convert it to an Integer (int).

You do this using the constructor functions: str(), int(), and float().

Python

# 1. Converting String to Integer
string_number = "50"
real_number = int(string_number)
print(real_number * 2)  # Output: 100

# 2. Converting Integer to Float
whole_number = 5
decimal_number = float(whole_number)
print(decimal_number)  # Output: 5.0

# 3. Converting Float to String
price = 9.99
price_tag = "The cost is $" + str(price)
print(price_tag)  # Output: The cost is $9.99

Similar Posts

  • TCP/IP Protocol Explained: Cybersecurity Essentials & Network Fundamentals 

    🌐 TCP/IP: The Internet’s Foundation 🧱 What is TCP/IP? 🌐🤝 TCP/IP (Transmission Control Protocol/Internet Protocol) is the foundational communication protocol suite 📜 that powers the internet and most modern networks. It defines how data is packaged 📦, addressed 📍, transmitted ➡️, routed 🗺️, and received 📥 across networks. Unlike the OSI model, TCP/IP uses a…

  • What are AI Agents? explained with Examples

    🤖 What are AI Agents? AI agents, or Artificial Intelligence agents, are software programs designed to interact 💬 with an environment, perceive 💡 changes, process information ⚙️, and autonomously take actions 🏃‍♀️ to achieve specific, predetermined goals. In simple terms, they’re more sophisticated than basic chatbots or rule-based systems because they can reason, plan, and…

  • The Magic 8-Ball!

    Let’s build The Magic 8-Ball! A Magic 8-Ball is a fun toy where you ask it a “yes or no” question, shake it, and it gives you a random answer about the future. We can build our own digital version using the if, elif, and else statements you just learned. To make the answer a…

  • Dictionary Programs

    Frequency of User Logins Word Frequency Counter python sentence = “apple banana orange apple apple banana grape orange apple” words = sentence.split() # Split into a list of words word_count = {} # Dictionary to store word counts for word in words: if word in word_count: word_count[word] += 1 else: word_count[word] = 1 print(“Word Frequency:”)…

Leave a Reply

Your email address will not be published. Required fields are marked *