Part 2: Objects

Kerry Back, Rice University

Object Types

We have already encountered three types of Python objects:

  • integers (ints) - whole numbers like 10, -5, 0
  • strings - text enclosed in quotes like "hello" or 'world'
  • functions - actions we can perform, like the print function

We can tell the type of any object with the type function.

print(type(10))
print(type("abc"))
print(type(print))
<class 'int'>
<class 'str'>
<class 'builtin_function_or_method'>

Practice: Object Types

Exercise 1 (with Gemini): Ask Gemini to “write Python code that prints the type of the number 3.14”

Exercise 2 (on your own): Type print(type(100)) in a code cell and run it.

Floats

Numbers with decimal points are a different type called floating point objects, or floats.

They require more space in memory to store than integers.

x = 10.0
print(type(x))
<class 'float'>

Practice: Floats

Exercise 1 (with Gemini): Ask Gemini to “write Python code that creates a variable with a decimal number and prints its type”

Exercise 2 (on your own): Type print(5.0 + 3.0) and run it.

Mathematical Operations

Standard mathematical operations work on ints and floats:

  • addition (+)
  • subtraction (-)
  • multiplication (*)
  • exponentiation (**) - note: this is ** in Python, not ^ like in Excel
print("2 * 10.0 =", 2*10.0)
print("3**2 =", 3**2)
2 * 10.0 = 20.0
3**2 = 9

Practice: Math Operations

Exercise 1 (with Gemini): Ask Gemini to “write Python code that calculates 5 to the power of 3”

Exercise 2 (on your own): Type print(8 * 7) and run it.

Division Operations

Python has three types of division operators:

  • division (/) - returns a float
  • floor division (//) - returns the largest integer ≤ result
  • modulo (%) - returns the remainder
print("10 / 3 =", 10 / 3)
print("10 // 3 =", 10 // 3)
print("10 % 3 =", 10 % 3)
10 / 3 = 3.3333333333333335
10 // 3 = 3
10 % 3 = 1

Practice: Division

Exercise 1 (with Gemini): Ask Gemini to “write Python code that shows the remainder when 17 is divided by 5”

Exercise 2 (on your own): Type print(20 // 6) and run it. What is the result?

Strings

Strings are sequences of characters enclosed in quotes.

You can use single or double quotes - just be consistent at the beginning and end.

print("this is a string")
print('this is a string too')
this is a string
this is a string too

We can concatenate (paste) strings together with +:

"abc" + 'xyz'
'abcxyz'

Practice: Strings

Exercise 1 (with Gemini): Ask Gemini to “write Python code that concatenates ‘Hello’ and ‘World’ with a space between them”

Exercise 2 (on your own): Type print("Python" + "!") and run it.

Booleans

Booleans represent True or False values.

Basic comparison operators:

  • > (greater than)
  • < (less than)
  • >= (greater than or equal to)
  • <= (less than or equal to)
  • == (is equal to)

Important: Use two equals signs (==) for comparison. A single = is for assignment.

print(10 > 5)
print(3 == 3)
True
True

Practice: Booleans

Exercise 1 (with Gemini): Ask Gemini to “write Python code that checks if 15 is greater than or equal to 10”

Exercise 2 (on your own): Type print(7 < 5) and run it. Is the result True or False?

Logical Operators

We can combine booleans with logical operators:

  • and - A and B is True only if both are True
  • or - A or B is True if either (or both) is True
A = True
B = False
print("A and B:", A and B)
print("A or B:", A or B)
A and B: False
A or B: True

Practice: Logical Operators

Exercise 1 (with Gemini): Ask Gemini to “write Python code that uses ‘and’ to check if a number is between 10 and 20”

Exercise 2 (on your own): Type print(True or False) and run it.

Type Conversions

Python provides functions to convert between types:

  • int() - converts to integer (truncates, doesn’t round)
  • float() - converts to floating point
  • str() - converts to string
print("int(10.7) =", int(10.7))
print("float(5) =", float(5))
print("str(42) =", str(42))
int(10.7) = 10
float(5) = 5.0
str(42) = 42

Practice: Type Conversions

Exercise 1 (with Gemini): Ask Gemini to “write Python code that converts the string ‘100’ to an integer”

Exercise 2 (on your own): Type print(str(999)) and run it.

Attributes and Methods

Python objects have attributes and methods:

  • An attribute is a value or property of an object
  • A method is a function that belongs to an object

Access them using a period (.) after the object:

object.attribute
object.method()

Strings have many useful methods!

String Methods

Useful string methods:

  • .upper() - converts to uppercase
  • .lower() - converts to lowercase
  • .strip() - removes whitespace from ends
  • .replace(old, new) - replaces text
ticker = 'tsla'
print(ticker.upper())

text = "  hello  "
print(text.strip())

print("hello".replace("l", "x"))
TSLA
hello
hexxo

Practice: String Methods

Exercise 1 (with Gemini): Ask Gemini to “write Python code that converts ‘python programming’ to uppercase”

Exercise 2 (on your own): Type print("hello".replace("h", "j")) and run it.

f-strings

f-strings (formatted strings) let us insert variables into strings.

Syntax: f"text {variable} more text"

age = 25
statement = f'Alice is {age} years old.'
print(statement)
Alice is 25 years old.

Practice: f-strings

Exercise 1 (with Gemini): Ask Gemini to “write Python code using an f-string to print ‘My name is Bob and I am 30 years old’”

Exercise 2 (on your own): Type name = "Sam" then print(f"Hello, {name}!") and run it.

Formatting in f-strings

We can format numbers in f-strings:

  • .2f - floating point with 2 decimal places
  • .0% - convert decimal to percentage
  • :, - add commas to large numbers
pi = 3.14159
print(f'pi to two decimals: {pi:.2f}')

x = 0.25
print(f'as percentage: {x:.0%}')

y = 1000000
print(f'with commas: {y:,}')
pi to two decimals: 3.14
as percentage: 25%
with commas: 1,000,000

Practice: Formatting

Exercise 1 (with Gemini): Ask Gemini to “write Python code that formats the number 0.75 as a percentage”

Exercise 2 (on your own): Type num = 1234567 then print(f'{num:,}') and run it.

Summary

  • Python has different object types: int, float, str, bool, function
  • Objects are like containers that store data
  • Attributes are features of the data
  • Methods are functions that operate on the data
  • Use . notation to access attributes and methods
  • f-strings make it easy to format output

Next up: Lists and more complex data structures!