Introduction to Problem Solving and
Programming
Gaurav Pareek
The Python programming language
• Created by Guido van Rossum, released in early 1990s
• Companies and organizations that use Python include YouTube, Google, Yahoo,
and NASA
• The Python development consists of:
1. Text editor for creating and modifying the programs
2. Translator for executing the programs
3. Debugger to take control of the program and locate the errors in the
program
• Since Python is interpreted, it provides the ability to execute in an interactive
mode
• Python shell provides this interaction between the programmer and Python
Standard Library
The Python standard library
• A collection of built-in modules , each providing specific functionality beyond
what is included in the “core” part of Python
• For example the math module for addition mathematical functions
import math
math.factorial(4)
• To utilize the capabilities of a given module in a specific program, an import
statement is used
• The syntax for using the factorial function is math.factorial(n)
Python variables and operators
• Variable is a name assigned to a value
• E.g.:
n = 5 variable n is assigned a value 5
• Whenever the variable n appears in calculation, the current (last updated) value
of n is used
• E.g.:
n + 15 (actually 5 + 15 = 20)
n = 10 (last updated value is 10)
n + 20 (actually 10 + 20 = 30)
Python variables and operators (cont’d)
• The common arithmetic operators in Python are + (addition), - (subtraction), *
(multiplication), / (division), and ** (exponentiation)
• E.g.:
n + 5 (adding n with 5)
n – 10 (Subtracting 10 from n)
n/10 (dividing n by 10)
n * 5 (multiplying n by 5)
n**4 (n to the 4th power)
n * (2 + 5) (correct)
n(2+5) (incorrect)
Basic Input and Output in Python
• It is possible to build programs that ask the user to input values and output the
values for the users
• The input function in Python:
name = input('What is your name?: ')
• The statement given above asks the user for an input with message ‘What is
your name?’ and waits till the user inputs something and presses return key
• Whatever the user enters is stored in the variable name
• So, can you predict the output of the following statement?
print(‘Hello ’,name)
• Similarly,
n = 10
m = n + 15
print(m) (prints 25)
Basic Input and Output in Python (cont’d)
• What is the output of the following program? Why?
n = input(‘Enter the value for n’)
m = n + 10
print(m)
• Correction needed:
n = int (input(‘Enter the value for n’))
• Class Exercise: Write a Python program to take principle rate and time from the
user as input and display the simple interest
Data and Expressions
• Large amount of
data is exchanged
over the internet
everyday
• Computations on
data are the
essence of
programming
• Analysis of data
provides you
information
Literals in Python
They are the constant values in a programming language. Types of literals:
1. Numeric literals
– Integers
– Floating point literals
2. String literals
Numeric literals
• Contains only the digits 0–9, an optional sign character ( + or - ), and a possible
decimal point
• A numeric literal containing a decimal point is called floating point literal or
simply float (e.g., 32.35); otherwise it is called a integer literal (e.g., 100)
• Representation of a literal is critical in programming languages because:
– It specifies the range of values that a literal can take
– It specifies the operations permissible on the literal(s)
• There is no limit for representation of integer literals in Python
• This means that an integer literal can take any large value imaginable
• However, floating-point literals are allowed to take values only from a given finite
range
Numeric literals (cont’d)
• Python uses a double-precision standard format (IEEE 754) providing a range of
10-308 to 10308 with 16 to 17 digits of precision
• To denote such a range of values, floating-points can be represented in scientific
notation:
9.0045602e+5 (9.0045602 × 105, 8 digits of precision)
1.006249505236801e8 (1.006249505236801 × 108, 16 digits of
precision)
4.239e-16 (4.239 × 10-16 , 4 digits of precision)
Numeric literals (cont’d)
Question: Why is the range of floating-point literals important to remember?
Answer: Some arithmetic operations may result in arithmetic
overflow/underflow!!
• Compute 1.5e200 * 2.0e210 in your Python Shell
• The expression given above shows you the output inf (infinity)
• This is because the result of this expression exceeds the maximum value allowed
for a floating-point number in Python. This is called arithmetic overflow
• Similarly, arithmetic underflow occurs when the result of computation is smaller
than the minimum value allowed for a floating-point number in Python
Numeric literals (cont’d)
• Similar to the limit on range of values, floats also have a limit on “precision”
(number of digits after the decimal)
• Since any floating-point representation necessarily contains only a finite number
of digits, what is stored for many floating-point values is only an approximation
of the true value
• Experiment by yourself:
>>>1/3
.3333333333333333 (repeating the decimal ends after 16th digit)
>>>1/3 + 1/3 + 1/3 + 1/3 + 1/3 + 1/3
1.9999999999999998 (As a result of the approximation, does not
evaluate to 2)
The format function in Python
• A built-in function to produce a numeric string version of the value containing a
specific number of decimal places
>>>5/7
0.7142857142857143 (usual 16 digits after decimal)
>>>format(5/7, ‘.2f’)
‘0.71’ (Limits output to 2 digits after decimal)
• Here, ‘.2f’ is called a format specifier which rounds the result to two decimal
places of accuracy and prints are the output as a string
• For very small/large values:
>>>format(2 ** 100, '.6e')
'1.267651e+30’ (formats the output in 6 digits after decimal in
scientific representation)
String literals
• String literals or simply strings represent a sequence of characters
• Examples: ‘Smith’ ‘John’ “Hello John”
• In Python, the strings are delimited (surrounded) by using a pair of single quotes
(‘’) or double quotes (“”)
• A string may contain zero or more characters
• An empty string is different from a string containing just a white space
• Work out yourself: How can I print Gaurav’s class using Python
Variables and identifiers
• A variable is a name (identifier) that is associated with a value
• Here, num is a variable that is associated with, or is storing, a value 10
• A variable can be assigned different values during a program’s execution
num = 10
num = num + 1
Variables and identifiers (cont’d)
• Variables may also be assigned to the value of another variable after which two
variables get associated with same literal
• However, updating the value of one variable does not affect the other
Variables and identifiers (cont’d)
• Variables can be assigned values using the keyboard input
>>>name = input('What is your first name?')
What is your first name? John
• Here, the variable name is assigned the string 'John'.
• In case user does not input anything and enters a return symbol, name is
assigned an empty string (‘’)
• All input is returned by the input function as a string type
• Programmer can convert the string type to any numeric choice, if needed
line = input('How many credits do you have?')
num_credits = int(line)
line = input('What is your grade point average?')
gpa = float(line)
Variables and identifiers (cont’d)
Valid and invalid identifiers:
Variables and identifiers (cont’d)
An identifier cannot be same as a predefined identifier in Python
Operators
• Symbol that represents an operation performed on one or more operands
• A unary operator (e.g. unary minus) operates on just one operand and a binary
operator (e.g. addition, multiplication, division etc.) operates on two operands
Expressions and data types
• A combination of operators and operands that evaluates to some value
• Can have a literal or a variable as operand(s)
4 + (3 * k)
• A part of a large expression is also called subexpression
• For example the expression given above consists of (3 * k) and 4
• Also, (3 * k) consists of two subexpressions 3 and k
• Hence we could say that an expression can also contain a single literal or a single
variable
Operator precedence
• The order in which the operators in programming language are applied is called
operator precedence
• In the following operator precedence table, the higher priority operators are
placed above the lower priority ones
Operator associativity
• Addresses the question “What if two operators have the same level of
precedence?”
• Operators like addition and multiplication satisfy the associative law
• For those that do not, operator associativity defines the order in which the
operator is applied
• All operators are left-to-right associative except the exponentiation (**) operator
which is right-to-left associative
Data types
• A data type specifies a set of values, and a set of operators that may be applied
to those values
• For example, the integer data type consists of the set of integers, and operators
for addition, subtraction, multiplication, and division
• Integers, floats and strings are part of a set of a pre-defined data types and are
called built-in types
• Data types prevent the programmer from using values inappropriately in
expressions
• For example, it does not make sense to divide a string by 2
‘Hello’ / 2 (See for yourself what happens if you do this)
Data types (cont’d)
Two approaches to specify data types in a programming language
1. In Static typing, a variable of a certain type before it is used
2. In Dynamic typing, the data type of a variable depends only on the type of value
that the variable is currently holding.
So, the data type of a variable depends only on the type of value that the variable is
currently holding
Is Python a statically typed or dynamically types language?
Mixed-Type expressions
• A mixed-type expression is an expression containing operands of different type
• The CPU can only perform operations on operands of same type
• Hence, conversion of operands to a common type is a must
• Two types of conversion of types:
1. Implicit (automatic) conversion also called coercion
2. Explicit type conversion
Coercion or Implicit type conversion
• Done automatically by the language only if the target type is capable of storing
the value without loss of data
• Assigning 2 to a variable of type float is “safe”
• Assigning 2.5 to an integer type variable is not “safe” as it results in loss of the
decimal digits
Explicit type conversion
• Converts the operands to a specific type even if there is a loss of information
• Python provides built-in functions for explicit type conversion
int () truncates the decimal digits if the operand is a float
float() adds 0 as decimal digit if the operand is an integer
Control Structures
• Control flow is the sequence in which the statements are executed in a program
• Three forms of control:
1. Sequential control: Instructions are executed in the order they are written
2. Selection control: Selectively execute the instructions based on satisfiability
of some condition
3. Iterative control: Repeated execution of a set of instructions until a
condition is satisfied
The conditions in control structures (Boolean Expressions)
• A Boolean data type takes values only from the set {True, False} in Python
• A Boolean expression always evaluates to a Boolean value
• Three categories of operators for Boolean expressions:
1. Relational operators
2. Membership operators
3. Boolean operators
Character representation
• The way the characters are represented within a computer
• Unicode encoding scheme has been accepted universally
• Unicode is actually a collection of different encoding schemes utilizing between 8
and 32 bits for each character
• Python uses 8-bit encoding scheme compatible with ASCII (American Standard
Code for Information Interchange)
ASCII codes for some important characters
Relational operators
• Perform usual comparison operations. Return a Boolean (True or False) result
Relational operators (cont’d)
• Relational operators can be applied to any set of values that has ordering
Membership operators
• Determine if a particular value occurs within a specified list of values
Membership operators (cont’d)
• The sequences (10, 20, 30) and (‘red’, ‘blue’, ‘green’) are called tuples in Python
and are covered in detail later
Boolean operators
• Boolean algebra consists of set of Boolean (logical) operators
• These operators can be combined to form complex Boolean expressions
Boolean operators (cont’d)
Operator precedence and Boolean expressions
• Boolean expressions can contain both mathematical and Boolean operators
• Hence the precedence of all the operators have to be collectively applied
• In the following table operators higher in the table have higher priority
Lazy evaluation of Boolean expressions
• Rule: the second operand of Boolean operators and and or is not evaluated if the
value of the Boolean expression can be determined from the first operand alone.
• Example:
n != 0 and 1/n < 0.5
• If the value of n is zero in the above statement, 1/n is never computed
• This prevents the divide by zero error
Selection control (if statement)
• Provides the programmer with the facility to provide selective execution of
instructions
• Selection control consists of:
1. Different sets of instructions
2. Control statement(s) controlling their execution
The if statement
• Executes a given set of instructions based on the (Boolean) output of the
expression that immediately follows
• The else part in the syntax given above can be omitted
• Write a Python program to convert temperature from both Celsius to Fahrenheit
and Fahrenheit to Celsius depending upon the unit of temperature input by user
The if statement (cont’d)
The if statement (cont’d)
The indentation in Python:
• Usually in a programming language, indentation is used to enhance readability of
the program by aligning the program lines of code
• But Python uses indentation to associate and group statements
• E.g., the if control statement in Python
Indentation in Python
• Statements or block or suite following a header must all be indented the same
amount
• Any number of spaces may be used for an indentation
Multi-way selection
• Nested if statements
• The elif header
Nested if statements
The elif header
• To avoid the complexities of
indentation due to nested if
statements, elif is used
• A single indentation for all the
conditional statements
Programming Exercise
• Write a Python program that takes a month (1,2,…,12) as input from the user and
prints the number of days in the input month
Iterative control
• Provides repeated execution of a set
of statements (body of the loop)
• The control statement (test condition)
determines the number of repetitions
• Iterative control statements are
commonly known as loops
• To summarize, a loop executes a set
of program statements repeatedly
until a condition is satisfied
While statement
• An iterative control statement that repeatedly executes a set of statements
based on a provided Boolean expression (condition)
• Statements in the while loop are executed as long as the condition holds true.
Once the condition becomes false, the iteration terminates and control continues
with the first statement after the while loop
• Python program using while that sums the first n integers:
While statement (cont’d)
• Execution of the program for n = 3
While statement (cont’d)
• Modify the temperature conversion program to check for an invalid unit before
conversion
• Can you guess the output of the following programs?
While statement (cont’d)
• An iterative control structure that never terminates is called an infinite loop
• If the condition of a while loop can never be false, an infinite loop will result
when executed
While statement (cont’d)
• A while loop can be either definite or indefinite
• You can predict the number of iterations before the loop executes in a definite
loop
• The number of times the loops iterates cannot be predicted before its execution
in an indefinite loop
Lists
• One of the natural and useful ways of organizing data is lists
• We tend to make shopping lists, to-do lists, and mental checklists
• Programming languages also provide various forms of lists that can store uniform
or different types of data items
• We consider lists and other data sequences in Python
• A list is a linear data structure , meaning that its elements have a linear ordering
• Each item in the list is identified by its index value starting from the index 0, 1,
2, . . . And so on
• Example:
Characteristics of lists
List operations
Lists (sequences) in Python
• Python list type
A list in Python is a mutable linear data structure, denoted by a comma-separated
list of elements within square brackets, allowing mixed-type elements
• Tuples
A tuple in Python is an immutable linear data structure, denoted by a comma-
separated list of elements within parentheses, allowing mixed-type elements.
• Sequences
In Python, a sequence is a linearly ordered set of elements accessed by index value.
Lists, tuples, and strings are sequence types in Python
Python list type operations
Python tuples operations
• Defined using parentheses instead of square brackets
• In case there is just one element in the tuple, add a comma after the element
• Example: lst = (‘Hello’,)
• An empty tuple is represented by a pair of parentheses
• Operations applicable to lists are applicable to tuples except the ones that alter
the tuple
Sequences operations
• Strings, lists and tuples are all types of sequences
Sequences operations (cont’d)
Nested lists
• Lists and tuples can be nested to create arbitrarily complex data structures
• list of exam grades for each student in a given class,
class_grades = [ [85, 91, 89], [78, 81, 86], [62, 75,
77] ]
• class_grades[0] equals [85, 91, 89], and class_grades[1]
equals [78, 81, 86]
• Hence to access the first exam grade of the first student in the list:
student1_grades = class_grades[0]
student1_exam1 = student1_grades[0]
• For directly accessing the same, class_grades[0][0]
Nested lists (cont’d)
Iterating over lists
• Using loops:
1. While loop
2. For loop
• See programs on how to use while and for loops for iterating over lists
The built in range function
• Used to generate a sequence of integers the loop should iterate over
• Program to calculate the sum of first 10 integers starting from 1,2,…,10
sum = k
for k in range(1, 11):
sum = sum + k
print(sum)
• Program to print all even numbers between 2 and 102, excluding 102:
for k in range(2, 102, 2):
print(k)
• Here, the third argument in the range function specifies the step value of the
iteration as 2
The built in range function (cont’d)
• To print the numbers in reverse order with step value as 2:
for k in range(10, -1, -2):
print(k)
• Using range function to access individual list element:
lst = [1,2,3,4,5]
for k in range(len(lst)):
print(lst[k])
• To print the list in reverse order:
for k in range(len(lst)-1, -1, -1):
print(lst[k])
Assigning and copying lists
• Consider the following python program fragment:
list1 = [10, 20, 30, 40, 50]
list2 = list1
• As a result of the statements given above, both list1 and list2 refer to the
same instance of the list in memory
Assigning and copying lists
• If an element of list1 is changed, then the corresponding element of list2 will
change as well
• Observe the output of the following program:
list1 = [10, 20, 30, 40]
list2 = list1
list1[0] = 5
list1
list2
• Changes in list1 cause changes in list2!!
• To prevent this assign the values as list2 = list(list1)
• change in list1 does NOT cause any change in list2
List comprehensions
• Used to generate more varied sequences