Number system, Lists, Tuples, Sets, Loops¶
In this lab, we will explore the fundamental concepts of number systems, lists, tuples, sets, and loops in Python programming. These concepts are essential for understanding how to manipulate data and perform various operations in Python.
age = 25
temperature = -10
count = 0
print(f"Integer examples: {age}, {temperature}, {count}")
print(f"Type: {type(age)}")
Integer examples: 25, -10, 0 Type: <class 'int'>
2. Floats - decimal numbers¶
In Python, a float stores real numbers with high precision, similar to the double type in C or C++. It can represent numbers accurately up to about 16 decimal digits.
To avoid confusion, it’s a good habit to write numbers in the form that matches how you want them to be used. For instance, if a variable should behave like a floating-point number, write x = 1.0 instead of x = 1.
If an expression mixes integers and floating-point numbers, Python automatically converts the result to the appropriate type.
x=1
y=1.0
print(type(x),type(y))
<class 'int'> <class 'float'>
price = 19.99
pi = 3.14159
height = 5.8
print(f"\nFloat examples: {price}, {pi}, {height}")
print(f"Type: {type(price)}")
Float examples: 19.99, 3.14159, 5.8 Type: <class 'float'>
3. Basic arithmetic operations¶
a = 10
b = 3
print(f"\nArithmetic operations:")
print(f"Addition: {a} + {b} = {a + b}")
print(f"Subtraction: {a} - {b} = {a - b}")
print(f"Multiplication: {a} * {b} = {a * b}")
print(f"Division: {a} / {b} = {a / b}")
print(f"Floor Division: {a} // {b} = {a // b}")
print(f"Modulo (remainder): {a} % {b} = {a % b}")
print(f"Exponentiation: {a} ** {b} = {a ** b}")
Arithmetic operations: Addition: 10 + 3 = 13 Subtraction: 10 - 3 = 7 Multiplication: 10 * 3 = 30 Division: 10 / 3 = 3.3333333333333335 Floor Division: 10 // 3 = 3 Modulo (remainder): 10 % 3 = 1 Exponentiation: 10 ** 3 = 1000
4. Type conversion¶
str_number = "42"
converted_int = int(str_number)
converted_float = float(str_number)
print(f"\nType conversion:")
print(f"String '{str_number}' to int: {converted_int}, type: {type(converted_int)}")
print(f"String '{str_number}' to float: {converted_float}, type: {type(converted_float)}")
Type conversion: String '42' to int: 42, type: <class 'int'> String '42' to float: 42.0, type: <class 'float'>
If the exponent $n$ in $$ y = x^n $$ is an integer, it is preferable to define $n$ as the integer $3$ rather than the floating--point value $3.0$. Using an integer exponent is computationally faster and more efficient.
import numpy as np
x = np.linspace(0.1, 2.0, 10_000_000)
%timeit x**2
%timeit x**2.0
17.4 ms ± 137 μs per loop (mean ± std. dev. of 7 runs, 100 loops each) 18.1 ms ± 117 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Formatted print¶
Formatted printing in Python allows precise control over how values appear in output—such as alignment, width, precision, and scientific notation. This is particularly useful for numerical computations, tables, and logs.
1. Using f-strings¶
Python f-strings (available from Python 3.6 onwards) provide a clean and readable way to format output.
x = 3.1415926535
n = 42
print(f"x = {x}")
print(f"x = {x:.3f}") # 3 decimal places
print(f"n = {n:6d}") # width 6, right-aligned
print(f"n = {n:<6d}") # left-aligned
print(f"n = {n:^6d}") # centered
x = 3.1415926535 x = 3.142 n = 42 n = 42 n = 42
2. Floating-point Formatting¶
x = 1234.56789
print(f"{x:.2f}") # fixed-point notation
print(f"{x:10.2f}") # width 10, 2 decimal places
print(f"{x:e}") # scientific notation
print(f"{x:.3e}") # scientific, 3 decimal places
1234.57 1234.57 1.234568e+03 1.235e+03
3. Mixing texts and numbers¶
name = "Roop"
score = 7.25
print(f"Student: {name}, Score: {score:.2f}/10")
Student: Roop, Score: 7.25/10
Math Functions¶
The Python core language does not natively provide standard mathematical functions such as sin and cos. These functions are available through additional modules. The math module implements many commonly used mathematical functions and constants.
The module must be imported before use:
import math
Functions and constants are accessed using dot notation:
x = 10.0
z = math.sin(x)
print(z)
-0.5440211108893698
The mathematical constant $\pi$ is available as:
print(math.pi)
3.141592653589793
On import¶
Instead of importing the entire module, we can import all names from a module directly into the current namespace. In that case, functions can be used without prefixing them with math.
from math import *
x = sin(1.5*pi)
However, this style of import is not recommended, since different modules may contain functions with the same name, leading to name conflicts and reduced code clarity.
A better practice is to import only the required functions and constants:
from math import sin, cos, pi
Swapping Variables in Python¶
Swapping means exchanging the values of two variables.
It is a basic operation used while working with variables, lists, and loops.
Method 1: Using a Temporary Variable¶
a=5
b=10
temp = a
a = b
b = temp
print(a, b)
10 5
- Works for all data types
- Clearly shows how values are exchanged
- Useful when swapping elements inside a list
Method 3: Python Multiple Assignment¶
a=10
b=20
a, b = b, a
print(a,b)
20 10
- Python evaluates the right-hand side first
- Values are swapped in a single statement
- Commonly used in practice
Example: Swapping Elements in a List¶
L = [10, 20, 30, 40]
print(L)
i = 0
j = 3
L[i], L[j] = L[j], L[i]
print(L)
[10, 20, 30, 40] [40, 20, 30, 10]
Strings¶
Strings in Python can be created by enclosing characters in single quotes or double quotes.
a, b, c, d = 'Hello', ',', ' ', 'World!'
print(a + b + c + d)
Hello, World!
The addition (+) operator concatenates strings.
Constructing Strings Programmatically¶
To create a string such as log_001.txt, we can combine strings and numbers using explicit type conversion:
base = 'log_'
num = 1
ext = '.txt'
filename = base + str(num).zfill(3) + ext
print(filename)
log_001.txt
Here, str(num) converts the integer to a string, and zfill(3) pads it with leading zeros to ensure a fixed width.
Lists¶
A list is an ordered, mutable collection of elements in Python. Lists are created using square brackets [], and elements can be of any type.
a = [1, 2, 3, 4]
b = [1.0, 2.5, 3.7]
c = ['a', 'b', 'c']
d = [1, 'hello', 3.14]
print(d)
[1, 'hello', 3.14]
Creating Lists with range¶
x = list(range(5))
print(x)
[0, 1, 2, 3, 4]
Accessing Elements¶
List indices start at 0. You can access elements using their index in square brackets.
x = [10, 20, 30, 40]
print(x[0]) # first element
print(x[2]) # third element
print(x[-1]) # last element
10 30 40
Modifying Lists¶
Lists are mutable, meaning their elements can be changed.
x = [1, 2, 3]
x[1] = 10
print(x)
[1, 10, 3]
Common List Operations¶
x = [1, 2, 3]
x.append(4) # add element at the end
print(x)
x.insert(1, 10) # insert at index 1
print(x)
x.remove(2) # remove first occurrence of 2
print(x)
y = x.pop() # remove and return last element
print(x)
[1, 2, 3, 4] [1, 10, 2, 3, 4] [1, 10, 3, 4] [1, 10, 3]
List slicing¶
x = [0, 1, 2, 3, 4, 5]
print(x[1:4]) # elements from index 1 to 3
print(x[:3]) # first three elements
print(x[3:]) # from index 3 to end
[1, 2, 3] [0, 1, 2] [3, 4, 5]
Tuples¶
A tuple is an ordered collection of elements that is immutable, meaning its contents cannot be changed after creation. Tuples are created using parentheses ().
b = (1.0, 'hello', 3.14)
x = (10,2,'x')
print(x)
print(x[0])
print(x[1])
print(x[2])
(10, 2, 'x') 10 2 x
Try to modify some element of a tuple.
x[1] = 0
Sets¶
A set is an unordered collection of unique elements. Sets are useful when the order of elements is unimportant and when duplicate values should be eliminated.
Sets can be created using curly braces {} or the set() constructor.
A = {1, 3, 2, 4, 3}
B = set([2, 3, 4, 5])
print(A)
print(B)
{1, 2, 3, 4}
{2, 3, 4, 5}
Note that duplicate elements are automatically removed.
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B) # union
print(A.union(B)) # union using method
print(A & B) # intersection
print(A - B) # difference
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
{3}
{1, 2}
Membership Testing¶
x = {10, 20, 30}
print(20 in x)
print(40 in x)
True False
Adding and removing elements¶
Adding and removing elements from a set can be done using the add() and remove() methods, respectively.
x = {1, 2, 3}
x.add(4) # add an element
x.remove(2) # remove an element
print(x)
{1, 3, 4}
🔁 Loops in Python: for and while¶
Loops allow us to repeat instructions efficiently.
Python provides two main loop constructs:
forloopwhileloop
1. The for Loop¶
Use a for loop when the number of iterations is known in advance, or when iterating over a collection.
for i in range(5):
print(i)
0 1 2 3 4
range(start, stop, step)¶
start: starting value (default 0)stop: stopping value (excluded)step: increment (default 1)
for i in range(1, 11, 2):
print(i)
1 3 5 7 9
Looping over lists¶
values = [1.0, 2.5, 3.2, 4.8]
for x in values:
print(x, x**2)
1.0 1.0 2.5 6.25 3.2 10.240000000000002 4.8 23.04
Using enumerate¶
names = ["Alice", "Bob", "Charlie"]
for i, name in enumerate(names):
print(i, name)
0 Alice 1 Bob 2 Charlie
Accumulation Pattern (Very Important)¶
This pattern appears in integration, summation, error computation, etc.
total = 0.0
for i in range(1, 6):
total = total + i
total
15.0
2. The while Loop¶
Use a while loop when the loop should continue until a condition is satisfied.
i = 0
while i < 5:
print(i)
i = i + 1
0 1 2 3 4
⚠️ Warning:
If the condition never becomes false, the loop becomes an infinite loop.
Convergence-style loop (scientific computing)¶
x = 1.0
tol = 1e-6
while x > tol:
x = 0.5 * x
print(x)
0.5 0.25 0.125 0.0625 0.03125 0.015625 0.0078125 0.00390625 0.001953125 0.0009765625 0.00048828125 0.000244140625 0.0001220703125 6.103515625e-05 3.0517578125e-05 1.52587890625e-05 7.62939453125e-06 3.814697265625e-06 1.9073486328125e-06 9.5367431640625e-07
3. break and continue¶
for i in range(10):
if i == 6:
break
print(i)
0 1 2 3 4 5
for i in range(6):
if i == 3:
continue
print(i)
0 1 2 4 5
4. Common Mistakes¶
# Infinite loop example (DO NOT RUN)
# while True:
# print("Oops")
Practice Exercises¶
Compute
$\sum_{i=1}^{20} i^2$ using aforloop.Print the first 10 terms of
$x_{n+1} = 0.5 x_n, \quad x_0 = 1$Find the smallest integer
nsuch that
$$1 + 2 + \cdots + n > 100$$Approximate
exp(-x)using repeated multiplication until the value is below1e-8.