1 of 35

Python Bootcamp�Day 2: Basic Syntax and Control Flow

2 of 35

Overview

  • How do we represent data?�
  • How do we make decisions?�
  • How do we repeat commands?

3 of 35

Basic Syntax

4 of 35

Building Blocks

  • InputGetting data from outside world���
  • OutputDisplaying result of a program��
  • Sequential ExecutionPerform states one after another
  • Conditional ExecutionCheck for certain conditions and execute or skip a set of instructions
  • Repeated ExecutionPerform a set of instructions repeatedly until a condition is met
  • ReuseGive a set of instructions a name and then reuse those instructions

5 of 35

Values

  • Every object in has a value.�
  • Every value belongs to a certain type which determines the behavior and properties of that object.

6 of 35

Expressions

An expression is a combination of values, variables, and operators.�

An operator is a symbol that represents a kind of computation.

Every expression has a value when evaluated.

7 of 35

Variables

We can store the results of an expression into a variable by using the the assignment.

Variable

A name or label that refers to stored data�(has a name, type, and value)�

8 of 35

Statements

A statement is unit of code that Python can execute (ex. print, assignment).

A program is a series of statements.

A statement does not necessarily have a value.

9 of 35

Activity: Tracing

Trace the execution of the following code:

# Program 1

x = 1

y = 2

print x, y

x = 1

y = 1

print x, y

# Program 2

x = 1

y = 2

z = x + y

print x, y, z

x = y

y = x

x * y

print x, y, z

10 of 35

Containers

  • ListsA collection of values.�
  • TuplesA fixed set of values.�
  • DictionariesA table of name, value pairs.�
  • SetsA collection that lets us know if a value is contained.

11 of 35

Activity: Computations

Write code that computes the following:

  • Area of a circle with radius of 5
  • Sum of the elements of the list [5, 7, 4]

12 of 35

Bugs

  • Syntax ErrorsViolated the grammar or syntax rules of the programming language
  • Logic ErrorsProgram has correct syntax, but there is a mistake in the order or construction of statements
  • Semantic ErrorsProgram has correct syntax and is logically correct, but doesn’t solve the problem you intend to solve

13 of 35

Conditional Execution

14 of 35

Logical Expressions

A logical expression evaluates to a truth value, in essence True or False.

Example

>>> length = 4

>>> width = 2

>>> length < width

False

15 of 35

Logical Operators

== equal to�!= not equal to�>= greater than or equal to�> greater than�< less than�<= less than or equal to��and both must be true�or one or both must be true�not reverses the truth value

Compare Two Objects

Glue Logical Expressions

16 of 35

Conditional Statements

We use conditional statements to check boolean expressions (which we call conditions), and change the behavior of the program accordingly.

if condition: if n == 0:

statement(s) print ‘n is zero’

17 of 35

Alternative Execution

Alternative execution is when we have two possibilities and the condition determines which one gets executed.�

if condition:� statement(s) # Condition is Trueelse:

statement(s) # Condition is False

18 of 35

Activity: Range Check

Write code that checks if a number is between 5 and 10 (inclusive).

  • To read a number use the raw_input function�� number = int(raw_input('Number? '))��
  • Print 'Yes!' if the number is in range, otherwise, print 'No!'

19 of 35

Chained Conditionals

When we want to check more than one condition, we can use chained conditionals.�Each condition is checked in the order that they appear; if one is triggered, then the rest are skipped.

if condition 1:� statements(s)�elif condition 2:� statements(s)�elif condition 3:� statements(s)�else:� statements(s)

20 of 35

Nested Conditionals

Conditional statements can be nested or placed inside another conditional statement.

Example

if a > b:

if a < c:

print ‘a is between b and c’

21 of 35

Activity: Odd and Divisible

Write code that checks if the number entered in by the user is both odd and divisible by three.

  • You can get the remainder of a division operation by using the modulus operator %�� 4 % 2 == 2
  • Print 'Yes!' if the number is meets both conditions, otherwise, print 'No!'

22 of 35

Iteration

23 of 35

While: Overview

We can use a while statement to repeatedly execute a series of tasks (i.e. a loop).

Syntax Example

while condition: n = 0

statement(s) while n < 10:

print n

n = n + 1

24 of 35

While: Control Flow

  • Evaluate condition (which is a boolean expression).�
  • If condition is False, then exit loop and continue program.�
  • If condition is True, then execute statements in body and then go to step 1.

25 of 35

While: Notes

  • Each time through the body of a loop is called an iteration.�
  • The condition normally contains a variable that changes within the body of the loop so that we can eventually exit the loop.�
  • If a loop never exits, then this is called an infinite loop.

26 of 35

Activity: Debugging

The following code is suppose to sum all the numbers between 0 and 9 (inclusive). Unfortunately, it has bugs. Correct these errors.

n = 0

total = 0

while n < 9:

total + n

print total

27 of 35

Activity: Loop Exercises

  • Find the smallest item in a list of numbers.�
  • Simulate rolling a die until we reach a 5.

28 of 35

For: Overview

Iterating through a definite set of objects is a common looping pattern, so Python provides the for statement.

Syntax Example

for item in dataset: for i in [0, 1, 2, 3]:

statement(s) print i

29 of 35

For: Control Flow

  • Extract one element from the dataset.�
  • Execute the body of for loop with item bound to the element.�
  • Go to step 1.

30 of 35

For: Range

We can generate a list of numbers using the range function:

>>> range(0, 3)

[0, 1, 2]

>>> for i in range(0, 3):� print i

0

1

2

31 of 35

For: Enumerate

We can generate a list of pairs consisting of the index and the item using enumerate:

>>> list(enumerate([‘a’, ‘b’, ‘c’]))

[(0, 'a'), (1, 'b'), (2, 'c')]

>>> for index, letter in enumerate(‘abc’):

print index, letter

0 a

1 b

2 c

32 of 35

Activity: Loop Exercises

  • Find the smallest item in a list of numbers.�
  • Simulate rolling a die until we reach a 5.

33 of 35

Break

We can exit a loop immediately by using the break statement

import random

while True:

r = random.randint(0, 10)

if r == 0:

break

print r

print r

34 of 35

Continue

We can skip the rest of the loop body and move on to the next iteration by using continue

while True:

r = random.randint(0, 10)

if r == 0:

break

if r % 2:

continue

print '{0} is even'.format(r)

35 of 35

Activity: Guessing Game

Write code that generates a random number and asks the user to guess what it is.

Guess the number: 1� Higher!

Guess the number: 3� Lower!

Guess the number: 2� Hooray, you got it!

  • If the guess is too low, tell the user to guess 'Higher!'
  • If the guess is too high, tell the user to guess 'Lower!'
  • End the program when the user has found the number