Menu

Python Basics for Data Science

Python programs process information through variables, data types, and operators. These elements are essential for handling numerical values, performing calculations, evaluating conditions, and preparing data for analysis.

For example, an e-commerce application may store product prices as floating-point numbers, quantities as integers, and payment statuses as Boolean values. Python uses these values to calculate revenue, validate transactions, and generate business metrics.

Python is a high-level, general-purpose programming language with dynamic typing, automatic memory management, and an extensive ecosystem of libraries for numerical computing, data analysis, and machine learning.

Understanding how Python represents and processes information is the first step towards using libraries such as NumPy, Pandas, and Scikit-learn.

What Are Variables in Python?

A variable is a name that refers to an object stored in memory. Variables allow programmers to access and manipulate information without repeatedly entering the original values.

Python creates a variable when a value is assigned using the assignment operator (=).

Consider the following example:

customer_name = "Aarav"customer_age = 25purchase_amount = 4500.50is_subscribed = Trueprint(customer_name)print(customer_age)print(purchase_amount)print(is_subscribed)

Output:

Aarav
25
4500.5
True

Here:

  • customer_name refers to a string containing the customer's name.
  • customer_age refers to an integer value.
  • purchase_amount refers to a floating-point number.
  • is_subscribed refers to a Boolean value.

Python uses dynamic typing, meaning the variable name does not require an explicitly declared data type.

For example:

value = 100value = "Data Science"print(value)

Output:

Data Science

The variable value initially refers to an integer and is subsequently reassigned to a string.

Although Python allows reassignment between data types, maintaining consistent types is important when processing datasets.

What Are the Main Data Types in Python?

A data type defines the kind of value represented by an object and determines which operations can be performed on it.

Python provides several built-in data types.

Data Type Description Example Data Science Application
Integer (int) Whole numbers 150 Number of transactions
Float (float) Decimal numbers 2450.75 Sales revenue
String (str) Text values "Electronics" Product categories
Boolean (bool) True or false values True Subscription status
List (list) Ordered, mutable collection [10, 20, 30] Daily sales
Tuple (tuple) Ordered, immutable collection (28.6, 77.2) Coordinates
Dictionary (dict) Key-value collection {"age": 25} Customer records
Set (set) Collection of unique elements {101, 102} Unique customer IDs
NoneType Represents the absence of a value None Missing or unavailable information

Integer and Float Data Types

Integers represent whole numbers, whereas floats represent numerical values using floating-point representation.

orders = 120average_order_value = 1599.50print(type(orders))print(type(average_order_value))

Output:

<class 'int'>
<class 'float'>

The type() function identifies the type of an object.

Python integers can represent arbitrarily large values subject to available memory. Standard Python floats generally use double-precision binary floating-point representation.

This distinction matters because floating-point calculations can introduce small rounding differences.

For example, financial applications requiring exact decimal arithmetic may use Python's decimal module rather than relying exclusively on floating-point values.

String Data Type

Strings represent text enclosed in single or double quotation marks.

product = "Laptop"category = "Electronics"print(product.upper())print(category.lower())

Output:

LAPTOP
electronics

Strings are useful for processing customer names, product descriptions, categories, and other text-based information.

Python also supports string indexing and slicing.

language = "Python"print(language[0])print(language[0:3])

Output:

P
Pyt

Python uses zero-based indexing, meaning the first character has index 0.

Boolean Data Type

Boolean values represent logical states.

payment_successful = Truerefund_requested = Falseprint(payment_successful)print(refund_requested)

Boolean variables are commonly used to represent transaction outcomes, customer eligibility, and binary classification labels.

For example, a fraud detection dataset may represent fraudulent transactions as 1 and legitimate transactions as 0.

What Is Type Conversion in Python?

Type conversion changes a value from one compatible data type to another.

Real-world datasets frequently contain numerical information stored as strings.

For example, a CSV file may contain a purchase amount represented as "2500" rather than the numerical value 2500.

Python provides built-in functions for type conversion.

Function Purpose
int() Converts compatible values into integers
float() Converts compatible values into floating-point numbers
str() Converts values into strings
bool() Converts values into Boolean values

Consider the following example:

price = "2500"quantity = 3total = int(price) * quantityprint(total)

Output:

7500

The int() function converts the string into an integer before multiplication.

Type conversion requires valid input values. For example, converting "Laptop" using int() raises a ValueError.

Data scientists must therefore validate values before performing numerical operations.

What Are Operators in Python?

Operators are symbols or keywords used to perform calculations, compare values, and evaluate logical expressions.

Python provides arithmetic, comparison, logical, assignment, membership, and identity operators.

Arithmetic Operators

Arithmetic operators perform mathematical operations on numerical values.

Operator Operation Example Result
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 4 2.5
// Floor division 10 // 4 2
% Modulus 10 % 4 2
** Exponentiation 2 ** 3 8

Consider an e-commerce company calculating revenue.

unit_price = 1200quantity = 5revenue = unit_price * quantityprint("Total Revenue:", revenue)

Output:

Total Revenue: 6000

The multiplication operator calculates total revenue from product price and quantity sold.

Comparison Operators

Comparison operators evaluate relationships between values and return Boolean results.

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

For example:

monthly_sales = 85000sales_target = 75000print(monthly_sales >= sales_target)

Output:

True

The expression evaluates whether actual sales meet or exceed the target.

Logical Operators

Logical operators combine Boolean expressions.

Python provides three primary logical operators:

  • and returns True when both conditions are true.
  • or returns True when at least one condition is true.
  • not reverses the truth value of an expression.

Example:

purchase_amount = 6500is_member = Trueeligible = purchase_amount > 5000 and is_memberprint(eligible)

Output:

True

This condition checks whether a customer has spent more than ₹5,000 and holds an active membership.

Assignment Operators

Assignment operators update variables using mathematical operations.

sales = 10000sales += 2500sales *= 2print(sales)

Output:

25000

The += operator adds a value to the existing variable, while *= multiplies the current value.

How Are Variables and Operators Used in Data Science?

Data science workflows frequently involve calculating derived features from existing numerical variables.

Consider a retail dataset containing product prices and quantities.

Total revenue is calculated using:

\[ Revenue = Price \times Quantity \]

Profit margin can be calculated using:

\[ Profit\ Margin = \frac{Revenue-Cost}{Revenue}\times100 \]

Python implementation:

revenue = 50000cost = 35000profit_margin = ((revenue - cost) / revenue) * 100print(f"Profit Margin: {profit_margin:.2f}%")

Output:

Profit Margin: 30.00%

These calculations become particularly useful when applied to thousands of records using Pandas or NumPy.

Common Mistakes Beginners Should Avoid

  1. Confusing assignment and comparison: = assigns a value, while == compares values.
  2. Mixing incompatible data types: Adding a string to an integer raises a TypeError.
  3. Ignoring floating-point precision: Binary floating-point calculations may produce small rounding differences.
  4. Using unclear variable names: Descriptive names such as total_revenue improve readability.
  5. Forgetting Python is case-sensitive: Sales and sales refer to different variable names.

Data Science Tutorial for Beginners

VA

Vaishali Ardhana



Learn via Video Course

undefined Logo

0 hrs



Get in Touch For Details