Chapter 1
Introduction to
1
(c) Bharadwaj V Dept of ECE NUS (2023)
Introduction to
Environment: Several platforms available!
Integrated development and learning environment (IDLE):
An environment that allows you to Edit, Run, and
Debug your program!
“Anaconda” – A comprehensive platform that gives
you most modules you need, an IDLE, and other
choices for editing and running your python
programs!
Downside? - A full installation may consume more
memory!
(c) Bharadwaj V Dept of ECE NUS (2023) 2
Why & Where all Python is popular?
• Scientific applications – Large-scale data
processing (Machine learning, developing
analytics, etc)
• Financial applications
• Medical data processing
• Statistical data processing
• 2D & 3D Visualization – all applications
(c) Bharadwaj V Dept of ECE NUS (2023) 3
Let’s get started! We will use
Python 3.5 and
How to name your variables?
above
• Alphabets: 'a'-'z' or 'A'-'Z' or '_'
• Alphabets and numbers can be mixed but a
variable cannot begin with a number
• Contain only alphanumeric characters or '_'
• Case sensitive – Apple is different from aPple
• Must avoid all the reserved keywords e.g. if, else,
while, for, with, etc
– Convention: words separated by '_' and not with a
blank space! E.g., HDB_blk
(c) Bharadwaj V Dept of ECE NUS (2023) 4
Data types
Type Example
Integer -8, 245, -12300
Float 1.414, -2.009, 7.0, 0.00025
Boolean True, False
String “Python” , ‘My name is Samantha’
Observe: Single/double quotes
(c) Bharadwaj V Dept of ECE NUS (2023) 5
Using your variables!
On the prompt try this!
>>> x = 25
>>> myname = ‘BV’
How do I know what type of data my variable is
storing?
Use the built-in type() function
>>> type(x) Output: >>> <class 'int'>
>>> type(myname) Output: >>> <class ’str'>
(c) Bharadwaj V Dept of ECE NUS (2023) 6
Data type conversions
We can convert from one data type to other!
• >>> str(95)
Output: >>> ’95'
• >>> float(’0.54’)
Output: >>> 0.54
• >>> int(101.5)
Output: >>> 101
• >>> int(‘weight’)
Output: >>> ValueError! 7
(c) Bharadwaj V Dept of ECE NUS (2023)
Using your variables and writing simple
expressions
>>> x = 12 // Assignment operator = Tutorial 1.1
>>> y = 10
>>> z = x+y Output: >>> ? [You will not see anything as you have
not printed it yet!]
>>> print(z) Output: >>> 22 [print() is a built-in function in
python – we will see details of this function later ]
Earlier values will be remembered by the system until you
exit out of the shell! Try it out!
>> print(z+x) Output: >>> ?
(c) Bharadwaj V Dept of ECE NUS (2023) 8
Writing simple arithmetic expressions
Arithmetic operators: {+ - * /} {% // **}
Try this out now! Tutorial 1.2
>>> x = 11
>>> y = 2
>>> print (x+y)
>>> print(x/y)
>>> print(x // y) From the outputs, what do you infer?
>>> print(x%y)
>>> print(x**2)
(c) Bharadwaj V Dept of ECE NUS (2023) 9
Other Operators
Boolean type statements:
Examples: 1 > 17 is false; 16 > 10.3 is true
Comparison Operators:
> >= < <= == !=
Assignment Operators:
= += -= *= /= //= **= %=
Logical Operators: Pay attention in the lecture
session for examples!
and or not (c) Bharadwaj V Dept of ECE NUS (2023) 10
Logical operations
Python 3.x: True: 1; False: 0
Thus:
• >>> True or False
True An expression A or B is True
if either A or B is True
• >>> True and False
False An expression A and B is True
if both A and B are True
• >>> not False
True An expression is not a True
if A is not True
(c) Bharadwaj V Dept of ECE NUS (2023) 11
• Try out these exercises! Tutorial 1.3
x = 10 x = 23
y=5 y %= x+y
x >=y x != y+20
(x < y*5) and (x/5 >=2)
a, b, c = 10, 20, 30
x += y
a, b, c = c, b, a
print(x) print(a, b, c)
(x < ‘a’’)
(c) Bharadwaj V Dept of ECE NUS (2023) 12
Operator precedence
Operators with the
highest precedence
at the top and
lowest at the
bottom.
Associativity is the
order in which
Python evaluates
an expression
containing multiple
operators
Almost all
operators
except the
exponent (**)
support the
left-to-right
associativity.
(c) Bharadwaj V Dept of ECE NUS (2023) 13
Arithmetic operators precedence
9/3*(2+3) Tutorial 1.4
print(4 * 7 % 3) // the product (*) and the modulus (%)
have the same precedence. So, if both appear in an
expression, then the left one will get evaluated first.
print(4 * (7 % 3)) // L to R assoc; check for the above
print(4 ** 2 ** 2) // R to L assoc.
print((4 ** 2) ** 2) // check for the above
(c) Bharadwaj V Dept of ECE NUS (2023) 14
Writing mathematical
expressions/formulae
• Python math module has a range of
mathematical functions.
You must import math module in your program to
use these functions!
>>> import math
>>> x=23
>>> print (math.sqrt(x))
>>> x = x+ math.sqrt(x)
(c) Bharadwaj V Dept of ECE NUS (2023) 15
Mathematical expressions (Cont’d)
Tutorial 1.5
• Try coding these formulae!
(1) Determine the real roots of a quadratic
equation;
(2) Evaluate the following polynomial:
x=4
Y = 5x3+3x2+2x+2
(c) Bharadwaj V Dept of ECE NUS (2023) 16
Input/Output in Python
• Assigning values to variables and using them is
straightforward!
• User inputs ?
In Python 3.x you can use the input() function to read
data from the user:
> input()
After receiving a value/string, you can store them into a
variable.
(c) Bharadwaj V Dept of ECE NUS (2023) 17
Input/Output (Cont’d)
Note: Whatever you enter as input, the input function
converts it into a string. If you enter an integer value still
input() function convert it into a string.
You need to do an explicit conversion into an integer in your
code.
Tutorial 1.6
name = input(‘What is your name? ‘)
Print the user input value and check its type
weight= int(input(‘What is your weight? ‘))
Print the user input value and check its type
Q: How do you accept a float value?
(c) Bharadwaj V Dept of ECE NUS (2023) 18
Input/Output (Cont’d)
In Python 3.x, it is straightforward to print anything! Use
print() built-in function!
>>> x = 10 >>> y = 3.45678
>>> print(x,y) # see the output!
But how do you control towards getting your required
precision? [Output formatting ]
We can use python built-in methods in “math” to
truncate, finding ceil and floor of a float number;
We can use %, format() and round() methods to control
precision of a float number. See an example in the next
slide.
(c) Bharadwaj V Dept of ECE NUS (2023) 19
Printing – General format - String modulo
operator(%)
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
Output: The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
Output: The value of x is 12.3457
Format - print(‘ STRING HERE with format specs’
%corresponding variables in the same order)
>>> print(’ The value of x is %3.2f ' %x)
(c) Bharadwaj V Dept of ECE NUS (2023) 20
Print int, float and strings using all types of
formats. Follow the demo during the lecture.
Tutorial 1.7
(c) Bharadwaj V Dept of ECE NUS (2023) 21
String processing in Python
• Creating a string
mystring = ’PythoN’ // observe singles quotes
>>> print(mystring)
Two important operations:
• Can I access individual characters in a string?
• Slicing (using slicing operator : )
Indices ordering : 0 1 2 3 4 5
P y t h o N
Indices ordering : -5 -4 -3 -2 -1
(c) Bharadwaj V Dept of ECE NUS (2023) 22
String processing in Python
Individual chars of a string can be accessed using
the method of Indexing: >>>print(mystring[0])
To access a range of characters in the string,
method of slicing is used.
Slicing is done by using a slicing operator (colon :).
Indexing allows negative address references to
access characters from the back of the string,
P y t h o N
Indices ordering : 0 1 2 3 4 5
-5 -4 -3 -2 -1
23
(c) Bharadwaj V Dept of ECE NUS (2023)
String processing in Python
• There is a third, optional index used in slicing: step. If the
step is two, we advance two places after an element is
copied. So we can skip over elements. [start:stop: step]
Example: Starting at 0 and continuing until end, print every
other char.
Starting index 8th element in the string
mystring= ‘AaBbCcDdEe’
>>> mystring[3:8] will print as – ‘bCcDd’
Using slicing try printing: ‘CcDdE’, ‘e’, ‘A’
print(mystring[::2]) # step size is 2 here
Remember! Given_string[ start index : stop at kth element : step size]
Note that your printing is always from left to right elements!
If you want from R to L, use negative steps – reverse direction!
(c) Bharadwaj V Dept of ECE NUS (2023) 24
String processing in Python
Tutorial 1.8
Try this exercise!
String1 = "Python_is_Awesome!"
print("Initial String: ")
print(String1)
• Print the First & the Last characters
• Slicing: Print the characters from 3rd to 17th character
• Slicing: Printing characters between 3rd and 2nd last
character
• Slicing: Slice from start to fourth index.
• Slice from second index to end.
Note: First index is 0, 2nd index is 1, and so on.
(c) Bharadwaj V Dept of ECE NUS (2023) 25
String processing in Python
>>> x = ‘ba’
>>> y = ‘ba’
>>> print(x+t) Output: >>> baba
>>> z = x + ‘na’*2
>>> print(z) Output: >>> banana
You can check if a char is there in your string!
>>> ‘p’ in x // in is a membership operator!
False
>>> ‘bananab’ > z # Lexicographical comparison
True
>>> ‘m’ < z
False (c) Bharadwaj V Dept of ECE NUS (2023) 26
Some useful String
methods in Python
Start to explore these following useful string methods. Use a
string “Avada Kedavra” and try to play with the following
methods! Print and see the results!
• len(your_string_here) Tutorial 1.9
• your_string_here.lower() // try .upper() too!
• your_string_here.count() // read about count() and use
• your_string_here.capitalize()
• your_string_here.index(single character here for which you need the
index)
• your_string_here.replace(‘character to be replaced’, ‘char that will
replace’)
Explore more methods on your own! More the easier &
merrier!!
(c) Bharadwaj V Dept of ECE NUS (2023) 27
DIY! (No solutions will be provided. You need to start
to become a pro!! Start to “search” and identify the
methods and use them! )
• Consider three strings - “Python” , “is” ,
“addictive”. Remove the first character in each
string and print.
• Consider a string - “Python is addictive”.
Remove the first character from each word of
the above string and print!
(c) Bharadwaj V Dept of ECE NUS (2023) 28