Computer Science•Chapter 2•3 min read

Python — Names, Types, Strings & Conversion

O
OIYO EditorialContributor
2/8

Basic Data Types

Assignment binds a name to an object; objects have types. Rebinding a name does not modify its previous object. Dynamic typing does not automatically make incompatible operations valid. See the execution model.

items = [1]
alias = items
items.append(2)
print(alias)
items = [9]
print(alias)
print(items)

Output:

[1, 2]
[1, 2]
[9]

Identifiers permit certain Unicode letters, not only ASCII letters; digits cannot be first and keywords cannot be ordinary variable names. Naming conventions are not syntax requirements. Integer precision is not fixed to one machine word, but memory and conversion limits still exist. Floats approximate many decimal fractions: rounding a display does not change that representation. Compare with an appropriate tolerance when the contract permits one, rather than relying on 0.1 + 0.2 == 0.3.

# Integer
age = 25
count = -3

# Float
pi = 3.14159
temperature = -2.5

# String
name = "Alice"
greeting = 'Hello, World!'

# Boolean
is_student = True
is_raining = False

# Check types
print(type(age))        # <class 'int'>
print(type(pi))         # <class 'float'>
print(type(name))       # <class 'str'>

Operators

# Arithmetic
print(10 + 3)   # 13
print(10 - 3)   # 7
print(10 * 3)   # 30
print(10 / 3)   # 3.333...
print(10 // 3)  # 3  (floor division)
print(10 % 3)   # 1  (modulo)
print(10 ** 2)  # 100 (exponentiation)

# Comparison
print(5 > 3)    # True
print(5 == 5)   # True
print(5 != 4)   # True

# Logical
print(True and False)  # False
print(True or False)   # True
print(not True)        # False

First Program: Temperature Converter

input() returns text and conversion can fail. This example assumes a valid numeric entry; Chapter 6 reviews exception handling. The supplied helper function is reviewed in Chapter 4.

def celsius_to_fahrenheit(celsius):
    fahrenheit = (celsius * 9/5) + 32
    return fahrenheit

temp_c = float(input("Enter temperature in Celsius: "))
temp_f = celsius_to_fahrenheit(temp_c)
print(f"{temp_c}°C = {temp_f:.1f}°F")

Strings and conversion

name = "Alice"
print(name[0])
print(name[1:4])
print(f"Hello, {name}")
print("10" + "2")
print(int("10") + 2)

Output:

A
lic
Hello, Alice
102
12

Strings are immutable; strip() returns a result instead of editing the original. int("3.5") raises ValueError rather than rounding. Assignment operators, slicing and formatting work with the resulting objects, not with an untyped memory box. Use conversion according to the input contract rather than assuming every string is numeric.


Chapter 3 Preview

Next: Conditions, Loops & Iteration.

O

OIYO Editorial

Editorial Desk

The OIYO editorial desk researches money, law, lifestyle, and self-understanding topics against primary sources and public statistics. Every piece carries source notes and is reviewed on a regular cycle for accuracy and usefulness.