Day 3 — Exploring Python’s Building Blocks: Variables and Basic Data Types

Akshay Gawande
Data Shastra
Published in
10 min readAug 23, 2023
Photo by Dan Cristian Pădureț on Unsplash

Welcome to an exciting journey into the heart of Python programming! In this comprehensive guide, we’ll unravel the essential elements that lay the foundation for your Python adventures. Let’s dive into the diverse world of variables and basic data types to supercharge your coding skills. 🚀🐍

Discover the gateway to Python’s data universe with an immersive exploration of variables and fundamental data types. In this enriching guide, you’ll unravel the essence of data manipulation, uncovering the power of variables and their role in crafting dynamic programs. Embark on a journey of insight and mastery with Python’s building blocks. 🚀🐍

Table of Contents 📚

  1. Understanding How Programs Execute
  2. Introduction to Variables and Simple Data Types
  3. Unveiling the World of Variables
  4. Exploring Essential Data Types
  5. Handy Tips and Insights
  6. Conclusion

Understanding How Programs Execute 😊

Today, we’re delving into the exciting world of data manipulation in Python. We’ll also explore the art of using variables to give life to our data. But before we embark on our data journey, let’s take a peek behind the curtain and see what really goes down when we run our trusty hello_world.py. Believe it or not, even the simplest program involves a bit of magic:

🔍 Python does its thing, even for a basic program:

hello_world.py

print('Hello Gotham, this is your Dark Knight, the Batman')

When we hit that run button, all we see is: Hello Gotham, this is your Dark Knight, the Batman

But beneath the surface, Python’s interpreter goes to work. It reads each line, follows instructions, and conjures up results. For example: When the interpreter encounters a print followed by those trusty parentheses (), it whips out whatever's inside and presents it on the screen. Voila! print() means "put this on the console."

So, buckle up! As we explore the data universe, remember, even the simplest hello can hide a touch of programming magic. 🎩✨

Introduction to Variables and Simple Data Types 😊📊

What is a Variable? 🌟📝

A variable is like a magical tag that points to a treasure stored in the memory of your program. It’s like naming a secret that you can use to access and transform your data throughout your coding journey! 🎩✨ Variables provide a way to label and manage information of all kinds: be it numbers, strings, lists, or even enchanting objects. Every variable is linked to a precious value, the essence of the information it holds. 🌈🔗

Let’s try using a variable in hello_world.py.

hello_world.py

#hello_world.py
message = 'Hello Gotham, this is your Dark Knight, the Batman!'
print(message)

We’ve added a variable named message with `value` Hello Gotham, this is your Dark Knight, the Batman! 📜🌆

When we ask a Python interpreter to run our code, it processes the first line and associates the variable message with “Hello Gotham, this is your Dark Knight, the Batman!” text. 😎🦇 And when it reaches the second line, it gleefully prints the value associated with the message to the screen. 🖨️🌌

Let’s try something else:


message = 'Hello Gotham, this is your Dark Knight, the Batman'
print(message)

message = "I'm not a hero. I'm whatever Gotham needs me to be."
print(message)

What this means is that we can change the value of a variable in our program at any time, and Python will always keep track of its current value.

Unveiling the World of Variables🌍🔍

Variables are Labels🏷️🔖:

Variables are often described as boxes you can store values in, but it isn’t an accurate way to describe how variables are represented internally in Python. It’s better to think of variables as labels that you can assign to values.

We can also say that a variable references a certain value.

How to name and use the variables?📝

Whenever we use variables in Python, we should follow a few rules. These rules will help us to write code that’s easier to read, and understand and minimize errors.

  1. Variable names can contain only letters [a-z, A-Z], numbers [0–9], and underscore [_].
  2. Variables can start with a letter or an underscore, but NOT with a number. For instance, message_1 is valid but 1_message is not.
  3. Spaces are not allowed in variable names but we can use underscore instead. For example, first_name works but first name will throw an error.
  4. Avoid using Python Keywords and function names as variable names.
  5. Variable names should be short and descriptive. For example, first_name is better than f_n, name_length is better than length_of_persons_name😊🚀

Exploring Essential Data Types 🧐📊

Strings:

A string is a series of characters. Anything inside quotes is considered a string in Python, and we can use single or double quotes around your strings as follows:😄📝

"I am Batman"
"It's not who I am underneath, but what I do that defines me."

This flexibility allows us to use the quotes and apostrophes within our string:

"I'm not a hero. I'm whatever Gotham needs me to be."
'He said "Why so serious? HAHAHAHAHA"'

Let’s take a look at a few methods/operations we can do with String:

  • Changing Case in a String with Methods:
    One of the simplest things we can do with the String is to change the case of the words in a String.
name = 'bruce wayne'
print(name.title())

What is a Method?
The method is an action that Python can perform on a piece of data. The dot[.] after name in name.title() allows Python to make the title() methods act on the variable `name`. Every method is followed by a set of parentheses because methods often need additional parameters to do their work. that information is provided inside the parenthesis.🤖🔍

In the above example title() method changes each word to title case, where each word begins with a capital letter. 🌟✨

Several other useful methods are available for dealing with cases as well. For example: upper, lower🚀📚

name = 'brUce WAYne'
print(name.title())
print(name.upper())
print(name.lower())

the lower() method is particularly useful for storing the data. We typically don’t want to trust the capitalization that our users provide, so we will convert the strings to lowercase before storing them.

Using variables in a string:

In some situations, we might need to use a variable’s value inside a string. For example, if we want to use two variables to represent a first name and a last name, respectively, and then combine those values to display the full name:🚀📚

first_name = 'Bruce'
last_name = 'Wayne'
full_name = f"{first_name} {last_name}"
print(full_name)

The f here stands for the format and these strings are called f-strings. We can use the f-strings to compose a message and then assign the entire message to a variable.🚀📚


first_name = ‘Bruce’
last_name = ‘Wayne’
full_name = f”{first_name} {last_name}”
message = f”Alfred, No know should ever know that {first_name} {last_name} is Batman”
print(message)

How to add whitespaces to strings with Tabs or Newlines?
In programming, whitespace refers to any nonprinting characters, such as spaces, tabs, and end-of-line symbols. We use these white spaces characters to organize our output so that it’s easier for users to read.📝👨‍💻
1. Tab [\t]:
To add a tab to our text we use [\t]📑📊

print(‘I am Batman’)
print(‘I am \t Batman’)

2. New Line [\n]:
To add a new line we use [\n]

print('Villains:\nJoker\nTwo Face\nPenguine\nScare Crow\nBane')

We can also combine the tabs and newlines in a single string. [\n\t] will tell the Python to move to the next line and add a tab.

print('Villains:\n\tJoker\n\tTwo Face\n\tPenguine\n\tScare Crow\n\tBane')

Stripping Whitespaces:

To us as a Programmer and human being with brain ‘Batman’ and ‘Batman ‘ looks the same and has the same meaning. But then the program they are two different strings. It is very important to think about the whitespaces because we might need to compare two strings to determine whether they are the same or not. Python makes it easy to eliminate an extra whitespace from data that we need to process. Below are some methods which we can use to trim these whitespaces.🧹📝
1. rstrip(): To remove the whitespaces at the right side of a string.
2. lstrip(): To remove the whitespaces at the left side of a string.
3. strip(): TO remove the whitespaces from both sides of a string.🧼🌟

variable_name = '  I AM VENGENCE  '
print(variable_name.lstrip())
print(variable_name.rstrip())
print(variable_name.strip())

Important:

When any of the above strip methods acts on a variable, the extra space is removed from the left, right, or both sides of a variable based on the method we use. However, it is only removed temporarily. If we ask for the value of the variable again, the string looks the same as when it was entered including the extra whitespace.⚠️🧽

For Example:

message = ' I am Batman '
print(message.strip())
print(message)
stripped_message = message.strip()
print(stripped_message)

Let’s look at some more string methods:

  1. removeprefix():
    When working with the string, another common task is to remove a prefix. Consider a URL with the common prefix https://. We want to remove this prefix, so we can focus on just the part of the URL.👀🔗

gotham_url = 'https://gothamcity.com'
print(gotham_url.removeprefix('https://'))
print(gotham_url)

When we see a URL in an address bar and https:// part isn’t visible, the browser is probably using a method like removeprefix() behind the scenes.😎🌐

2. removesuffix():
We can also remove the suffix if needed.🪄🔗

file_name = 'Arkham_Asylum.txt'
print(file_name.removesuffix('.txt'))
print(file_name)

How to Avoid Syntax Errors with String?🚫🔍

A syntax error occurs when a Python doesn’t recognize a section of our program as a valid Python Code.
For Example, if we use the apostrophes in a single quote, we will get an error message.🚫📝

Here’s how to use single and double quotes correctly.🤓📜

message = "I'm whatever Gotham needs me to be."
print(message)

message = '''I'm whatever Gotham needs me to be.'''
print(message)

message = 'I\'m whatever Gotham needs me to be.'
print(message)

Numbers: 🧮🔢

Numbers are used quite often in programming to keep the score of games, represent data in visualization, store information, account details, and many more. Python treats numbers in several different ways, depending on how they’re being used.
Let’s take a look at how Python manages integers, because they are simplest to work with.

1. Integers:
— We can add [+], subtract [-], multiple[*], divide [/] integers in Python.
— [**] Python uses two multiplication symbols to represent exponents.
— Python supports the order of operations[PEMDAS/BIDMAS] too.
Parentheses / Brackets
Exponents / Indices
Multiplication and Division (from left to right)
Addition and Subtraction (from left to right)
🚀🧾

print(2 + 3)

print(3 - 2)

print(2 * 3)

print(3 / 2)

print(3 ** 2)

print(( 3 * 3) / 2 ** 2)

2. Floats:🌟🔢
— Python calls any number with a decimal point as a float.
— We can perform all the mathematical operations related to decimals with Python.
— Sometimes we can get an arbitrary number of decimal places in our answers.💃🕺🌍

print(2.0 + 3.5)

print(3.5 - 2.0)

print(2.0 * 3.5)

print(3.5 / 2.0)

print(3.5 ** 2.0)

print(( 3.5 * 3.5) / 2.0 ** 2.0)

Numeric Insights 💡🔢

Here’s a glance at some intriguing aspects of numeric manipulation in Python:

Integers and Floats: When we divide any two numbers, even if they are integers that result in a whole number, you will always get a float.
If we mix an integer and a float in any other operations, we will get a float as well.
Python defaults to a float in any operation that uses a float, even if the output is a whole number.

Underscores in Numbers:
When we are writing long numbers, we can group the digits using the underscores to make the large numbers readable.
This feature works both with integer and float.

Multiple Assignment:
We can assign values to more than one Variable using just a single line of code. This can help us to shorten our program and make them easier to read.
We need to separate the variable names with commas and do the same with the values, and Python will assign each value to its respective variable. As long as the number of values matches the number of variables, Python will match them up correctly.

Constants:
A constant is a variable whose values stay the same throughout the life of a program, Python does not have a built-in constant type, but Python programmers use all Capital letters to indicate a variable should be treated as a constant and needs not be changed.🔢🌟

Embrace these numeric nuances as you orchestrate elegant code and navigate the realms of constants, assignments, and precision in Python! 🔢🌟

#Integers and Floats
#When we divide any two numbers, even if they are integers that result in a whole number, you will always get a float.

print( 100 / 10 )

#Underscores in Numbers:
num = 10_00_0_000
num2 = 10_25.5_51
print(num)
print(num2)

#Multiple Assignment:
num1, num2, num3, num4 = 75, 56, 98 , 123_45.67_89
print(num1)
print(num2)
print(num3)
print(num4)

#Constants
MAX_VAL = 10_000_000
print(MAX_VAL)

Conclusion:

Armed with these insights, you’re poised to understand, harness, and manipulate variables and basic data types proficiently. These foundational concepts serve as the stepping stones to crafting elegant, powerful, and dynamic Python programs. Let the exploration begin! 📚🔍🎓

--

--