Understanding Python Variables, Data Types, and How to Convert Them

Welcome to the first class of Python programming. If you are a beginner and want to strengthen your foundational knowledge in Python, then understanding variables and data types is very important. Think of them as the simple components you will use to create everything from basic programs to more complicated applications.

In this post, we will take a deep look at what variables are, how they work in Python, explore the fundamental basic data types in Python, and learn about type conversion in Python. We’ll use simple examples to make everything clear and easy to follow.

Let’s get started!

Starting simple: Your first python program

Before we discuss variables and data types, let’s ensure we understand the environment in which our Python code runs.

The first step when writing a Python program is creating a file. For example, you might create a file called hello_world.py. The .py at the end is really important; it’s the standard file extension that tells your computer (and your code editor) that this is a Python program.

When you use a code editor or run this file directly, the Python interpreter processes the code. The interpreter is like a translator that reads your program line by line, understands what each word and symbol means according to Python’s rules, and executes the instructions you have written.

Let’s consider a very simple program:

print("Hello python world")

If you add this one line to your hello_world.py file and run it, the Python interpreter will see the print() function and the text inside the parentheses (“Hello python world”). The purpose of the print() function is to show whatever you give it on the screen (your console or terminal).

Simple, right? Now, let’s make it a bit more dynamic using a variable.

Python variables: Naming and storing information

In programming, we need to store pieces of information so we can use or change them later. This is where python variables come in.Let’s modify our hello_world.py file. We will add a line at the beginning:

message = "Hello python world"
print(message)

But what happened here? We introduced the word message. In this context, message is a variable. So, 

What is a variable in python?

A variable in python means creating a name that is connected to a value. In the example above, we created a variable named message and connected it to the text value “Hello python world”. From that point on, whenever we use the name message, Python knows we are referring to the value “Hello python world”.

Think of a variable as a label or a box where you can store different types of information. You can change the information in the box, but the label (the variable name) stays the same.

Naming your variables: The rules of the road

While you are free to choose names for your python variables, there are some important rules and best practices you should follow to keep your code clean, readable, and error-free:

  1. Allowed characters: A variable name can contain letters (a-z, A-Z), numbers (0-9), and underscores (_).
  2. Starting character: A variable name cannot start with a number. It must start with a letter or an underscore.
  3. Case sensitivity: Python variable names are case-sensitive. This means message, Message, and MESSAGE are considered three entirely different variables by the interpreter.
  4. No spaces: Avoid using spaces in variable names. If you need to use multiple words, use underscores (_) to separate them (e.g., user_name, total_count). This is a common convention called “snake_case”.
  5. Avoid keywords: Do not use Python keywords as variable names. Examples of keywords include print, if, else, while, for, import, etc. Using a keyword will cause a SyntaxError.
  6. Be descriptive: Choose variable names that are descriptive and meaningful. user_age is much clearer than ua or x. This makes your code easier for others (and your future self!) to understand.
  7. Keep it concise (but Clear): While descriptive is good, try to keep names reasonably short. Find a balance between clarity and brevity.
  8. Avoid special characters: Do not use symbols like !, @, #, $, %, ^, &, *, (, ), -, +, =, [, ], {, }, |, \, ;, :, ‘, “, <, >, ,, ., ?, /, ~, “` except for the underscore (_).
  9. Avoid built-in names: It’s best practice to avoid using names that are already used for built-in functions or modules in Python (like list, dict, str, int, sum, max, min). While you can technically overwrite them, it can lead to confusion and unexpected behavior later in your code. Do not worry too much about memorizing all built-ins now; you will learn them as you go.

Let’s see some examples of valid and invalid variable names based on these rules:

Valid Examples:

# Valid variable names:
age = 25
name = "asad"
print(name)
print(age)

# More valid examples
user123 = "Alice"
_private_variable = "This starts with an underscore"
user_name = "Bob"
total_sales_amount = 1500.75

print(user123)
print(_private_variable)
print(user_name, total_sales_amount)

Invalid Examples:

# Invalid variable name (starts with a number)
# 123user = "asad"
# print(123user) # This would raise a SyntaxError

# Invalid variable name (using a Python keyword)
# if = "conditional keyword"
# print(if) # This would raise a SyntaxError

# Example showing case sensitivity (important!)
Name = "Alice"
name = "Bob" # This is a *different* variable
print(Name) # Output: Alice
print(name) # Output: Bob

# If you try to use 'name' after only defining 'Name':
# print(non_existent_name) # This would raise a NameError because 'non_existent_name' was never defined

As you can see, paying attention to these rules helps prevent errors and makes your code more maintainable.

Python data types

Now that we know how to store values using variables, the next natural question is: what is data type in python? In Python, every value has a specific type. This type tells Python how the value is stored in memory and what kinds of operations can be performed on it. Understanding python data types is crucial because it dictates how you can interact with the data your variables hold.

But the question, How many data types in python are there? Python has a rich set of built in data types in python, ranging from simple ones like numbers and text to more complex structures like lists and dictionaries. 

For beginners, it’s most important to start with the basic data types in python, which are also considered the python core data types.

Let’s take a look at the most common ones:

  1. Integers (int): These represent whole numbers (positive, negative, or zero) without any decimal point. Examples: 1, 100, -5, 0, 2023.
  2. Floating-point numbers (float): These represent numbers that have a decimal point. They are used for representing real numbers. Examples: 1.0, 3.14, -0.01, 2.71828.
  3. Strings (str): These represent sequences of characters, essentially text. They are enclosed in either single quotes (‘…’) or double quotes (“…”). Examples: “Hello”, ‘Python’, “Data Science”, “123”.
  4. Booleans (bool): These represent truth values. There are only two possible boolean values: True and False. They are typically the result of comparison operations.

Let’s look at examples for each of these data types and expand on them.

Integers (int)

Integers are used to store whole numbers. They are part of the python numeric data types.

age = 25
year = 2023
negative_number = -10
zero_value = 0
print(age, year, negative_number, zero_value) # Output: 25 2023 -10 0

You can perform standard arithmetic operations with integers:

a = 10
b = 5

sum_result = a + b       # Addition
difference = a - b       # Subtraction
product = a * b      # Multiplication
quotient = a / b     # Division (Result is always a float)
floor_quotient = a // b # Floor Division (Result is an integer, discarding remainder)

print("Sum:", sum_result)         # Output: Sum: 15
print("Difference:", difference) # Output: Difference: 5
print("Product:", product)       # Output: Product: 50
print("Quotient:", quotient)     # Output: Quotient: 2.0 (Note: division often results in float)
print("Floor Quotient:", floor_quotient) # Output: Floor Quotient: 2

Other useful operations for integers include:

# Modulus (%)
modulus = a % b  # Returns the remainder of a divided by b
print("Modulus:", modulus) # Output: Modulus: 0 (10 divided by 5 has a remainder of 0)

# Exponentiation (**)
exponentiation = a ** 2 # a raised to the power of 2 (10 * 10)
print("Exponentiation:", exponentiation) # Output: Exponentiation: 100

# Absolute Value (abs())
absolute_value = abs(-10) # Absolute value of -10
print("Absolute Value:", absolute_value) # Output: Absolute Value: 10

# Round (round()) - Used for rounding numbers, works on both int and float
rounded_value = round(3.7) # Round 3.7 to the nearest integer
print("Rounded Value (3.7):", rounded_value) # Output: Rounded Value (3.7): 4

rounded_value_decimal = round(3.14159, 2) # Round to 2 decimal places
print("Rounded Value (3.14159 to 2 places):", rounded_value_decimal) # Output: Rounded Value (3.14159 to 2 places): 3.14

Floating-point numbers (float)

Floats are used for numbers with decimal points. They are also part of the python numeric data types.

pi = 3.14159
e = 2.71828
negative_float = -1.5
zero_float = 0.0

print(pi, e, negative_float, zero_float) # Output: 3.14159 2.71828 -1.5 0.0

Arithmetic operations work similarly to integers:

x = 10.0
y = 5.0

sum_float = x + y       # Addition
difference_float = x - y       # Subtraction
product_float = x * y      # Multiplication
quotient_float = x / y     # Division

print("Float Sum:", sum_float)         # Output: Float Sum: 15.0
print("Float Difference:", difference_float) # Output: Float Difference: 5.0
print("Float Product:", product_float)       # Output: Float Product: 50.0
print("Float Quotient:", quotient_float)     # Output: Float Quotient: 2.0

Important Note on Floats: Be aware that floating-point numbers can sometimes have small precision issues due to how they are represented in computer memory. For most common calculations, this is not a problem, but for financial calculations or comparisons where exact precision is critical, you might need to use special libraries like decimal.

# Example of potential floating-point precision issue
# This may not equal exactly 0.3 due to internal representation
a = 0.1 + 0.2
print(a) # Output might be something like: 0.30000000000000004

Strings (str)

Strings are used for text. The string data type in python is incredibly versatile. You can create a string by enclosing characters in single quotes (‘…’) or double quotes (“…”).

greeting = "Hello"
name = 'Alice'
sentence = "Python is fun!"
number_as_string = "123" # Even if it looks like a number, if in quotes, it's a string!

print(greeting, name, sentence, number_as_string) # Output: Hello Alice Python is fun! 123

There are many operations you can perform on strings. Here are some common ones:

Concatenation: Joining strings using the + operator.

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name # Add a space in between
print(full_name) # Output: John Doe

Slicing: Extracting a portion of a string using square brackets [] and indices. Python uses zero-based indexing, meaning the first character is at index 0.

my_string = "Programming"
# Get characters from index 0 up to (but not including) 4
substring = my_string[0:4]
print(substring) # Output: Prog

# Get characters from index 4 to the end
substring_from = my_string[4:]
print(substring_from) # Output: ramming

# Get characters from the beginning up to (but not including) index 3
substring_to = my_string[:3]
print(substring_to) # Output: Pro

# Get the last character
last_char = my_string[-1]
print(last_char) # Output: g

Length: Getting the number of characters in a string using the len() function.

text = "Hello"
text_length = len(text)
print(text_length) # Output: 5

Upper and Lower Case: Converting the entire string to uppercase or lowercase using .upper() and .lower() methods.

mixed_case = "PyThOn"
upper_case = mixed_case.upper()
lower_case = mixed_case.lower()
print(upper_case) # Output: PYTHON
print(lower_case) # Output: python

Stripping: Removing leading and trailing whitespace (spaces, tabs, newlines) using the .strip() method. .lstrip() removes leading whitespace, and .rstrip() removes trailing whitespace.

whitespace_string = "   some text with spaces   \n"
stripped_string = whitespace_string.strip()
print(f"'{stripped_string}'") # Output: 'some text with spaces'

Replacing: Replacing occurrences of a substring within a string using the .replace() method.

sentence = "I like dogs."
new_sentence = sentence.replace("dogs", "cats")
print(new_sentence) # Output: I like cats.

Splitting: Splitting a string into a list of substrings based on a delimiter (by default, whitespace) using the .split() method.

csv_data = "apple,banana,cherry"
fruits_list = csv_data.split(",")
print(fruits_list) # Output: ['apple', 'banana', 'cherry']

sentence_split = "This is a sentence."
words = sentence_split.split() # Splits by whitespace
print(words) # Output: ['This', 'is', 'a', 'sentence.']

Joining: Joining a list of strings into a single string using the .join() method. This is the opposite of split().

word_list = ["Hello", "World", "Python"]
# Join with a space in between
joined_string_space = " ".join(word_list)
print(joined_string_space) # Output: Hello World Python

# Join with a hyphen in between
joined_string_hyphen = "-".join(word_list)
print(joined_string_hyphen) # Output: Hello-World-Python

Formatting (f-strings): Inserting values of variables or expressions directly into a string using f-strings (formatted string literals, available in Python 3.6+). This is a very convenient way to build strings.

name = "Alice"
age = 30
# Put the variable names directly inside curly braces {}
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string) # Output: My name is Alice and I am 30 years old.

These are just some of the most common data types in python with examples for strings. There are many more string methods to explore as you advance.

Booleans (bool)

The boolean data type in python is the simplest, representing only one of two values: True or False. These values are often the result of comparisons or logical operations, and they are fundamental for controlling the flow of your programs using conditional statements (like if statements, which we’ll cover in a future post).

is_logged_in = True
has_permission = False
is_greater = 10 > 5    # The result of a comparison is a boolean
is_equal = (5 == 5)  # Check for equality (use ==)

print(is_logged_in) # Output: True
print(has_permission) # Output: False
print(is_greater)   # Output: True
print(is_equal)     # Output: True

These four – integers, floats, strings, and booleans – are the foundational basic data types in python you’ll encounter constantly. Mastering them is key to writing effective Python code.

Converting Between Types: Type Conversion in Python

What happens when you have data in one format, but you need it in another? For example, you might receive user input as text (a string), but you need to perform mathematical calculations (which require numbers). This is where type conversion becomes handy.

What is type conversion in python? It’s the process of converting a value from one data type to another. 

Python provides built-in functions to help you perform type conversion function in python:

Python provides built-in functions to help you perform type conversion function in python:

  1. int(value): Converts value to an integer.
  2. float(value): Converts value to a floating-point number.
  3. str(value): Converts value to a string.
  4. bool(value): Converts value to a boolean.

Let’s see some examples of how to do type conversion in python using these functions:

Converting Numbers and Strings

You can convert between numbers (int/float) and strings if the string contains a valid representation of the number.

# Integer to Float
int_value = 10
float_value = float(int_value)  # Converting integer to float
print(f"Integer {int_value} converted to float: {float_value}") # Output: Integer 10 converted to float: 10.0

# Float to Integer (Note: This truncates the decimal part)
float_value = 3.99
int_value = int(float_value)  # Converting float to integer
print(f"Float {float_value} converted to integer: {int_value}") # Output: Float 3.99 converted to integer: 3

# String to Integer (String must contain only digits, optionally with a sign)
string_value = "42"
int_value = int(string_value) # Converting string to integer
print(f"String '{string_value}' converted to integer: {int_value}") # Output: String '42' converted to integer: 42

# String to Float (String must contain a valid number format)
string_value = "3.14"
float_value = float(string_value) # Converting string to float
print(f"String '{string_value}' converted to float: {float_value}") # Output: String '3.14' converted to float: 3.14

# Example of python type conversion string to int causing an error
# invalid_string = "hello"
# int_value = int(invalid_string) # This would raise a ValueError because "hello" cannot be converted to an integer

These are key examples of type conversions in python, showing you data type conversion in python examples that are very common.

Converting to Boolean

The bool() function can convert values of other types into a boolean. The rule is generally: “empty” or “zero” values convert to False, while “non-empty” or “non-zero” values convert to True.

# String to Boolean
print(f"bool('Hello'): {bool('Hello')}") # Output: bool('Hello'): True (Non-empty string is True)
print(f"bool(''): {bool('')}")     # Output: bool(''): False (Empty string is False)

# Integer to Boolean
print(f"bool(10): {bool(10)}")     # Output: bool(10): True (Non-zero number is True)
print(f"bool(0): {bool(0)}")       # Output: bool(0): False (Zero is False)

# Float to Boolean
print(f"bool(3.14): {bool(3.14)}")   # Output: bool(3.14): True (Non-zero float is True)
print(f"bool(0.0): {bool(0.0)}")     # Output: bool(0.0): False (Zero float is False)

Conclusion

Congratulations! You have taken significant steps in your Python journey by learning about variables, fundamental data types, and the crucial process of type conversion.

You now understand:

  • what is variable in python and how to name them correctly.
  • what are data types in python and the key differences between integers, floats, strings, and booleans.
  • what is type conversion in python and how to do type conversion in python using built-in functions like int(), float(), str(), and bool().

These concepts are the basis upon which you will build more complex programs.Practice creating variables, experimenting with different data types and string operations, and trying out various type conversions in python. The more you code, the more intuitive these concepts will become.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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