Introduction to Programming in Python
1. Learning Objectives
After completing this unit, students should be able to:
Use Python as a calculator.
Perform algebraic and numerical calculations interactively.
Understand variables, expressions and operators.
Use Python's built-in functions and discover functions using help().
Understand default arguments in functions.
Import and use math and cmath modules.
Take input from the keyboard and display output.
Work with strings, lists and tuples.
Use indexing and slicing.
Write simple formula-based programs.
Use if, if-elif-else, for, and while.
Handle simple errors using try-except.
Note: raw_input() belongs to Python 2. In Python 3, the corresponding function is
input(). Since current UG practical work should use Python 3, the examples below use
input().
2. Python as a Number Calculator
Python can be used directly as a calculator in the interactive interpreter.
Basic arithmetic
>>> 10 + 5
15
>>> 10 - 5
5
>>> 10 * 5
50
>>> 10 / 5
2.0
Other arithmetic operators
>>> 17 // 5
3
>>> 17 % 5
2
>>> 2 ** 5
32
Here:
Operator Meaning Example
+ Addition 5 + 3
- Subtraction 5 - 3
* Multiplication 5 * 3
/ Division 5 / 3
// Floor division 5 // 3
% Remainder 5 % 3
** Power 5 ** 3
Exercise
Calculate interactively:
1. 25+37
2. 125−47
3. 12×15
4. 125/8
5. 210
6. The remainder when 157 is divided by 12.
3. Algebraic Calculation Through Python
Python follows the usual mathematical order of operations.
>>> 2 + 3 * 4
14
>>> (2 + 3) * 4
20
Variables can be used to represent algebraic quantities.
>>> a = 5
>>> b = 3
>>> a + b
8
>>> a**2 + b**2
34
>>> (a + b)**2
64
Example: Quadratic expression
For
y=ax2+bx+c
we can write:
>>> a = 2
>>> b = 3
>>> c = 5
>>> x = 4
>>> y = a*x**2 + b*x + c
>>> y
49
Example: Simple physics calculation
Distance travelled under uniform acceleration:
s=ut+1/2at2
u = 10
a = 2
t = 5
s = u*t + 0.5*a*t**2
print(s)
Output:
75.0
4. Built-in Functions and help()
Python provides many built-in functions.
Examples:
>>> abs(-25)
25
>>> round(3.14159, 2)
3.14
>>> max(10, 25, 7)
25
>>> min(10, 25, 7)
7
>>> sum([1, 2, 3, 4])
10
Searching for help
Python's help() function can be used to learn about functions.
>>> help(abs)
You can also use:
>>> help(round)
For a general topic:
>>> help("math")
To see the attributes/functions available in a module:
>>> import math
>>> dir(math)
For example:
>>> help([Link])
This is an important programming habit: students should learn to discover functions
rather than memorising every function.
5. Default Arguments
A function can have a default value for an argument.
For example:
>>> round(3.1415926)
3
The second argument, ndigits, has a default value.
>>> round(3.1415926, 2)
3.14
A simple user-defined example:
def power(x, n=2):
return x**n
Now:
print(power(5))
print(power(5, 3))
Output:
25
125
Here n=2 is the default argument.
6. Importing the math Module
The math module provides mathematical functions.
import math
Examples:
print([Link](25))
print([Link]([Link]/2))
print([Link](0))
print([Link](10))
print([Link](2))
Some useful constants:
print([Link])
print(math.e)
Important functions
Function Meaning
[Link](x) Square root
[Link](x) Sine
[Link](x) Cosine
[Link](x) Tangent
[Link](x) Natural logarithm
math.log10(x) Common logarithm
[Link](x) ex
[Link](n) n!
[Link] π
Example
Find
2+sin4π.
import math
result = [Link](2) + [Link]([Link]/4)
print(result)
7. The cmath Module
cmath is used for calculations involving complex numbers.
import cmath
For example:
z = [Link](-4)
print(z)
Output:
2j
Python uses j to represent the imaginary unit:
j=−1.
Example
z = 3 + 4j
print(z)
print([Link])
print([Link])
print(abs(z))
Output:
(3+4j)
3.0
4.0
5.0
Complex square root
import cmath
print([Link](-9))
Output:
3j
8. Standard Input and Output
print()
print("Hello")
print(25)
Multiple items can be printed:
a = 10
b = 20
print("a =", a, "b =", b)
Formatted output
x = 3.1415926
print(f"x = {x:.2f}")
Output:
x = 3.14
9. Taking Input Using input()
name = input("Enter your name: ")
print("Hello", name)
Importantly, input() returns a string.
Therefore, numerical input must normally be converted.
x = float(input("Enter x: "))
print(x**2)
For an integer:
n = int(input("Enter an integer: "))
print(n**2)
Example
a = float(input("Enter a: "))
b = float(input("Enter b: "))
print("Sum =", a + b)
print("Product =", a * b)
10. Strings
A string is a sequence of characters.
name = "Bidhannagar College"
print(name)
Strings can be indexed.
word = "PYTHON"
print(word[0])
print(word[1])
print(word[-1])
Output:
P
Y
N
Python indexing starts from 0.
String slicing
word = "PYTHON"
print(word[0:3])
print(word[2:5])
print(word[:4])
print(word[2:])
print(word[::-1])
Output:
PYT
THO
PYTH
THON
NOHTYP
Useful string methods
text = "python programming"
print([Link]())
print([Link]())
print([Link]())
print([Link]("python", "Python"))
Other useful methods:
[Link]("program")
[Link]("m")
[Link]("python")
[Link]("ing")
Students can investigate methods using:
help(str)
or:
dir(str)
11. Lists
A list stores multiple values.
marks = [75, 82, 68, 91, 77]
print(marks)
Lists can contain different types:
data = [10, 3.14, "Python", True]
Indexing
print(marks[0])
print(marks[-1])
Slicing
print(marks[1:4])
print(marks[:3])
print(marks[2:])
List methods
[Link](88)
print(marks)
[Link](1, 90)
print(marks)
[Link](68)
print(marks)
[Link]()
print(marks)
Useful methods include:
append()
insert()
remove()
pop()
sort()
reverse()
count()
index()
Students can investigate them using:
help(list)
12. Tuples
A tuple is similar to a list but is immutable.
point = (3, 5)
print(point)
print(point[0])
print(point[1])
Tuple slicing works similarly:
numbers = (10, 20, 30, 40, 50)
print(numbers[1:4])
A tuple cannot normally be modified:
point[0] = 10
This produces an error because tuples are immutable.
List vs Tuple
List Tuple
[1,2,3] (1,2,3)
Mutable Immutable
Can be modified Cannot be modified
More methods Fewer methods
13. Formula-Crunching Programs
Formula-based programs are particularly useful for UG science students.
Example 1: Area of a circle
A=πr2
import math
r = float(input("Enter radius: "))
area = [Link] * r**2
print("Area =", area)
Example 2: Simple interest
I=100PRT
P = float(input("Enter principal: "))
R = float(input("Enter rate: "))
T = float(input("Enter time: "))
I = P*R*T/100
print("Simple Interest =", I)
Example 3: Kinetic energy
K=21mv2
m = float(input("Enter mass: "))
v = float(input("Enter velocity: "))
K = 0.5*m*v**2
print("Kinetic Energy =", K)
Example 4: Einstein's mass-energy relation
E=mc2
c = 3.0e8
m = float(input("Enter mass in kg: "))
E = m*c**2
print("Energy =", E, "J")
14. Control Structures
Control structures determine the flow of execution of a program.
The main structures at this level are:
if
if-else
if-elif-else
for
while
try-except
15. if Statement
x = float(input("Enter x: "))
if x > 0:
print("Positive number")
Notice the indentation.
Python uses indentation to define blocks of code.
16. if-else
n = int(input("Enter an integer: "))
if n % 2 == 0:
print("Even")
else:
print("Odd")
Another example
temperature = float(input("Enter temperature: "))
if temperature > 100:
print("Temperature is above boiling point")
else:
print("Temperature is not above boiling point")
17. if-elif-else
This is useful when there are several possibilities.
marks = float(input("Enter marks: "))
if marks >= 90:
print("Grade A+")
elif marks >= 80:
print("Grade A")
elif marks >= 70:
print("Grade B")
elif marks >= 60:
print("Grade C")
else:
print("Needs improvement")
18. for Loop
A for loop is useful for repeating an operation.
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Sum of first 10 natural numbers
total = 0
for i in range(1, 11):
total = total + i
print("Sum =", total)
19. for Loop with a List
marks = [65, 72, 81, 90, 56]
for mark in marks:
print(mark)
Calculate the average
marks = [65, 72, 81, 90, 56]
total = 0
for mark in marks:
total += mark
average = total / len(marks)
print("Average =", average)
20. while Loop
A while loop repeats as long as a condition remains true.
i = 1
while i <= 5:
print(i)
i += 1
Example: Sum of numbers
n = int(input("Enter n: "))
i = 1
total = 0
while i <= n:
total += i
i += 1
print("Sum =", total)
21. try-except
Programs can encounter errors during execution. try-except allows us to handle some
errors without abruptly terminating the program.
Example
try:
x = float(input("Enter a number: "))
print("Square =", x**2)
except ValueError:
print("Please enter a valid number.")
Division by zero
try:
a = float(input("Enter numerator: "))
b = float(input("Enter denominator: "))
result = a / b
print("Result =", result)
except ZeroDivisionError:
print("Division by zero is not allowed.")
22. Combined Example
The following program combines input, calculation, if-elif-else, try-except and
output.
Temperature conversion
F=59C+32
try:
C = float(input("Enter temperature in Celsius: "))
F = (9/5)*C + 32
print(f"Temperature = {F:.2f} °F")
if C < 0:
print("The temperature is below freezing point.")
elif C == 0:
print("The temperature is at the freezing point.")
else:
print("The temperature is above freezing point.")
except ValueError:
print("Invalid input.")
23. Suggested UG Practical Exercises
The following exercises would be appropriate for an introductory practical class.
A. Python as a calculator
1. Calculate 215.
2. Calculate 2.
3. Calculate the remainder of 12345 divided by 17.
4. Evaluate
23+43+5.
5. Evaluate
sin6π+cos3π.
B. Algebraic/formula calculations
6. Calculate the roots of a quadratic equation.
ax2+bx+c=0.
7. Calculate the distance travelled under uniform acceleration.
s=ut+21at2.
8. Calculate kinetic and potential energy.
K=21mv2,U=mgh.
9. Calculate the wavelength using
λ=ph.
10. Calculate the ideal-gas pressure using
P=VnRT.
C. Strings, lists and tuples
11. Enter a student's name and print it in uppercase.
12. Reverse a string using slicing.
13. Store five marks in a list and calculate the total and average.
14. Find the maximum and minimum marks.
15. Store the Cartesian coordinates of a point as a tuple.
16. Demonstrate the difference between a list and a tuple.
D. Control structures
17. Determine whether an integer is positive, negative or zero.
18. Determine whether an integer is even or odd.
19. Find the largest of three numbers.
20. Print the multiplication table of a number.
21. Calculate n! using a for loop.
22. Calculate n! using a while loop.
23. Find the sum
1+2+3+⋯+n.
24. Print all even numbers from 1 to 100.
25. Print the first 10 terms of the Fibonacci sequence.
E. Error handling
26. Write a program that accepts two numbers and performs division. Handle division by
zero.
27. Write a program that accepts an integer and handles invalid input.
28. Write a simple calculator using try-except.
24. Suggested Mini Practical: Scientific Calculator
As a concluding exercise, students can combine the concepts learned above.
import math
try:
print("1. Square root")
print("2. Sine")
print("3. Cosine")
print("4. Exponential")
print("5. Logarithm")
choice = int(input("Enter your choice: "))
x = float(input("Enter x: "))
if choice == 1:
result = [Link](x)
elif choice == 2:
result = [Link](x)
elif choice == 3:
result = [Link](x)
elif choice == 4:
result = [Link](x)
elif choice == 5:
result = [Link](x)
else:
print("Invalid choice.")
result = None
if result is not None:
print("Result =", result)
except ValueError:
print("Invalid input.")
except Exception as e:
print("Error:", e)
This single exercise gives students practice with:
import
math
variables
input()
print()
type conversion
if-elif-else
try-except
mathematical functions.
25. Recommended Teaching Sequence
For a UG college practical course, I would teach this unit in the following order:
Practical 1: Python interpreter, calculator, variables and operators
↓
Practical 2: Algebraic expressions, built-in functions and help()
↓
Practical 3: math, cmath and scientific calculations
↓
Practical 4: input(), print(), strings and slicing
↓
Practical 5: Lists, tuples and their methods
↓
Practical 6: Formula-based physics/science programs
↓
Practical 7: if, if-else, if-elif-else
↓
Practical 8: for loop
↓
Practical 9: while loop
↓
Practical 10: try-except and integrated programs
This progression is particularly suitable for [Link].-level students who are encountering
programming for the first time, because each practical introduces only a small number of
new programming concepts while reinforcing the previous ones.