If you’ve been in the data field for quite some time, you’ve probably noticed that some technical skills are becoming more dominant, and the data backs this up. Until the release of NumPy in 2005, Python was considered slow for numeric analysis. But Numpy changed that. Pandas, in 2008, made Python the best language for Data Analysis.
Further, with the introduction of frameworks like SciKit-Learn, Tensorflow, and PyTorchβPython became the number one programming language for Data Science (AI and ML).
Well, if you had asked any data professional a few years ago which language you should learn, R or Python, most would have said it really doesn’t matter. But with the rise in AI and LLMs, Python is certainly dominating. Today, in this part, we will be going over the handful of useful and cool tips and tricks you need to ditch the noob Python programmer inside you and write some better code. These are the fundamentals of Python programming for writing better codes, whether you are a beginner or a seasoned expert.
The goal of this Fundamentals of Python Programming article is to make sure whenever you’re reading the production code:
There are many codes, so I compiled all of them in a Python notebook, which you can download here. These codes will serve as a quick syntax reference.
Before diving deep first, let’s address the elephant in the room: Why Python?
Do you know 87% of data scientists use Python as their main language for current projects, and another 10% say they use it as a secondary language? That’s a huge number. Nowadays, many academic and research work and most enterprises extensively utilize Python programming language in Gen-AI and Deep Learning, Data Science, Data Analysis, Web Development, Web Scraping, etc. Python is often the language of choice for AI and machine learning applications due to several key reasons:
Disclaimer: Python is a case-sensitive programming language. The convention is to avoid syntax errors using a snake case with all lowercase letters.
I’ll start with the most important crux of Fundamentals of Python Programming, gradually working our way up.
This is going to be very code-y, but stay with me. Let’s begin!
The coming section will talk about the Python fundamentals:
# Static Typing in CPP, etc
int q = 9
# Dynamic Typing in Python
a = 1
print(type(a))
b = "Hi"
print(type(b))
c:float = 3.14
print(type(c))Output
<class 'int'>
<class 'str'>
<class 'float'>
# Dynamic binding in python
a = 1
print(a)
a = "Hi"
print(a)
1
Hi
Compilation is a widely used but poorly understood concept, especially by beginners. It converts high-level language code into machine-level binary code.
It’s done using:
Also read: Everything You Ever Wanted to Know About Setting up Python on Windows, Linux and Mac
These are some reserved words that are used by the compiler and interpreter to understand the program and make their work easier during the compilation process.
Though it seems the same, identifiers are the names we give to uniquely identify a variable, function, class, module, or other object. In contrast, the variable is a name given to a memory location used to store a value.
Having said that, since Python gives us the flexibility to name our identifiers, there are some rules associated with it:
name1 = "AnalyticalNikita.io"
print(name1)
AnalyticalNikita.io
myVariable = 3
VariableName = 4
_my_variable = 5
_ = "AnalyticalNikita.io"
print(myVariable)
print(VariableName)
print(_my_variable)
print(_)
3
4
5
AnalyticalNikita.io
Changing an objectβs data type is known as type conversion. There are two types of Type Conversion in Python:
Too heavy? Let’s break them out:
Python interpreter is smart enough to perform Implicit Type Conversion, reducing data loss automatically.
# Implicit Type Conversion
print(9+2.8)
print(type(9), type(2.8))
print(int(5.9))
print(float(3))
print(str('3'))
print(bool(0))
11.8
<class 'int'> <class 'float'>
5
3.0
3
False
However, it also allows its user to easily convert objects’ datatypes using specified functions in Explicit Type Conversion, sometimes referred to as type-casting.
Note: You need to be super-cautious while type-casting, as it may lead to data loss if the object is forced to conform to another particular datatype.
# Explicit Type Conversion
print(9 + float('2.8'))
print(type(9), type(2.8))
11.8
<class ‘int’> <class ‘float’>
The Python Type Conversion operation doesn’t change the original data. However, it creates a new value for the operations.
You may have often heard that some Python data types are immutable.
Immutability means that its original state cannot be modified once an object is created.
Whenever we talk about immutability at the memory level, we mean that an immutable object cannot be altered directly.
Any operation that seems to change to these objects actually creates a different memory allocation for these new objects with modified value/s.
Wherein the mutable objects share the same memory allocated previously. Changes to these objects occur in-place, modifying the original memory content without any new allocation.
id(): Returns the unique memory address for the unique objects.
# Printing addresses to verify immutability of primitive datatypes
primitive_data1 = 10
primitive_data2 = primitive_data1
primitive_data2 = 1 # replaced data2
print("Address of data1 is: ", id(primitive_data1)) # different addresses
print("Address of data1 is: ", id(primitive_data2)) # different addresses
print("Data 1 now is: ", primitive_data1)
Address of data1 is: 2615765789264
Address of data1 is: 2615765788976
Data 1 now is: 10
Python’s memory management relies on two principles to handle the deletion of objects.
print(): Prints specific messages on the standard output device’s screen.
a, b = 12, 30
# Rather
# a = 12
# b = 30
print("Value of 'a' is" , a ,"and Value of 'a' is" , b)
Value of 'a' is 12 and Value of 'a' is 30
pow(): Returns the value of x to the power y.
power = pow(3, 5)
print("Power of 3 raise to 5: ", power)
Power of 3 raise to 5: 243
print("Round of 10.5 is" , round(10.5)) # round down to 10
print("Round of 11.5 is" , round(11.5)) # round up to 12
Round of 10.5 is 10
Round of 11.5 is 12
billion = 1_000_000_000
print("Billion :", billion)
Billion : 1000000000
del: Deletes the object.
# Set the variable 'age' to the value 16
age = 16
print("Initial value of 'age':", age)
# Check if 'age' is in the local and global namespaces
print("'age' in locals():", 'age' in locals())
print("'age' in globals():", 'age' in globals())
# Delete the variable 'age'
del age
# print("After deleting 'age':", age) # This will raise an error since 'age' is deleted
# Check again if 'age' is in the local and global namespaces
print("'age' in locals():", 'age' in locals())
print("'age' in globals():", 'age' in globals())
print("\n")
# Set the variable 'age' to the value None
age = None
print("After setting 'age' to None:", age)
# Check again if 'age' is in the local and global namespaces
print("'age' in locals():", 'age' in locals())
print("'age' in globals():", 'age' in globals())
Initial value of 'age': 16
'age' in locals(): True
'age' in globals(): True
'age' in locals(): False
'age' in globals(): False
After setting 'age' to None: None
'age' in locals(): True
'age' in globals(): True
# Function to prints character position
def position(x, y, z):
print(f'Character to {x} {y} {z}')
# Unpack the list to its equivalent position
pos = [5, 10, 15]
position(*pos)
Character to 5 10 15
all(): Returns “True” if all elements in an iterable are “True”.
and(): Returns “True” if both operands are “True”.
# Define age and reputation
age = 21
reputation = 20
# Create a list of conditions
conditions = [
age >= 21, # Check if age is greater than or equal to 21
reputation > 25 # Check if reputation is greater than 25
]
# Use all() to allow access
if all(conditions):
print("You're an admin. Allowed the access.")
else:
print("You're a standard user. Not allowed the access.")
You're a standard user. Not allowed the access.
any(): Returns “True” if at least one element in an iterable is “True”.
or(): Returns “True” if at least one operand is “True”.
# Define age and reputation
age = 21
reputation = 20
# Create a list of conditions
conditions = [
age >= 21, # Check if age is greater than or equal to 21
reputation > 25 # Check if reputation is greater than 25
]
# Use any() to allow access
if any(conditions):
print("You're an admin. Allowed the access.")
else:
print("You're a standard user. Not allowed the access.")
You're an admin. Allowed the access.
In Python, specifically, strings are a sequence of Unicode Characters:
To encounter this problem, firstly, we need to understand a brief about ASCII (American Standard Code for Information Interchange) and Unicode Values:
I believe it is now clearer to you that Python strings use Unicode values rather than ASCII. This gives Python a much wider array of characters to represent different languages and a variety of emoji symbols.
String is a universal data type; any data type can be type-cast as “string” or “object.”
Before digging into codes, let’s discuss the most important concept that is helpful for both interview preparation and day-to-day work as a DS.
As we already know, strings in Python are immutable, and their deletion follows the general rule of immutable objects.
# Print statements with colored text using ANSI escape codes
print(f"\033[97mCoding is \033[92mexciting")
print(f"\033[97mCoding is \033[92mcreative")
print(f"\033[97mCoding is \033[91mchallenging")
print(f"\033[97mCoding is \033[91mstressful")
print("\n")
print(f"\033[93mCoding Everyday!")
The output of this code is really colorful. So, check out this link.
# Open a web browser and navigate to Google
import webbrowser
webbrowser.open('https://www.google.com')
True
# Concatenate strings without using "+" sign
message = "Hello, this " "string concatenation" " without using '+' sign."
print(message)
Hello, this string concatenation without using '+' sign.
split(): Splits the string into a list using a specific delimiter.
# Split a fullname into first and last names based on underscore separator
full_name = "Analytical_Nikita.io"
first_name , last_name = full_name.split(sep= "_")
print(first_name, last_name)
Analytical Nikita.io
join: Joins the list into a single string with a specified separator.
# Join a list of names into single string with an underscore separator
names = ["Analytical", "Nikita.io"]
full_name = "_".join(names)
print(full_name)
Analytical_Nikita.io
in: Returns the index of the first occurrence in a specific string.
# Check if the substring is present in string and print its index
if "Analytical" in "AnalyticalNikita.io":
print("The substring is present at", "AnalyticalNikita.io".index("Analytical"), "index.")
The substring is present at 0 index.
Note: If the value is not present in the substring it will throw an error, to avoid this, we use find() function.
find(): Returns the index of first occurrence in a specific string. If not found, return -1.
# Finding a substring in a string
print("The substring is present at", "AnalyticalNikita.io".find("Analytics"), "index.")
The substring is present at -1 index.
id(): Returns the unique memory address for the unique objects.
# Printing address of specific data
data = {"AnalyticalNikita.io": 1}
print("Address of this data is: ", id(data))
Address of this data is: 2615849709376
We use an alias if we want two variables to point to the same data or if we want functions to be able to modify arguments passed to them.
# Aliasing
data1 = {"AnalyticalNikita.io": 1}
data2 = data1
data2['DataAnalytics'] = 9
# Print memory address of both dictionaries
print("Address of data1 is: ",id(data1))
print("Address of data2 is: ",id(data2))
# Print the modified dictionary
print("Data1 now is: ", data1)
Address of data1 is: 2615850448448
Address of data2 is: 2615850448448
Data1 now is: {'AnalyticalNikita.io': 1, 'DataAnalytics': 9}
# List of favorite technologies
favorite_technologies = ["Python", "SQL", "Power BI", "Tableau", "SAS", "Alteryx"]
# Iterate over the list of favorite technologies
for technology in (favorite_technologies):
print(technology, end = " ")
print("") #to go to next line for the next output
Python SQL Power BI Tableau SAS Alteryx
# Define name and list of favorite technologies
name = "AnalyticalNikita.io"
favorite_technologies = ["Python", "SQL", "Power BI", "Tableau", "SAS", "Alteryx"]
print(name, "is proficient in", favorite_technologies)
AnalyticalNikita.io is proficient in ['Python', 'SQL', 'Power BI', 'Tableau', 'SAS', 'Alteryx']
f” “: Embed expressions inside the string literals.
# Implict string conversion
name = "AnalyticalNikita.io"
print(f"My name is {name}.")
My name is AnalyticalNikita.io.
# Function to return a tuple of positions
def returning_position():
# In, real scenario, these values are obtained from user or database
return 5, 10, 15, 20
print("A tuple", returning_position())
# Assign the values from tuple to multiple variable
x, y, z, a = returning_position()
print("Assigning to multiple variables: ", "x is", x, "y is", y,"z is", z,"a is", a)
A tuple (5, 10, 15, 20)
Assigning to multiple variables: x is 5 y is 10 z is 15 a is 20
# Method 1: If - else
reputation = 30
if reputation > 25:
name = "admin"
else:
name = "visitor"
print(name)
# Method 2: String comprehension
reputation = 20
name = "admin" if reputation > 25 else "visitor"
print(name)
admin
visitor
Break: Terminates the current loop.
# Create a list of fruits
fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi', 'apple']
# Option 1: Check if 'orange' is in the list directly
if 'orange' in fruits: print("Yes, 'orange' is in the list.")
# Option 2: Use a flag variable to check for 'kiwi'
kiwi_found = False # Assume
for fruit in fruits:
print(fruit, end=" ") # do something with each element if needed
if fruit == 'kiwi':
kiwi_found = True # could count elements
break
if kiwi_found: print("\nYes, 'kiwi' is in the list.")
# Option 3: Check if 'grapefruit' is in the list without using break
for fruit in fruits:
print(fruit, end=" ")
if fruit == 'grapefruit':
break
else: #no break
print("\nNo 'grapefruit' found in the list.")
Yes, 'orange' is in the list.
apple banana orange grape kiwi
Yes, 'kiwi' is in the list.
apple banana orange grape kiwi apple
No 'grapefruit' found in the list.
# Create a list of fruits with duplicate data
fruits = ['apple', 'banana', 'banana', 'banana', 'kiwi', 'apple']
# Removing duplicate items of list using set
unique_fruits = list(set(fruits))
print("Unique fruits are: ", unique_fruits)
Unique fruits are: ['apple', 'kiwi', 'banana']
It is popularly used while checking against a list of values.
# Check the weather condition and cancel the plan if the weather in the given list
weather = "rainy"
if weather in ['rainy', 'cold', 'snowy']:
print("Plan is cancelled")
Plan is cancelled
It may be frustrating, but mistakes are truly inevitable when writing a program. Those programming errors are called bugs, and the process of fixing them is called debugging.
Broadly, three types of common errors can occur in a program:
# Invalid Identifier
name! = "analyticalnikita.io"
Cell In[1], line 1
name! = "analyticalnikita.io"
^
SyntaxError: invalid syntax
# TypeError is a type of Exception
# Input string
inputString = "analyticalnikita.io"
# Input Number
inputNumber = 29
# Adding both integer and string values
print(inputString + inputNumber)
TypeError: must be str, not int
# Finding average of 100 and 300
100 + 300 / 2
250
For some programmers, programming is debugging a program until it does what you want.
But if you spend a lot of time debugging your code, that’s a sign that you are writing too much code before testing it.
The idea here is to take smaller steps and divide your code into modular components. This will help you write better code and make debugging it much easier.
In this article, I have provided you with a comprehensive overview of the simplicity of the Python programming language. Weβll later discuss the versatility of awesome frameworks that make it a powerful tool for AI and ML.
It is the most popular programming language in the data science field due to its easy-to-learn syntax, extensive libraries, and strong community support.
Understanding Python programming fundamentals, such as static vs. dynamic typing, memory management, and useful string operations, can significantly improve your coding skills.
Remember, practice and constant learning are the keys to becoming a pro in any programming language. You can write better production-level code by following these practical tips and suggestions.
If you are looking to master a coding language online, then power up your career with the best and most popular data science language, Python. Leverage your Python skills to start your Data Science journey. This course is intended for beginners with no coding or Data Science background.
Ans. Static typing determines the methods to be invoked during compilation, while dynamic typing determines the datatype of variables at runtime.
Ans. Python manages memory using:
A. Reference Counting: It helps to track the number of references pointing to an object. Memory is freed when the count drops to zero.
B. Cyclic Reference Counting: The garbage collector handles the cyclic references to deallocate the memory that is no longer being used.
Ans. To write better Python code:
A. Thoroughly understand the basic concepts of Python.
B. Write modular code for your team and test often to catch bugs early.
C. Practice reading and writing production-level codes.
Ans. “Fundamentals of Python Programming” covers essential concepts like syntax, variables, data types, control structures (if, loops), and setting up the Python environment for coding.