lists, loops and conditionals - purdue universitylists •a list is a general, sequence object where...

37
Lists, Loops and Conditionals HORT 59000 Lecture 11 Instructor: Kranthi Varala

Upload: others

Post on 31-May-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Lists, Loops and Conditionals

HORT 59000Lecture 11

Instructor: Kranthi Varala

Page 2: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Core data types

• Numbers• Strings• Lists• Dictionaries• Tuples• Files• Sets

Page 3: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Lists

• A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can contain integers, floats, strings etc.. • Lists are mutable, i.e., a list can be changed without

having to create a new list object

Page 4: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Lists: Common Methods

• L.append() : Adds one item to the end of the list.• L.extend() : Adds multiple items to the end of the list.• L.pop(i) : Remove item ‘i’ from the list. Default:Last.• L.reverse() : Reverse the order of items in list.• L.insert(i,item): Inserts ‘item’ at position i.• L.remove(item) : Finds ‘item’ in list and deletes it from the

list.• L.sort(): Sorts the list in- place i.e., changes the sequence in

the list. (Sorting mixed data types only works on python2)

Page 5: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

MultiDimensional Lists• Lists are of arbitrary length and and easily be nested.• Simplest nested lists are 2 –dimensional matrices.• my2DList = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

my2DList

0

1

2

3

0 21 3

Page 6: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

MultiDimensional Lists• Nested Lists need not be homogeneous.• my2DList = [[1,2,3,'a'],[5,6,7,'cat'],[9,10,'e',12],['beta',14,15,16]]

1

2

3

a

5

6

7

cat

9

10

e

12

beta

14

15

16

my2DList

0

1

2

3

0 21 3

Page 7: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Arbitrary dimensional Lists• Nested Lists need not be of the same length.• my2DList = [[1,2,3,’a’],[5,6,7],[9,10,’e’,12,’cat’],[’beta’,14,15,16]]

1

2

3

a

5

6

7

9

10

e

12

cat

beta

14

15

16

my2DList

0

1

2

3

0 21 3

Page 8: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Arbitrary dimensional Lists• Nested Lists can have arbitrary depth as well.• subL = [['p','q'],['r','s']]

• my2DList = [[1,2,3,'a'],[5,6,7,'cat'],[9,10,'e',12],['beta',14,15,subL]]

1

2

3

a

5

6

7

cat

9

10

e

12

beta

14

15

my2DList

0

1

2

3

p q

r s

0 21 3

0 1

0

1

Page 9: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Lists as sequences of references

• myList = [’Name’,[Month,Date,Year],Address,[Home,Cell]]

Str [Ref] Str [Ref]

int

int

int

Str

Str

Page 10: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Lists as sequences of references

• myList = [’Name’,[Month,Date,Year],Address,[Home,Cell]]

[Ref] [Ref] [Ref] [Ref]

int

int

int

Str

Str

Str Str

Page 11: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Lists are mutable!!

>>>subL = [[’p’,’q’],[‘r’,’s’]]

>>>myList = [[1,2,3,’a’],[5,6,7,’cat’],[9,10,’e’,12],[’beta’,14,15,subL]]

>>>myList

[[1,2,3,’a’],[5,6,7,’cat’],[9,10,’e’,12],[’beta’,14,15,[[‘p’,’q’],[‘r’,’s’]]]]

>>>subL[0][1] = ‘z’

>>>myList

[[1,2,3,’a’],[5,6,7,’cat’],[9,10,’e’,12],[’beta’,14,15,[[‘p’,’z’],[‘r’,’s’]]]]

Page 12: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Working with Lists

• Lists are a great way to store values in an ordered way. E.g., First Names.

• Multiple lists with related values can be stored and retrieved based on index. E.g., List1 -> First Names, List2->Last Names.

• When working with lists, we need a quick and robust way to iterate over them, i.e., retrieve each item separately.

• Loops with conditional statements are the most common way to iterate over lists.

Page 13: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Relational Operators

• These operators compare the value of two ‘expressions’ and returns a Boolean value.

• Beware of comparing across data types, especially when reading values in from command line or files.

Page 14: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Relational Operators== equal True if expressions are equal!= not equal True if expressions are not equal> Greater than True if left is greater than the right< Less than True if left is less than the right>= greater than OR equal<= less than OR equal

is identity True if the left is the same object as rightin contains True if the object on left is contained in object

on right (Useful for finding values in list)

Page 15: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Assignment OperatorsA += B increase A by value of BA -= B decrease A by value of B A *= B multiply A by B and assign value to AA /= B divide A by B and assign value to AA **=B raise value of A to the power of BA %= B modulus of A by B, assigned to AA //= B floor of A divided by B, assigned to A

• String context:• S1 += S2 add string on right to the one on left• S1 *= A Make A copies of S1 and concatenate them to S1

Page 16: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Boolean OperatorsCombines two or more statements that return a Boolean value.A and B True if both A and B are trueA or B True if either A or B is truenot A Reverse the Boolean given by Axor(A,B) True if only one of A or B is True

A B A and B A or B Not A xor(A,B)TRUE TRUE TRUE TRUE FALSE FALSETRUE FALSE FALSE TRUE FALSE TRUEFALSE TRUE FALSE TRUE TRUE TRUEFALSE FALSE FALSE FALSE TRUE FALSE

Page 17: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

General Python Syntax rules• End of line is end of statement• Statements at the same indentation level are in the

same block (e.g., within a loop or condition)• End of indentation is end of block• Exceptions:

• Semi colon ; separates statements on the same line

• Single line blocks are allowed without indentation

Page 18: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Branching logic• Used to implement alternate paths for the logic

flow.

https://upload.wikimedia.org/wikipedia/commons/4/44/LampFlowchart.png

Page 19: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

If/elif/else statements

if test1:statement 1

elif test2:statement 2

else:statement 3

• Both the elif and else blocks are optional.

Page 20: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

if/elif/else statements

Page 21: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Lamp flowchart with if/else

Accepts input from user, as a string

Page 22: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Truth and Boolean tests in Python

• All objects in python have an inherent true or false value.

• Any nonempty object is true. • For Integers : Any non-zero number is true

• Zero, empty objects and special object ‘None’ are false.

• Comparisons return the values True or False

Page 23: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Loops/Iterations

• A loop is a block of statements that repeats all the statements within the block until the exit condition is met.• Statements in a loop are defined by indenting them

relative to the loop start.• Loop ends when indentation ends.• Python has two forms of loops: for and while • E.g. >>> for x in range(10)• E.g. >>>while (A==10)

Page 24: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

while loops• while condition:

statement 1statement 2..

• Most generic form of loop, that checks whether the condition is true at the start of each iteration.

• Expects the condition to become false at some point during the iterations of the loop.

• If condition is never changed, this creates an ‘infinite’ loop. i.e., the program will get stuck in this loop for ever.

Page 25: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Example while loops

Page 26: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Altering while loops

• Normally, a loop ends only when exit condition is met.

• break statement forces the current loop to exit.• continue statement skips the rest of the block and

goes to the next iteration of the loop.• pass statement is a placeholder for empty blocks.

Page 27: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Altering while loops

Page 28: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

for loops• for item in sequence:

statement 1statement 2..

• Generic iterator for items in a ordered sequence such as lists, tuples etc.

• On each iteration retrieves one item from the list and assigns it to the variable specified.

• Automatically moves to the next item in the order.• Value of variable may be altered within the for loop,

but change is not made in the list.

Page 29: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

for loops

Page 30: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Looping over Strings and Lists

• List is a general sequence object while String is a character sequence object.

• Both can be iterated over by a for loop:

Page 31: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Looping over lists with and without index

• Looping with an index allows accessing the item within the list and changing it.

Page 32: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Nested Loops

• Loops can be nested just like the if/else statements.

• Indentation is again the key to creating nested loops.

• In a 2 level nested loop with x iterations on the outer loop and y iterations in the inner loop:

• All statements in the outer loop will be executed x times• All statements in the inner loop will be executed x*y times

Page 33: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

MultiDimensional Listsmy2DList = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

my2DList

0

1

2

3

0 21 3

Page 34: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

MultiDimensional Listsmy2DList = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

for x in range(len(my2DList)):

insideList=my2DList[x]

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

my2DList

0

1

2

3

0 21 3

Page 35: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

MultiDimensional Listsmy2DList = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

for x in range(len(my2DList)):

for y in range(len(my2DList[x])):

print my2DList[x][y]

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

my2DList

0

1

2

3

0 21 3

Page 36: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Arbitrary dimensional ListssubL = [[’p’,’q’],[‘r’,’s’]]

my2DList = [[1,2,3,’a’],[5,6,7,’cat’],[9,10,’e’,12],[’beta’,14,15,subL]]

1

2

3

a

5

6

7

cat

9

10

e

12

beta

14

15

my2DList

0

1

2

3

p q

r s

0 21 3

0 1

0

1

Loop1

Loop2Loop3

Page 37: Lists, Loops and Conditionals - Purdue UniversityLists •A List is a general, sequence object where the individual items in the list can be different types. I.e., the same list can

Summary: Lists, Conditions and loops

• Lists : Best suited for ordered collections of items where the order or the items themselves may need to be changed.

• Lists are mutable, heterogenous and arbitrarily sized.• Conditional statements with the proper comparison and

boolean operators allow the creation of alternate execution paths in the code.

• Loops allow repeated execution of the same set of statements on all the objects within a sequence.

• Using an index based for loop is best suited for making changes to items within a list.

• Always ensure that your exit condition will be met.