Introduction to
Python Programming
Dr. Vinay Chamola
EEE F411 Internet of Things, BITS-Pilani
1
Languages
Some influential ones:
FORTRAN
science / engineering
COBOL
business data
LISP
logic and AI
BASIC
a simple language
Python
2
Programming basics
code or source code: The sequence of instructions in a program.
syntax: The set of legal structures and commands that can be
used in a particular programming language.
output: The messages printed to the user by a program.
console: The text box onto which output is printed.
Some source code editors pop up the console as an external window,
and others contain their own console window.
3
Compiling and interpreting
Many languages require you to compile (translate) your program
into a form that the machine understands.
compile execute
source code byte code output
Hello.java Hello.class
Python is instead directly interpreted into machine instructions.
interpret
source code output
Hello.py
4
Expressions
expression: A data value or set of operations to compute a value.
Examples: 1 + 4 * 3
42
Arithmetic operators we will use:
+ - * / addition, subtraction/negation, multiplication, division
% modulus, a.k.a. remainder
** exponentiation
precedence: Order in which operations are computed.
* / % ** have a higher precedence than + -
1 + 3 * 4 is 13
Parentheses can be used to force a certain order of evaluation.
(1 + 3) * 4 is 16
5
Real numbers
Python can also manipulate real numbers.
Examples: 6.022 -15.9997 42.0 2.143e17
The operators + - * / % ** ( ) all work for real numbers.
The / produces an exact answer: 15.0 / 2.0 is 7.5
The same rules of precedence also apply to real numbers:
Evaluate ( ) before * / % before + -
When integers and reals are mixed, the result is a real number.
Example: 1 / 2.0 is 0.5
The conversion occurs on a per-operator basis.
7 / 3 * 1.2 + 3 / 2
2 * 1.2 + 3 / 2
2.4 + 3 / 2
2.4 + 1
3.4
6
Math commands
Python has useful commands for performing calculations.
Command name Description Constant Description
abs(value) absolute value e 2.7182818...
ceil(value) rounds up pi 3.1415926...
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root
To use many of these commands, you must write the following at
the top of your Python program:
from math import *
7
Variables
variable: A named piece of memory that can store a value.
Usage:
Compute an expression's result,
store that result into a variable,
and use that variable later in the program.
assignment statement: Stores a value into a variable.
Syntax:
name = value
Examples: x = 5
gpa = 3.14
x 5 gpa 3.14
A variable that has been given a value can be used in expressions.
x + 4 is 9
Exercise: Evaluate the quadratic equation for a given a, b, and c.
(a + b+ c)^2 8
Anaconda prompt
9
Workout
10
print
print : Produces text output on the console.
Syntax:
print (‘Message’)
print (Expression)
Prints the given text message or expression value on the console, and
moves the cursor down to the next line.
print (Item1, Item2, ..., ItemN)
Prints several messages and/or expressions on the same line.
Examples:
print (‘Hello, world!’) ; print (‘Hello’, ‘world’);
age = 30
print "You have", 65 – int(age), "years until retirement"
Output:
Hello, world!
You have 35 years until retirement
11
input
input : Reads a number from user input.
You can assign (store) the result of input into a variable.
Example:
age = input(‘How old are you?‘)
print (‘Your age is’, age)
print (‘You have", 65 – int(age), ‘years until retirement’
Output:
How old are you? 30
Your age is 30
You have 35 years until retirement
Exercise: Write a Python program that prompts the user for
his/her amount of money, then reports how many cars the person
can afford. (car cost: 100000)
12
money= input('how much money do you have')
print('The number of cars you can purchase is',
round(int(money)/100000))
13
Repetition (loops)
and Selection (if/else)
14
The for loop
for loop: Repeats a set of statements over a group of values.
Syntax:
for variableName in groupOfValues:
statements
We indent the statements to be repeated with tabs or spaces.
variableName gives a name to each value, so you can refer to it in the statements.
groupOfValues can be a range of integers, specified with the range function.
Example:
for x in range(1, 6):
print (x, "squared is", x * x)
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
15
for x in range(1, 6):
print (x, "squared is", x * x)
print('I am done')
print('hello')
16
range
The range function specifies a range of integers:
range(start, stop) - the integers between start (inclusive)
and stop (exclusive)
It can also accept a third value specifying the change between values.
range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step
Example:
for x in range(5, 0, -1):
print (x)
print (‘Congratulations’)
Output:
5
4
3
2
1
Congratulations!
Exercise: Print 1 to 10 and then 10 to 1 by one code?
17
Cumulative loops
Some loops incrementally compute a value that is initialized outside
the loop. This is sometimes called a cumulative sum.
sum = 0
for i in range(1, 11):
sum = sum + (i * i)
print (‘sum of first 10 squares is’, sum)
Output:
sum of first 10 squares is 385
Exercise: Write a Python program that computes the factorial of an
integer.
18
if
if statement: Executes a group of statements only if a certain
condition is true. Otherwise, the statements are skipped.
Syntax:
if condition:
statements
Example:
gpa = 3.4
if gpa > 2.0:
print "Your application is accepted."
19
if/else
if/else statement: Executes one block of statements if a certain
condition is True, and a second block of statements if it is False.
Syntax:
if condition:
statements
else:
statements
Example:
cgpa = 6
if cgpa > 4.0:
print (‘Application selected!’)
else:
print (‘Your application is denied.’)
Multiple conditions can be chained with elif ("else if"):
if condition:
statements
elif condition:
statements
else:
statements
20
while
while loop: Executes a group of statements as long as a condition is True.
good for indefinite loops (repeat an unknown number of times)
Syntax:
while condition:
statements
Example:
number = 1
while number < 200:
print (number),
number = number * 2
Output:
1 2 4 8 16 32 64 128
21
Logic
Many logical expressions use relational operators:
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True
Logical expressions can be combined with logical operators:
Operator Example Result
and 9 != 6 and 2 < 3 True
or 2 == 3 or -1 < 5 True
not not 7 > 0 False
Exercise: Write code to display the factors of a number.
22
Text and File Processing
23
Strings
string: A sequence of text characters in a program.
Strings start and end with quotation mark " or apostrophe ' characters.
Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"
A string may not span across multiple lines or contain a " character.
"This is not
a legal String."
"This is not a "legal" String either."
A string can represent characters by preceding them with a backslash.
\t tab character
\n new line character
\" quotation mark character
\\ backslash character
Example: print ("Hello\tthere\nHow are you?“)
24
Indexes
Characters in a string are numbered with indexes starting at 0:
Example:
name = “VChamola"
index 0 1 2 3 4 5 6 7
character V C h a m o l a
Accessing an individual character of a string:
variableName [ index ]
Example:
print name, "starts with", name[0]
Output:
Vchamola starts with V
25
String properties
len(string) - number of characters in a string
(including spaces)
str.lower(string) - lowercase version of a string
str.upper(string) - uppercase version of a string
Exercise: Print your name length and name in uppercase
name = input (‘what is your name’)
length = len(name)
big_name = str.upper(name)
print (length, big_name)
26
Text processing
text processing: Examining, editing, formatting text.
often uses loops that examine the characters of a string one by one
A for loop can examine each character in a string in sequence.
Example:
for c in “sun-moon":
print c
Output:
s
u
n
-
m
o
o
n
27
Strings and numbers
ord(text) - converts a string into a number.
Example: ord("a") is 97, ord("b") is 98, ...
Characters map to numbers using standardized mappings such as
ASCII and Unicode.
chr(number) - converts a number into a string.
Example: chr(99) is "c"
28
Sequence types: Tuples,
Lists, and Strings
Sequence Types
1. Tuple: (‘john’, 32, [CMSC])
A simple immutable ordered sequence of
items
Items can be of mixed types, including
collection types (CMSC = (4,5) )
2. Strings: “John Smith”
Immutable
Conceptually very much like a tuple
3. List: [1, 2, ‘john’, (‘up’, ‘down’)]
Mutable ordered sequence of items of
mixed types
Similar Syntax
All three sequence types (tuples, strings,
and lists) share much of the same syntax
and functionality.
Key difference:
Tuples and strings are immutable
Lists are mutable
The operations shown in this section can
be applied to all sequence types
most examples will just show the
operation performed on one
Sequence Types 1
Define tuples using parentheses and
commas
>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
Define lists are using square brackets
and commas
>>> li = [“abc”, 34, 4.34, 23]
Define strings using quotes (“, ‘, or “““).
>>> st = “Hello World”
>>> st = ‘Hello World’
>>> st = “““This is a multi-line
string that uses triple quotes.”””
Sequence Types 2
Access individual members of a tuple,
list, or string using square bracket
“array” notation
Note that all are 0 based…
>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> tu[1] # Second item in the tuple.
‘abc’
>>> li = [“abc”, 34, 4.34, 23]
>>> li[1] # Second item in the list.
34
>>> st = “Hello World”
>>> st[1] # Second character in string.
‘e’
Positive and negative indices
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
Positive index: count from the left, starting
with 0
>>> t[1]
‘abc’
Negative index: count from right, starting
with –1
>>> t[-3]
4.56
Slicing: return copy of a subset
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
Return a copy of the container with a
subset of the original members. Start
copying at the first index, and stop
copying before second.
>>> t[1:4]
(‘abc’, 4.56, (2,3))
Negative indices count from end
>>> t[1:-1]
(‘abc’, 4.56, (2,3))
Slicing: return copy of a =subset
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
Omit first index to make copy starting
from beginning of the container
>>> t[:2]
(23, ‘abc’)
Omit second index to make copy starting
at first index and going to end
>>> t[2:]
(4.56, (2,3), ‘def’)
Copying the Whole Sequence
[ : ] makes a copy of an entire sequence
>>> t[:]
(23, ‘abc’, 4.56, (2,3), ‘def’)
Note the difference between these two
lines for mutable sequences
>>> l2 = l1 # Both refer to 1 ref,
# changing one affects both
>>> l2 = l1[:] # Independent copies, two refs
Example:
List1= [1,2,3,4,5]
List2= List1
List2[0]= 5
Print (List1)
The ‘in’ Operator
Boolean test whether a value is inside a container:
>>> t = [1, 2, 4, 5]
>>> 3 in t
False
>>> 4 in t
True
>>> 4 not in t
False
For strings, tests for substrings
>>> a = 'abcde'
>>> 'c' in a
True
>>> 'cd' in a
True
>>> 'ac' in a
False
Be careful: the in keyword is also used in the syntax of for loops
and list comprehensions
The + Operator
The + operator produces a new tuple, list, or
string whose value is the concatenation of its
arguments.
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> “Hello” + “ ” + “World”
‘Hello World’
Exercise: List3= List1 + List2
The * Operator
The * operator produces a new tuple, list, or
string that “repeats” the original content.
>>> (1, 2, 3) * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> “Hello” * 3
‘HelloHelloHello’
Mutability:
Tuples vs. Lists
Lists are mutable
>>> li = [‘abc’, 23, 4.34, 23]
>>> li[1] = 45
>>> li
[‘abc’, 45, 4.34, 23]
We can change lists in place.
Name li still points to the same
memory reference when we’re
done.
Tuples are immutable
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> t[2] = 3.14
Error: Can’t assign function call
You can’t change a tuple.
You can make a fresh tuple and assign its
reference to a previously used name.
>>> t = (23, ‘abc’, 3.14, (2,3), ‘def’)
The immutability of tuples means they’re
faster than lists.
Operations on Lists Only
>>> li = [1, 11, 3, 4, 5]
>>> li.append(‘a’) # Note the method syntax
>>> li
[1, 11, 3, 4, 5, ‘a’]
>>> li.insert(2, ‘i’)
>>>li
[1, 11, ‘i’, 3, 4, 5, ‘a’]
The extend method vs +
+ creates a fresh list with a new memory ref
extend operates on list li in place.
>>> li.extend([9, 8, 7])
>>> li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7]
Potentially confusing:
extend takes a list as an argument.
append takes a singleton as an argument.
>>> li.append([10, 11, 12])
>>> li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7, [10, 11, 12]]
Operations on Lists Only
Lists have many methods, including index,
count, remove, reverse, sort
>>> li = [‘a’, ‘b’, ‘c’, ‘b’]
>>> li.index(‘b’) # index of 1st occurrence
1
>>> li.count(‘b’) # number of occurrences
2
>>> li.remove(‘b’) # remove 1st occurrence
>>> li
[‘a’, ‘c’, ‘b’]
Operations on Lists Only
>>> li = [5, 2, 6, 8]
>>> li.reverse() # reverse the list *in place*
>>> li
[8, 6, 2, 5]
>>> li.sort() # sort the list *in place*
>>> li
[2, 5, 6, 8]
>>> li.sort(some_function)
# sort in place using user-defined comparison
Tuple details
The comma is the tuple creation operator, not parens
>>> 1,
(1,)
Python shows parens for clarity (best practice)
>>> (1,)
(1,)
Don't forget the comma!
>>> (1)
1
Empty tuples have a special syntactic form
>>> ()
()
>>> tuple()
()
Summary: Tuples vs. Lists
Lists slower but more powerful than tuples
Lists can be modified, and they have lots of
handy operations and mehtods
Tuples are immutable and have fewer
features
To convert between tuples and lists use the
list() and tuple() functions:
li = list(tu)
tu = tuple(li)
50