
3 Variables, Data Types, and Python Input/Output

3.1 Commenting code
Commenting a code may have several purposes in programming, such as:
Describe what is going to happen in a sequence of code
Document who wrote the code or other ancillary information
Turn off a line of code - perhaps temporarily
3.1.1 Single-line Comments
Use #
before the comment. Everything after #
on the same line is ignored by Python.
#Computing number of hours of lecture in this course
print("Total lecture hours of STAT201=",10*3*(5/6))
Total lecture hours of STAT201= 25.0
3.1.2 Multi-line Comments (for documentation or explanation)
While technically Python doesn’t have multi-line comments, we often use triple-quoted strings for that purpose, especially in function/method docstrings:
"""
This is a multi-line comment.
It's technically a string, but can be used like a comment.
Good for longer explanations.
"""
"\nThis is a multi-line comment.\nIt's technically a string, but can be used like a comment.\nGood for longer explanations.\n"
More commonly, triple quotes are used for docstrings of a function (will be covered in the python function chapter):
def greet(name):
"""
This function takes a name as input
and prints a greeting message.
"""
print("Hello,", name)
You can access these docstrings with:
print(greet.__doc__)
This function takes a name as input
and prints a greeting message.
3.1.3 Practice exercise 1
Which of the following lines is a comment:
#this is a comment
##this may be a comment
A comment#
3.2 Variables
In programming, a variable is a named container that stores information your program can use and manipulate.
Think of a variable like a labeled box where you can put a value (like a number, word, or object), and then refer to that box by its label later in your code. It allows you to store, access, and manipulate data in your program.

3.2.1 Variable Declaration
- You can create a variable by assigning a value to it using the assignment operator
=
.
For example:
= 10
x = "Alice"
name = 3.14
pi = True is_active
Variable Naming Rules:
- Names must start with a letter (a-z, A-Z) or an underscore (_).
- Names can only contain letters, numbers (0-9), and underscores.
- Names are case-sensitive (
name
andName
are different variables). - Reserved keywords (e.g.,
if
,for
,while
) cannot be used as variable names.
There are certain reserved words in python that have some meaning, and cannot be used as variable names. These reserved words are:

Best Practices:
Python style guide: Please refer to the python style guide for best coding practices, such as naming variables, using spaces, tabs, and styling the different components of your code.
For example:
# use descriptive variable names:
= 100 total_price
# use snake_case for variable names
= 25 user_age
3.2.2 Dynamic Typing
Variables in Python are dynamically typed, meaning you don’t need to specify their type when declaring them. The type of a variable is determined by the value assigned to it.
For example:
= 10 # x is an integer
x = x # y is also an integer y
3.2.3 Checking Variable Types
You can use the type()
function to check the type of a variable.
= 10
x print(type(x))
= "Python"
y print(type(y))
<class 'int'>
<class 'str'>
3.2.4 Practice exercise 2
Which of the following variable names are valid?
var.name
var9name
_varname
varname*
Which of the following statements is an assignment statement:
x = 5
print(x)
type(x)
x + 4
3.3 Data types
Python provides several built-in data types for storing different kinds of information in variables. These data types can be broadly categorized into primitive data types and collection (containers) data types. While collection data types will be covered later, this chapter focuses on primitive data types, which are used to represent a single value.
3.3.1 Primitive Data Types
They represent a single value. In Python, primitive data types include:
- String (
str
): A sequence of characters (e.g.,"hello"
,'world'
). - Integer (
int
): Whole numbers (e.g.,10
,-3
). - Floating-point number (
float
): Numbers with decimals (e.g.,3.14
,-2.7
). - Boolean (
bool
): Logical valuesTrue
orFalse
. - None type (
None
): Represents the absence of a value.
3.3.2 Practice exercise 3
What is the datatype of the following objects?
‘This is False’
“This is a number”
1000
65.65
False
3.3.3 Commonly Used Built-in methods associated with each data type
Each data type comes with its own set of built-in methods that help you interact with the data.
3.3.3.1 Strings
Strings are sequences of characters and are immutable in Python.
3.3.3.1.1 Single quotes '
and double quotes "
to define strings
in Python, you can use either single quotes ('
) or double quotes ("
) to define strings. Both are functionally equivalent, and you can choose based on preference or readability. Here’s an example:
# Using single quotes
= 'Hello, world!'
string1 print(string1)
# Using double quotes
= "Hello, world!"
string2 print(string2)
Hello, world!
Hello, world!
When to use one over the other
- Single quotes (
'
) are often preferred for simple strings without embedded quotes. - Double quotes (
"
) are useful when your string contains a single quote, as it avoids the need for escaping:
# Single quote in a double-quoted string
= "It's a beautiful day!"
message print(message)
# Double quote in a single-quoted string
= 'He said, "Hello!"'
message print(message)
It's a beautiful day!
He said, "Hello!"
Escaping quotes: If your string contains both single and double quotes, you can use the backslash (\
) to escape them:
# Escaping single quotes in a single-quoted string
= 'It\'s a sunny day.'
string_with_escape1 print(string_with_escape1)
# Escaping double quotes in a double-quoted string
= "He said, \"Hello!\""
string_with_escape2 print(string_with_escape2)
It's a sunny day.
He said, "Hello!"
You can also use triple quotes ('''
or """
) for strings that span multiple lines or contain both types of quotes without escaping:
= """This string spans
multi_line_string multiple lines and can include 'single quotes' and "double quotes"."""
print(multi_line_string)
This string spans
multiple lines and can include 'single quotes' and "double quotes".
3.3.3.1.2 String Concatenation
- Use the
+
operator to join strings together. - All operands must be strings; otherwise, you’ll get a
TypeError
.
# Basic Concatenation
= "Hello"
greeting = "Alice"
name = greeting + ", " + name + "!"
message print(message)
# Concatenating String Literals
print("Python" + " is " + "fun!")
# Concatenating with Variables
= "Python"
lang = "beginner"
level print("I'm learning " + lang + " as a " + level + " programmer.")
Hello, Alice!
Python is fun!
I'm learning Python as a beginner programmer.
3.3.3.1.3 String Repetition
String repetition is achieved using the *
operator. It creates a new string by repeating an existing string a specified number of times.
# Creating Patterns
print("*" * 10)
**********
= 4
repeat_count print("Python! " * repeat_count)
Python! Python! Python! Python!
Below are Commonly used Methods for strings:
len()
: returns the length of a stringlower()
: returns a string with every letter of the original in lowercaseupper()
: returns a string with every letter of the original in uppercasereplace(x,y)
: returns a string with every occurrence of x replaced by ycount(x)
: counts the number of occurrences of x in the stringindex(x)
: returns the location of the first occurrence of xformat()
: format stringsisalpha()
: returns True if every character of the string is a letter
For a more comprehensive list of string methods, please refer to here
# Example Methods:
= "Hello, World!"
s
# Returns the length of the string
len(s)
print("the length of the string is", len(s))
# Converts string to uppercase
s.upper()print("the string in uppercase is", s.upper())
# Converts string to lowercase
s.lower()print("the string in lowercase is", s.lower())
# Capitalizes the first character of the string
s.capitalize()print("the string with first letter capitalized is", s.capitalize())
# Finds the first occurrence of a substring
"World")
s.find(print("the first occurrence of the substring is at", s.find("World"))
# Replaces a substring with another string
"World", "Python")
s.replace(print("the string after replacement is", s.replace("World", "Python"))
# Splits the string into a list
", ")
s.split(print("the string after splitting is", s.split(", "))
# Strips leading/trailing whitespace
s.strip()print("the string after stripping is", s.strip())
# count the number of occurrences of a substring
"l")
s.count(print("the number of occurrences of the substring is", s.count("l"))
# Checks if the string is alphanumeric
s.isalnum()print("is the string alphanumeric?", s.isalnum())
the length of the string is 13
the string in uppercase is HELLO, WORLD!
the string in lowercase is hello, world!
the string with first letter capitalized is Hello, world!
the first occurrence of the substring is at 7
the string after replacement is Hello, Python!
the string after splitting is ['Hello', 'World!']
the string after stripping is Hello, World!
the number of occurrences of the substring is 3
is the string alphanumeric? False
split()
: By default,.split()
separates a string using any whitespace (spaces, tabs, newlines) and returns a list of words.
= " Hello World "
text text.split()
['Hello', 'World']
= "apple,banana,cherry"
text_3 ",") text_3.split(
['apple', 'banana', 'cherry']
count()
: Returns the number of non-overlapping occurences of a substring in a string. It is case-sensitive
= "the three thieves thought they were thorough"
text
# Count how many times 'th' appears
print(text.count("th"))
# Count how many times 'the' appears
print(text.count("the"))
6
2
For word-level counting, use .split()
or regular expressions
= "The dog and the cat chased the rat."
sentence "the") sentence.lower().split().count(
3
str.startswith()
andstr.endswith()
startswith()
checks is a string begins with the specified substring.
= "hello world"
text
print(text.startswith("hello"))
print(text.startswith("world"))
True
False
endswith()
: Checks if a string ends with the specified substring.
= "hello world"
text
print(text.endswith("world")) # True
print(text.endswith("hello"))
True
False
3.3.3.2 Numerical Data Types
In Python, numerical data includes:
- Integers (
int
): Whole numbers, positive or negative (e.g.,-5
,0
,42
) - Floats (
float
): Numbers with decimal points, used to represent real values (e.g.,3.14
,-0.5
,2.0
)
3.3.4 Common Mathematical Operators
Python provides several operators that can be used in expressions to perform mathematical calculations. Below are the most common ones:
- Exponentiation (
**
): Raises a number to the power of another.- Example:
2 ** 3
results in8
.
- Example:
- Modulo (
%
): Returns the remainder of a division.- Example:
10 % 3
results in1
.
- Example:
- Multiplication (
*
): Multiplies two numbers.- Example:
4 * 5
results in20
.
- Example:
- Division (
/
): Divides one number by another, resulting in a float.- Example:
10 / 2
results in5.0
.
- Example:
- Addition (
+
): Adds two numbers.- Example:
7 + 3
results in10
.
- Example:
- Subtraction (
-
): Subtracts one number from another.- Example:
9 - 4
results in5
.
- Example:
⚠️ Important:
When used with strings: -+
joins strings together.
Example:"Hello" + "World"
→"HelloWorld"
-*
repeats a string.
Example:"ha" * 3
→"hahaha"
These operations do not perform addition or multiplication in the mathematical sense when applied to strings.
3.3.5 Operator Precedence in Python
The operators listed above are in decreasing order of precedence, meaning:
- Exponentiation (
**
) is evaluated first. - Modulo (
%
) is evaluated next. - Multiplication (
*
) follows. - Division (
/
), if present, has the same precedence as multiplication. - Addition (
+
) and Subtraction (-
) are evaluated last, from left to right.
3.3.5.1 Example: Precedence in Action
Consider the expression: 2 + 3 % 4 * 2
To evaluate this, Python follows the precedence rules:
- Modulo (
%
) is evaluated first:
3 % 4
3
Multiplication (*
) is evaluated next:
3 * 2
6
Addition (+
) is evaluated last:
2+6
8
Thus, the result of the expression 2 + 3 % 4 * 2
is 8
.
3.3.5.2 Key Takeaways
- Precedence determines the order in which operations are performed in an expression.
- Parentheses
()
can be used to override the default precedence and control the order of evaluation.
= (2 + 3) % (4 * 2)
result print(result)
5
3.3.6 Practice exercise 4
What will be the result of the following expression:
1%2**3*2+1
The formula for computing final amount if one is earning compund interest is given by: \[A = P\bigg(1+\frac{r}{n}\bigg)^{nt},\]
where:
P = Principal amount (initial investment),
r = annual nominal interest rate,
n = number of times the interest is computed per year,
t = number of years
Write a Python program that assigns the principal amount of $10000 to variable P, assign to n the value 12, and assign to r the interest rate of 8%. Then have the program prompt the user for the number of years t that the money will be compounded for. Calculate and print the final amount after t years.
What is the amount if the user enters t as 4 years?
3.3.6.1 Booleans
Booleans represent logical values True
or False
.
They are commonly used to control the flow of a program through conditional statements such as if
, elif
, and while
.
= True
is_valid if is_valid:
print("The value is valid")
The value is valid
3.4 print()
function in python
The print()
function is a fundamental tool for displaying information.
3.4.1 Basic Usage
# Printing a simple string
print("Hello, World!")
Hello, World!
# Printing a string with a number
print ("The total number of seconds in a day is", 24*60*60)
The total number of seconds in a day is 86400
# combine multiple strings using the + operator
print("Hello, " + "World!")
Hello, World!
3.4.2 Handling special characters in print()
Sometimes, you need to print strings with quotes, backslashes, or other special characters that are not displayed directly in output.
3.4.2.1 Method 1: Use backslashes \
to escape quotes or other special characters
print("He said, \"Hello, World!\"")
He said, "Hello, World!"
3.4.2.2 Method 2: Use raw strings (prefix the string with an r
) to avoid the need for escaping backslashes
print(r"C:\Users\Alice\Documents")
C:\Users\Alice\Documents
3.4.3 Concatenating strings and variables/expressions in print()
function
3.4.3.1 Using f-Strings (Formatted String Literals)
f-strings provide a concise way to embed expressions inside strings. Introduced in Python 3.6, they improve readability and efficiency.
3.4.3.2 Syntax
- Use
f
orF
before the string. - Embed variables or expressions in
{}
.
# Example 1: Basic Variable Substitution
= "Alice"
name = 30
age print(f"My name is {name} and I am {age} years old.")
# Example 2: Arithmetic Expressions
= 10
a = 5
b print(f"The sum of {a} and {b} is {a + b}.")
# Example 3: Formatting Numbers
= 3.14159
pi print(f"Pi rounded to 2 decimal places is {pi:.2f}.")
print(f"Pi rounded to 2 decimal places is {pi:.0f}.")
My name is Alice and I am 30 years old.
The sum of 10 and 5 is 15.
Pi rounded to 2 decimal places is 3.14.
Pi rounded to 2 decimal places is 3.
= 123456789
value print(f"Rounded With commas: ${value:,}")
Rounded With commas: $123,456,789
3.4.3.3 Using str.format()
Method
The str.format()
method allows you to format strings by placing placeholders {}
in the string and replacing them with variables or values.
"Your text here {}".format(variable_or_expression)
# Example 1: Basic Variable Substitution
= "Bob"
name = 25
age print("My name is {} and I am {} years old.".format(name, age))
# Example 2: Using Positional Arguments
print("The sum of {0} and {1} is {2}.".format(a, b, a + b))
# Example 3: Using Keyword Arguments
print("Pi rounded to 2 decimal places is {value:.2f}.".format(value=pi))
print("Pi rounded to 2 decimal places is {value:.0f}.".format(value=pi))
My name is Bob and I am 25 years old.
The sum of 10 and 5 is 15.
Pi rounded to 2 decimal places is 3.14.
Pi rounded to 2 decimal places is 3.
3.4.4 Customizing output formatting
The print()
function in Python is highly customizable. By default, it adds a newline character (\n
) at the end of each output and separates multiple arguments with a space (). However, these default behaviors can be changed using the
end
and sep
parameters.
3.4.4.1 Default Behavior of print()
When you call print()
multiple times, each statement starts on a new line:
print("Hello")
print("World") # this is printed on a new line
Hello
World
3.4.4.2 Changing the end
Parameter
To avoid automatic line breaks and control what is appended at the end of the output, use the end
parameter.
print("Hello", end=" ")
print("World") # this is printed on the same line
Hello World
print("Loading", end="...")
print("Complete")
Loading...Complete
print("Line 1", end="")
print("Line 2")
Line 1Line 2
3.4.4.3 Changing the sep
Parameter
When printing multiple arguments, the default separator between them is a space. You can change this behavior using the sep
parameter.
print("apple", "banana", "cherry", sep=", ")
# Output: apple, banana, cherry
apple, banana, cherry
print("A", "B", "C", sep="")
ABC
print("python", "java", "c++", sep="\n")
python
java
c++
3.4.4.4 Combining end
and sep
Both end
and sep
can be used together for more control:
print("1", "2", "3", sep="-", end=".")
print(" Done!")
1-2-3. Done!
3.4.4.5 Takeaway:
- The
end
parameter changes what is appended at the end of the output (default:\n
). - The
sep
parameter modifies how multiple arguments are separated (default: space). - Both can be combined to create customized output formatting.
3.4.5 Practice exercise 5
Use the print()
function to:
- Display your name, age, and favorite hobby.
- Format the output neatly using f-strings.
- Use
sep
andend
to produce this output:apple:banana:cherry
.
3.5 Expressions
An expression is any combination of values, variables, operators, and function calls that Python can evaluate (i.e., compute) to produce another value.
for example:
= 4
x = 5
y
2 + 3 # ➝ 5 (an expression)
* (y + 1) # ➝ depends on x and y (still an expression) x
24
💡 In short: An expression is something that evaluates to a value.
3.6 Converting data types in Python
3.6.1 Why Convert Data Types in Python?
Data type conversion is essential in Python for several reasons:
Compatibility: Some operations or functions require specific data types to work correctly.
- Example: Performing arithmetic operations like addition or multiplication requires numeric types such as int or float. If the input is in another type, such as a string, it must be converted first.
# Example: Converting strings to numbers
= "19.99"
price = 0.07
tax = float(price) * (1 + tax) # Convert string to float
total_price print(total_price) # Output: 21.3893
21.3893
- Data Processing: When working with input data (e.g., user input, etc), the data may need to be converted to the appropriate type for further analysis.
Example: Converting strings to numbers to perform calculations
# Example: Arithmetic requires numeric types
= "42"
num_str = int(num_str) + 10 # Converts the string "42" to integer
result print(result) # Output: 52
52
- Error Prevention: Converting data types ensures consistency and prevents runtime errors caused by type mismatches.
# Example: Avoiding type mismatch errors
= 25
age = "Your age is " + str(age) # Convert integer to string for concatenation
message print(message) # Output: "Your age is 25"
Your age is 25
3.6.2 How to Convert Data Types in Python
Python provides several built-in functions for type conversion.
Common Conversion Functions:
Function | Description | Example |
---|---|---|
int() |
Converts to an integer (from float or string) | int("42") → 42 |
float() |
Converts to a float | float("3.14") → 3.14 |
str() |
Converts to a string | str(42) → "42" |
bool() |
Converts to a boolean | bool(1) → True |
3.6.3 Boolean conversion
In Python, you can convert values to True
or False
using the built-in bool()
function.
The conversion follows these general rules:
- Falsy values (converted to
False
):None
False
0
,0.0
''
(empty string)[]
(empty list),{}
(empty dict),set()
, etc.
- Truthy values (converted to
True
):
Anything not falsy, like:- Non-zero numbers:
1
,-5
,3.14
- Non-empty strings:
"hello"
- Non-empty collections:
[1]
,{'a': 1}
, etc.
- Non-zero numbers:
print(bool(0)) # Output: False
print(bool("")) # Output: False
print(bool("hello")) # Output: True
print(bool([1, 2])) # Output: True
False
False
True
True
3.6.4 Converting between numeric types
You can convert between integers and floating-point numbers. When converting from an integer to a float, Python implicitly adds the decimal point (.0). When converting from a float to an integer, Python truncates the decimal portion (removes the digits after the decimal point).
# Integer to float
= 42
x = float(x) # Converts int to float
y print(y) # Output: 42.0
# Float to integer (truncating the decimal part)
= 42.99
x = int(x) # Converts float to int (truncating the decimal part)
y print(y) # Output: 42
42.0
42
3.7 User input
Python’s built-in input()
function is used to take input from the user during program execution. It reads a line of text entered by the user and returns it as a string.
= input("What is your name? ")
name print(f"Hello, {name}!")
Hello, lizhen!
3.7.0.1 🔤 Important:
- The
input()
is always returned as a string, even if the user enters a number. - You can convert the input to other types (e.g.,
int
,float
) using type conversion functions. - The program execution pauses until the user provides input.
Examples
# To take numeric input, you need to convert the string to an appropriate data type:
= int(input("Enter your age: "))
age print(f"You will be {age + 1} years old next year.")
# input for calculating the area of a circle
= float(input("Enter the radius of the circle: "))
radius = 3.14 * radius ** 2
area print(f"The area of the circle is {area}")
3.7.1 Practice exercise 6
Ask the user to input their year of birth, and print their age.
3.8 Errors and Exceptions
Errors and Exceptions are common while writing and executing Python code.
3.8.1 Syntax errors
Syntax errors occur if the code is written in a way that it does not comply with the rules / standards / laws of the language (python in this case). It occur when the Python parser encounters invalid syntax.
For example, suppose a values is assigned to a variable as follows:
9value = 2
The above code when executed will indicate a syntax error as it violates the rule that a variable name must not start with a number.
# another example
print("Hello World"
Solution: Fix the syntax issue by ensuring correct punctuation or structure.
3.8.2 Exceptions
Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal:
Exceptions come in different types, and the type is printed as part of the message: below are the common ones:
- Using a local or global variables that is not defined prior
- Attempts to perform operations (such as math operations) on data of the wrong type (ex. attempting to subtract two variables that hold string values)
- Dividing by zero
- Attempts to use a type conversion function such as
int
on a value that can’t be converted to anint
For example, suppose a number is multipled as follws:
= misy * 4 multiplication_result
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[29], line 1 ----> 1 multiplication_result = misy * 4 NameError: name 'misy' is not defined
The above code is syntactically correct. However, it will generate an error as the variable misy
has not been defined as a number.
# Raised when a function receives an argument of the right type but inappropriate value.
int("abc")
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[25], line 1 ----> 1 int("abc") ValueError: invalid literal for int() with base 10: 'abc'
# raised when an operation is applied to an object of inappropriate type.
int("hello")
print("2" + 3)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[24], line 1 ----> 1 print("2" + 3) TypeError: can only concatenate str (not "int") to str
# zero division error
# raised when the second argument of a division or modulo operation is zero.
print(10 / 0)
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) Cell In[27], line 1 ----> 1 print(10 / 0) ZeroDivisionError: division by zero
3.8.3 Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
If we suspect that some lines of code may produce an error, we can put them in a try
block, and if an error does occur, we can use the except
block to instead execute an alternative piece of code. This way the program will not stop if an error occurs within the try
block, and instead will be directed to execute the code within the except
block.
These exceptions can be handled Using the Try-Except Blocks
try:
print(10 / 0)
except:
print("Cannot divide by zero!")
Cannot divide by zero!
Since the try
block raises an error, the except
block will be executed. Without the try
block, the program will crash and raise an error:
The finally
block, if specified, will be executed regardless if the try block raises an error or not.
try:
print(10 / 0)
except:
print("Cannot divide by zero!")
finally:
print("This will always execute.")
Cannot divide by zero!
This will always execute.
3.8.4 Practice exercise 7
Suppose we wish to compute tax using the income and the tax rate. Identify the type of error from amongst syntax error, semantic error and run-time error in the following pieces of code.
= 2000
income = .08 * Income
tax print("tax on", income, "is:", tax)
= 2000
income = .08 x income
tax print("tax on", income, "is:", tax)
Cell In[1], line 2 tax = .08 x income ^ SyntaxError: invalid syntax
= 2000
income = .08 ** income
tax print("tax on", income, "is:", tax)
tax on 2000 is: 0.0
3.8.5 Practice exercise 8
Input an integer from the user. If the user inputs a valid integer, print whether it is a multiple of 3. However, if the user does not input a valid integer, print a message saying that the input is invalid.
= input("Enter an integer:")
num
#The code lines within the 'try' block will execute as long as they run without error
try:
#Converting the input to integer, as user input is a string
= int(num)
num_int
#checking if the integer is a multiple of 3
if num_int % 3 == 0:
print("Number is a multiple of 3")
else:
print("Number is not a multiple of 3")
#The code lines within the 'except' block will execute only if the code lines within the 'try' block throw an error
except:
print("Input must be an integer")
Input must be an integer
3.8.6 Semantic errors (bugs)
Semantic errors occur when the code executes without an error being indicated by the compiler. However, it does not work as inteded by the user. For example, consider the following code of mutiplying the number 6 by 3:
= '6'
x * 3 x
'666'
If it was intended to multiply the number 6, then the variable x
should have been defined as x=6
so that x
has a value of type integer
. However, in the above code 6
is a string
type value. When a string
is multiplied by an integer, say n, it concatenates with itself n times.