You are on page 1of 29

INTRODUCTION TO PYTHON

(PART II)

Presenter: Prof. Amit Kumar Das


Assistant Professor,
Dept. of Computer Science and Engg.,
Institute of Engineering & Management.
ARITHMETIC OPERATORS

 operator: Combines multiple values or


expressions.
 + addition
 - subtraction (or negation)
 * multiplication
 / division
 // integer division (a.k.a. leave off any remainder)
 % modulus (a.k.a. remainder)
 ** exponent
RELATIONAL OPERATORS

Operator Meaning Example Value


== 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
ASSIGNMENT OPERATORS
THE IF STATEMENT

Executes a block of statements only if a test is true

if (test):
statement
...
statement

 Example:
gpa = float(input("gpa? "))
if (gpa >= 2.0):
print("Application accepted.")
THE IF/ELSE STATEMENT
Executes one block if a test is true, another if false

if (test):
statement(s)
else:
statement(s)

 Example:
gpa = float(input("gpa? "))
if (gpa >= 2.0):
print("Welcome to Mars University!")
else:
print("Application denied.")
NESTED IF/ELSE STATEMENT
Chooses between outcomes using many tests

if (test1):
statement1(s)
else:
if (test2):
statement2(s)
else:
statement3(s)

Example:
if (x < 0):
print("Negative")
else:
if (x > 0):
print("Positive")
else:
print("Zero")
FOR LOOP SYNTAX

for variable in range (start, stop, interval):


statement
statement
...
statement

 Set the variable equal to the start value


 Repeat the following:
 Check if the variable is less than the stop. If not, stop.
 Execute the statements.
 Increase the variable's value by 1.
FOR LOOP SYNTAX (CONTD.)

print("1 squared = " + str(1 * 1))


print("2 squared = " + str(2 * 2))
print("3 squared = " + str(3 * 3))
print("4 squared = " + str(4 * 4))
print("5 squared = " + str(5 * 5))
print("6 squared = " + str(6 * 6))

 Intuition: "I want to print a line for each number from 1 to 6"

 The for loop does exactly that!


for i in range(1, 7):
print(str(i) + " squared = " + str(i * i));

 "For each integer i from 1 through 6, print ..."


A DECEPTIVE PROBLEM...

 Write a method print_letters that prints each


letter from a word separated by commas.

For example, the call:


print_letters("Atmosphere")

should print:
A, t, m, o, s, p, h, e, r, e
FLAWED SOLUTIONS
 def print_letters(word):
for i in range(0, len(word)):
print(str(word[i]) + ", ", end="")
print() # end line

 Output: A, t, m, o, s, p, h, e, r, e,

 def print_letters(word):
for i in range(0, len(word)):
print(", " + str(word[i]), end="")
print() # end line
 Output: , A, t, m, o, s, p, h, e, r, e
FENCE POST ANALOGY
In a flawed solution:
 We print n letters but need only n - 1 commas.

 Similar to building a fence with wires separated by


posts:
 If we use a flawed algorithm that repeatedly places a post +
wire, the last post will have an extra dangling wire.

for length of fence :


place a post.
place some wire.
FENCE POST ANALOGY

 Add a statement outside the loop to place the initial


"post."
 Also called a fencepost loop or a "loop-and-a-half" solution.

place a post.
for length of fence – 1:
place some wire.
place a post.
CORRECT SOLUTIONS
 Either first or last "post" can be taken out:

def print_letters(word):
print(word[0])
for i in range(1, len(word)):
print(", " + word[i], end="")
print() # end line

def print_letters(word):
for i in range(0, len(word) - 1):
print(word[i], end=", ")
last = len(word) – 1
print(word[last]) # end line
WHILE LOOP SYNTAX

 definite loop: Executes a known number of times.


 The for loops we have seen are definite loops.
 Print "hello" 10 times.
 Find all the prime numbers up to an integer n.
 Print each odd number between 5 and 127.

 indefinite loop: One where the number of times its body


repeats is not known in advance.
 Prompt the user until they type a non-negative number.
 Print random numbers until a prime number is printed.

 Repeat until the user has typed "q" to quit.


WHILE LOOP SYNTAX (CONTD.)

 while loop: Repeatedly executes its


body as long as a logical test is true.
while (test):
statement(s)

 Example:
num = 1 # initialization
while (num <= 200): # test
print(str(num), end=" ")
num = num * 2 # update

# output: 1 2 4 8 16 32 64 128
WHILE LOOP SYNTAX (CONTD.)

Find the first factor of 91, other than 1.

n = 91
factor = 2
while (n % factor != 0):
factor = factor + 1
print("First factor is " + str(factor))
# output: First factor is 7

 while is better than for because we don't know how many


times we will need to increment to find the factor.
STANDARD DATA TYPES
 Python has five standard data types −
 Numbers
 String
 List
 Tuple
 Dictionary
NUMBERS
 Number data types store numeric values. Number
objects are created when you assign a value to them.
For example −
var1 = 1
var2 = 10
 Python supports four different numerical types −
 int (signed integers)
 long (long integers, they can also be represented in octal
and hexadecimal)
 float (floating point real values)
 complex (complex numbers)

Here are some examples of numbers −


STRINGS
Strings in Python are identified as a contiguous set of
characters represented in the quotation marks.

 Python allows for either pairs of single or double


quotes.
 Subsets of strings can be taken using the slice
operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1
at the end.
 The plus (+) sign is the string concatenation operator
and the asterisk (*) is the repetition operator.
STRINGS (CONTD.)

Output produced:
LISTS
Lists are the most versatile of Python's compound data
types. To some extent, lists are similar to arrays in C.

 A list contains items separated by commas and


enclosed within square brackets ([]).
 All the items belonging to a list can be of different data
type.
 The values stored in a list can be accessed using the
slice operator ([ ] and [:]) with indexes starting at 0 in
the beginning of the list and working their way to end
-1.
 The plus (+) sign is the list concatenation operator,
and the asterisk (*) is the repetition operator.
LISTS (CONTD.)

Output produced:
TUPLES
A tuple is another sequence data type that is similar to
the list. A tuple consists of a number of values separated
by commas.

 Unlike lists, however, tuples are enclosed within


parentheses.
 The main differences between lists and tuples are:
Lists are enclosed in brackets ( [ ] ) and their elements
and size can be changed, while tuples are enclosed in
parentheses ( ( ) ) and cannot be updated.
 Tuples can be thought of as read-only lists.
TUPLES (CONTD.)

Output produced:

The following code, which attempts to update a tuple, is invalid.


DICTIONARY
Dictionary in Python is an unordered collection of data
values, used to store data values like a map, which
unlike other Data Types that hold only single value as
an element, Dictionary holds key:value pair.

 Each key-value pair in a Dictionary is separated by a


colon :, whereas each key is separated by a ‘comma’.
 A dictionary key can be almost any Python type, but
are usually numbers or strings.
 Values, on the other hand, can be any arbitrary
Python object.
 Dictionaries are enclosed by curly braces ({ }) and
values can be assigned and accessed using square
braces ([]).
DICTIONARY (CONTD.)

Output produced:
NESTED DICTIONARY
THANK YOU &
STAY TUNED!

You might also like