Python for Data Science: Day 2-Python Basics

Muhammad Dawood
6 min readJul 17, 2023

--

Python for Data Science: Day 2-Python Basics

Day 2 of our Python for Data Science challenge! We established the groundwork yesterday by installing Python and the necessary libraries. Today, we’ll go through Python fundamentals, providing you with core programming principles that will act as building blocks for your data science journey. Let’s get started!

Variables and Data Types:

In Python, we use variables to store information. Think of a variable as a box with a name. We can put different things in these boxes and give them names that make sense to us.

There are different types of information we can put in these boxes. Let’s talk about a few:

Numbers:

We can put numbers in our boxes. There are two types of numbers: whole numbers (like 5 or 10) and numbers with decimal points (like 3.14 or 2.5).

# Whole numbers (integers)
age = 15
quantity = 10

# Numbers with decimal points (floating-point)
pi = 3.14
temperature = 98.6

Text:

We can also put words or sentences in our boxes. We call this type of information a “string.” For example, we can put “Hello” or “My name is Dawood” in a box.

greeting = "Hello"
name = "Dawood"
sentence = "My name is Dawood"

True or False:

Sometimes we need to decide if something is true or false. We use a particular type of information called a “boolean.” It can only be true or false, like answering “yes” or “no” to a question.

is_raining = True
is_sunny = False

Lists:

Imagine having a bunch of boxes lined up together. In each box, we can put any type of information we want — numbers, words, or even other boxes. We call this a “list.” It helps us keep many things together.

numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
mixed_list = [1, "apple", True, 3.14]

Dictionary:

A dictionary is like a real dictionary, where words have definitions. In programming, it’s a collection of labelled boxes. Each box has a name (we call it a “key”) and something in it (we call it a “value”).

student = {
"name": "Dawood",
"age": 15,
"grade": 9,
"school": "ABC High School"
}

employee = {
"name": "Ali",
"age": 25,
"position": "Manager",
"salary": 5000.0
}

In the examples above, we assign values to variables using the equal sign (=). The variable name is on the left side of the equal sign, and the value is on the right side.

These are some basic types of information we can store in our Python boxes. Using variables and different data types, we can save and work with all sorts of information in our programs.

Basic Arithmetic Operations:

Python allows you to perform various arithmetic operations on numbers. These operations include addition, subtraction, multiplication, division, and more. Let’s go through each one:

Addition (+):

The addition operation is used to combine two or more numbers. For example:

2 + 3 = 5

Subtraction (-):

The subtraction operation is used to find the difference between two numbers. For example:

5 - 2 = 3

Multiplication (*):

The multiplication operation is used to multiply two or more numbers together. For example:

3 * 4 = 12

Division (/):

The division operation is used to divide one number by another. It gives you the quotient (the result of the division). For example:

10 / 2 = 5

Modulo (%):

The modulo operation gives you the remainder after division. It is denoted by the per cent sign (%). For example:

10 % 3 = 1 (Because 10 divided by 3 is 3 with a remainder of 1)

Exponentiation (**):

The exponentiation operation raises a number to a power. It is denoted by two asterisks (**). For example:

2 ** 3 = 8 (Because 2 raised to the power of 3 is 8) or (2*2*2=8)

These are the basic arithmetic operations in Python. You can use them to perform calculations and solve mathematical problems in your programs. Remember that the order of operations follows the usual rules in mathematics, such as parentheses first, then exponentiation, multiplication and division, and finally addition and subtraction.

Working with Strings:

Working with strings in Python is quite straightforward. Strings are used to represent text or a sequence of characters. Here are some common operations and manipulations you can perform on strings in Python:

Creating a String:

To create a string, you simply enclose the text in single quotes (‘ ’) or double quotes (“ ”). For example:

message = "Hello, World!"
name = 'Alice'

Accessing Characters:

You can access individual characters within a string by using square brackets [ ] and providing the index of the character you want. Note that Python uses zero-based indexing, so the first character is at index ( ). For example:

message = "Hello, World!"
print(message[0]) # Output: 'H'
print(message[7]) # Output: 'W'

String Length:

To determine the length (number of characters) of a string, you can use the len() function. For example:

message = "Hello, World!"
print(len(message)) # Output: 13

Concatenating Strings:

You can concatenate (combine) strings using the + operator. This operation simply joins two strings together. For example:

greeting = "Hello"
name = "Alice"
message = greeting + " " + name
print(message) # Output: "Hello Alice"

String Slicing:

You can extract a portion of a string using slicing. Slicing allows you to retrieve a substring by specifying the start and end indices. For example:

message = "Hello, World!"
print(message[0:5]) # Output: "Hello"
print(message[7:]) # Output: "World!"

Modifying Strings:

Strings in Python are immutable, which means you cannot change individual characters within a string. However, you can create new strings based on existing ones. For example:

message = "Hello, World!"
new_message = message.replace("World", "Python")
print(new_message) # Output: "Hello, Python!"

These are just a few examples of operations you can perform on strings in Python. Strings offer many more capabilities, such as searching, splitting, and formatting. Python provides various built-in methods and functions to manipulate and work with strings effectively.

Control Flow:

Control flow in Python refers to the order in which statements are executed in a program. It allows us to make decisions, repeat actions, and perform different operations based on certain conditions. Let’s explore some common control flow structures in Python:

Conditional Statements (if, elif, else):

Conditional statements are used to make decisions based on specific conditions. The if statement checks if a condition is true and executes a block of code if it is. The elif (short for "else if") statement allows us to check additional conditions if the previous ones are false. The else the statement provides a fallback option if none of the previous conditions are met. Here's an example:

age = 15

if age < 13:
print("You are a child.")
elif age < 18:
print("You are a teenager.")
else:
print("You are an adult.")

Loops (for, while):

Loops allow us to repeat a block of code multiple times. The for loop iterates over a sequence (such as a list, string, or range) and performs the specified actions for each item. The while the loop continues executing a block of code as long as a certain condition is true. Here are examples of both types of loops:

# For loop
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)

# While loop
count = 0
while count < 5:
print("Count:", count)
count += 1

Break and Continue:

The break the statement is used to exit a loop prematurely. It allows you to terminate the loop even if the loop condition is still true. The continue statement skips the rest of the current iteration and moves to the next iteration. Here's an example:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
if num == 3:
break
print(num)

for num in numbers:
if num == 3:
continue
print(num)

These are basic control flow structures in Python that help control the flow and behaviour of your program. By using conditional statements, loops, and control statements like break and continue, you can create more complex and dynamic programs.

Throughout Day 2, practice coding exercises and challenges to reinforce your understanding of these fundamental concepts. Seek out online resources and tutorials to supplement your learning and gain further mastery over Python basics.

Congratulations on completing Day 2 of our Python for data science challenge! Today, you took significant strides in mastering Python basics, including variables, data types, arithmetic operations, working with strings, control flow, and loops. These fundamental concepts provide a solid foundation for your data science journey.

As you continue your Python learning, remember to practice regularly and experiment with different coding exercises. Tomorrow, on Day 3, we will explore data manipulation with Pandas, a powerful library for data analysis. Stay enthusiastic, embrace the learning process, and watch your Python skills flourish!

--

--

Muhammad Dawood
Muhammad Dawood

Written by Muhammad Dawood

On a journey to unlock the potential of data-driven insights. Day Trader | FX & Commodity Markets | Technical Analysis & Risk Management Expert| Researcher

No responses yet