1 Basic Data Types

(CSE331) Python for Data Science

Author
Affiliation

Md Rasel Biswas

IASDS, University of Dhaka

1 Quick Start

  • When you type something into the Python Console/REPL, it immediately evaluates and shows the result.
  • In notebooks (like Jupyter/Quarto), the last expression in a cell is also displayed.
2 + 4
6
  • As expected, Python returned 6.

2 Arithmetic Operations

  • Python can be used as a calculator.
  • Common operators: +, -, *, /, ** (power), // (floor division), % (modulus)
(59 + 73 + 2) / 3 
44.666666666666664
10**(3+1)               # exponentiation (** is power, not ^)
10000
3**2                     # 3 squared
9
10 // 3                  # 3: floor of the quotient
3
10 % 3                   # remainder (modulus)
1

With negative numbers, floor division rounds down, rather than toward zero:

print(-10 // 3)  # -4
print(-10 % 3)   # 2, because -10 = 3 * (-4) + 2
-4
2

Use parentheses to make the intended order of operations clear.

3 Creating Variables

  • A variable is a name that references an object (value) in memory.
  • Assignment (=) binds the name (left) to the object (right).
x = 48
  • Multiple assignment (tuple unpacking) is concise and common:
a, b, c, d = 7, 5, 8, 4
print(a, b, c, d)
7 5 8 4
  • Swapping variables without a temporary:
a, b = b, a
print(a, b)
5 7

4 Naming Variables

  • For this course, use these characters (Python also supports many Unicode letters):
    • letters (A–Z, a–z)
    • digits (0–9)
    • underscore (_)
  • Rules:
    • Cannot start with a digit.
    • Names may start with _ (e.g., _cache), but that implies “internal” by convention.
    • Reserved keywords cannot be used (e.g., True, False, None, and, class, def, …).
Style (PEP 8)
  • Use snake_case for variables/functions: total_count, is_ready.
  • Use UPPER_CASE for constants: PI = 3.14159.

5 Basic Scalar Data Types

Every value has a type describing what it represents and how it behaves.

  • int: integers (0, -7, 42)
  • float: approximate floating-point numbers (3.14, -0.001, 1.0)
  • bool: logical values (True, False): behave like ints (True==1, False==0)
  • str: immutable Unicode text ("Dhaka", "Data Science")
x = 10            # int
y = 3.5           # float
name = "Rasel"    # str
is_ready = True   # bool
print(type(x), type(y), type(name), type(is_ready))
<class 'int'> <class 'float'> <class 'str'> <class 'bool'>

Avoid assigning to built-in names such as list, str, sum, and max; doing so hides the corresponding built-in object.

5.1 Strings

  • Strings can use single ' or double " quotes.
a = 'one way of writing a string'
b = "another way"
  • Multi-line strings use triple quotes:
c = """
This is a longer string that
spans multiple lines
"""
print(c)

This is a longer string that
spans multiple lines

Indexing and slicing strings

Positions start at 0. Negative positions count backward from the end.

word = "Python"
print(word[0], word[-1])
print(word[1:4])  # positions 1, 2, 3; stop is excluded
print(len(word))
P n
yth
6

Strings are immutable. An operation such as word.upper() returns a new string.

Cleaning and splitting text

A method is called using object.method(...).

raw_name = "  Ayesha Rahman  "
clean_name = raw_name.strip()
print(clean_name)
print(clean_name.lower())
print(clean_name.replace("Rahman", "Islam"))
print(raw_name)  # original string is unchanged
Ayesha Rahman
ayesha rahman
Ayesha Islam
  Ayesha Rahman  
fields = "Dhaka,25,72.5".split(",")
print(fields)  # a list; studied in the next lecture
print(" | ".join(fields))
print("Dhaka" in "Dhaka, Bangladesh")
['Dhaka', '25', '72.5']
Dhaka | 25 | 72.5
True

strip() removes leading and trailing whitespace. split() separates text; join() combines strings. Use a CSV reader for real CSV files, which may contain quoted commas.

6 Data Types and Operations

  • Types determine what operations are allowed:
    • numeric + numeric → OK
    • string + string → concatenation
    • numeric + string → TypeError
17 + 4.3
21.3
17 + "seventeen"      # raises TypeError (number + string)
"This" + "That"
'ThisThat'

7 Explicit Type Conversion (Type Casting)

  • The type names str, bool, int, and float are callable: use them to convert values to those types:
s = '3.14159'
fval = float(s)       # string → float
type(fval)
float
ival = int(fval)      # float → int (truncates toward zero)
print(ival)
3
bval = bool(ival)     # non-zero → True; zero → False
print(bval)
True
Note

int("3.5") fails; you must convert to float first, then to int if needed.

8 Reading Input

input() always returns a string. Convert it when a calculation requires a number.

Run this example interactively in your notebook:

age = int(input("Enter your age in whole years: "))
print(f"Next year you will be {age + 1}.")

Entering text such as twenty causes a ValueError. We will handle conversion errors later. For reproducible analysis, put known values in code cells or read them from data files instead of repeatedly entering them by hand.

9 The None Type

  • Python provides a special value called None that is used to indicate the absence of a value.
  • The purpose of None is similar to NULL in R
a = None
a is None
True
  • If a function finishes without returning an explicit value, it returns None.
  • Use is None or is not None to check for this value.
  • None is not zero or an empty string. Missing values in NumPy and pandas will need additional conventions.

10 Equality vs Identity

  • == checks whether values are equal.
  • is checks whether two names refer to the same object.
  • Use == for ordinary numeric and string comparisons; use is None for a missing-value sentinel.
  • The next lecture demonstrates object identity with lists, where sharing an object matters.

11 Printing & f-Strings

  • Use print() to display values intentionally.
  • f-strings make formatted strings easy.
name = "Rasel"
score = 83.4567
print(f"Hello, {name}! Your score is {score:.1f}.")
print(f"Score to two decimal places: {score:.2f}")
Hello, Rasel! Your score is 83.5.
Score to two decimal places: 83.46

12 Comments & Help

  • Single-line comment: # this is a comment
  • Built-in help:
help(len)          # opens inline help
Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

13 Augmented Assignment

  • An augmented assignment is a programming shortcut that combines an operation and an assignment into a single statement, making code more concise and often more readable
n = 10
n += 5    # same as n = n + 5
n *= 2
n
30

14 Floating-point Rounding Issue

  • Floating-point numbers inherently experience rounding issues due to the way computers represent real numbers
a = 0.1 + 0.2
a == 0.3, a
(False, 0.30000000000000004)
  • Compare using math.isclose()
import math
math.isclose(a, 0.3)
True

15 Comparison and Logical Operators

  • Used to compare two operands and return a Boolean result (True or False).

  • Comparison operators (similar to R’s symbols):

Meaning Operator
equal to ==
not equal !=
greater / greater-equal >, >=
less / less-equal <, <=
10 <= 15
True
14 != 16
True

  • Chaining is allowed and reads naturally:
x = 3
0 < x < 5, (0 < x and x < 5)
(True, True)
  • Logical operators: and, or, not
(2 < 5) and (10 > 3), (2 > 5) or (10 > 3), not False
(True, True, True)

15.1 Truth values

Zero, None, empty strings, and empty collections are false in a condition. Other ordinary nonempty strings are true, including the string "False".

print(bool(0), bool(""), bool(None))
print(bool("False"), bool(-2))
False False False
True True

For Boolean expressions, and, or, and not express logical operations. More generally, and and or return one of their operands; not returns a Boolean.

16 Exercises

  1. Given a = 17 and b = 5, calculate their quotient, floor quotient, and remainder. Verify a == b * (a // b) + a % b.
  2. Convert temperature = "37.65" to a number and display it to one decimal place using an f-string.
  3. Clean name = " RASEL BISWAS " by removing surrounding spaces and converting to lowercase.
  4. For word = "statistics", obtain its first character, last character, and first four characters.
  5. Read two numbers interactively and print their sum. Explain why adding the two raw input() results would behave differently.
  6. Write an expression checking whether score lies between 0 and 100 inclusive.
  7. Predict bool("0"), bool(0), and bool(""), then check your answers.

17 Summary

  • Use ** for power, not ^.
  • Understand == vs is.
  • Floats are approximate; use math.isclose for comparisons.
  • Practice comparisons, logicals, and f-strings

18 Further reading