Introduction to CS and Programming in Python, Lecture 2_ Strings, Input_Output, and Branching - mit6_100l_f22_lec02
Introduction to CS and Programming in Python, Lecture 2_ Strings, Input_Output, and Branching - mit6_100l_f22_lec02
and BRANCHING
(download slides and .py files to follow along)
6.100L Lecture 2
Ana Bell
1
pi = 3.14 3.14
RECAP radius = 2.2
pi
2.2
area = pi*(radius**2)
radius
area 3.2
radius = radius+1
15.1976
var = type(5*4) var int
Objects
Objects in memory have types.
Types tell Python what operations you can do with the objects.
Expressions evaluate to one value and involve objects and operations.
Variables bind names to objects.
= sign is an assignment, for ex. var = type(5*4)
Programs
Programs only do what you tell them to do.
Lines of code are executed in order.
Good variable names and comments help you read code later.
2
6.100L Lecture 2 2
STRINGS
6.100L Lecture 2 3
STRINGS
silly = a * 3 c "memyself"
d "me myself"
silly "mememe"
6.100L Lecture 2 4
YOU TRY IT!
What’s the value of s1 and s2?
b = ":"
c = ")"
s1 = b + 2*c
f = "a"
g = " b"
h = "3"
s2 = (f+g)*int(h)
6.100L Lecture 2 5
STRING OPERATIONS
s = "abc"
len(s) evaluates to 3
chars = len(s)
6.100L Lecture 2 7
SLICING to get
ONE CHARACTER IN A STRING
Square brackets used to perform indexing
into a string to get the value at a certain
index/position
s = "abc"
index:
index:
0 1 2 indexing always starts at 0
-3 -2 -1 index of last element is len(s) - 1 or -1
s[0] evaluates to "a"
s[1] evaluates to "b"
s[2] evaluates to "c"
s[3] trying to index out of
bounds, error
s[-1] evaluates to "c"
s[-2] evaluates to "b"
s[-3] evaluates to "a"
7
6.100L Lecture 2 8
SLICING to get a SUBSTRING
6.100L Lecture 2 9
SLICING EXAMPLES
s = "abcdefgh"
index: 0 1 2 3 4 5 6 7
index: -8 -7 -6 -5 -4 -3 -2 -1
6.100L Lecture 2 10
YOU TRY IT!
s = "ABC d3f ghi"
s[3:len(s)-1]
s[4:0:-1]
s[6:3]
10
6.100L Lecture 2 11
IMMUTABLE STRINGS
"bar"
s
11
6.100L Lecture 2 12
BIG IDEA
If you are wondering
“what happens if”…
Just try it out in the console!
12
6.100L Lecture 2 13
INPUT/OUTPUT
13
6.100L Lecture 2 14
PRINTING
6.100L Lecture 2 15
INPUT
x = input(s)
Prints the value of the string s
User types in something and hits enter
That value is assigned to the variable x
Binds that value to a variable
text = input("Type anything: ")
print(5*text)
SHELL:
Type anything:
15
6.100L Lecture 2 17
INPUT
x = input(s)
Prints the value of the string s
User types in something and hits enter
That value is assigned to the variable x
Binds that value to a variable
text = input("Type anything: ")
print(5*text)
SHELL:
16
6.100L Lecture 2 18
INPUT
x = input(s)
Prints the value of the string s
User types in something and hits enter
That value is assigned to the variable x
Binds that value to a variable
text = input("Type anything: ")
print(5*text)
SHELL:
17
6.100L Lecture 2 19
INPUT
x = input(s)
Prints the value of the string s
User types in something and hits enter
That value is assigned to the variable x
Binds that value to a variable
text = input("Type anything: ")
print(5*text)
SHELL:
18
6.100L Lecture 2 20
INPUT
x = input(s)
Prints the value of the string s
User types in something and hits enter
That value is assigned to the variable x
Binds that value to a variable
text = input("Type anything: ")
print(5*text)
SHELL:
19
6.100L Lecture 2 21
INPUT
input always returns an str, must cast if working with numbers
num1 = input("Type a number: ")
print(5*num1)
num2 = int(input("Type a number: "))
print(5*num2)
SHELL:
num1 "3"
Type a number: 3
20
6.100L Lecture 2 22
INPUT
input always returns an str, must cast if working with numbers
num1 = input("Type a number: ")
print(5*num1)
num2 = int(input("Type a number: "))
print(5*num2)
SHELL:
num1 "3"
Type a number: 3
33333
21
6.100L Lecture 2 23
INPUT
input always returns an str, must cast if working with numbers
num1 = input("Type a number: ")
print(5*num1)
num2 = int(input("Type a number: "))
print(5*num2)
SHELL:
num1 "3"
Type a number: 3
33333
Type a number: 3
22
6.100L Lecture 2 24
INPUT
input always returns an str, must cast if working with numbers
num1 = input("Type a number: ")
print(5*num1)
num2 = int(input("Type a number: "))
print(5*num2)
SHELL:
num1 "3"
Type a number: 3
33333
num2 3
Type a number: 3
23
6.100L Lecture 2 25
INPUT
input always returns an str, must cast if working with numbers
num1 = input("Type a number: ")
print(5*num1)
num2 = int(input("Type a number: "))
print(5*num2)
SHELL:
num1 "3"
Type a number: 3
33333
num2 3
Type a number: 3
15
24
6.100L Lecture 2 26
YOU TRY IT!
Write a program that
Asks the user for a verb
Prints “I can _ better than you” where you replace _ with the verb.
Then prints the verb 5 times in a row separated by spaces.
For example, if the user enters run, you print:
I can run better than you!
run run run run run
25
6.100L Lecture 2 27
AN IMPORTANT ALGORITHM:
NEWTON’S METHOD
Finds roots of a polynomial
E.g., find g such that f(g, x) = g3 – x = 0
Algorithm uses successive approximation
()
next_guess = guess -
′ ()
Partial code of algorithm that gets input and finds next guess
6.100L Lecture 2 29
F-STRINGS
6.100L Lecture 2 30
BIG IDEA
Expressions can be
placed anywhere.
Python evaluates them!
28
6.100L Lecture 2 32
CONDITIONS for
BRANCHING
29
6.100L Lecture 2 33
BINDING VARIABLES and VALUES
variable = value
Change the stored value of variable to value
Nothing for us to solve, computer just does the action
some_expression == other_expression
A test for equality
No binding is happening
Expressions are replaced by values and computer just does the
comparison
Replaces the entire line with True or False
30
6.100L Lecture 2 34
COMPARISON OPERATORS
i > j
i >= j
i < j
i <= j
i == j equality test, True if i is the same as j
i != j inequality test, True if i not the same as j
31
6.100L Lecture 2 35
LOGICAL OPERATORS on bool
A B A and B A or B
True True True True
True False False True
False True False True
False False False False
32
6.100L Lecture 2 36
COMPARISON EXAMPLE
pset_time = 15
sleep_time = 8
print(sleep_time > pset_time)
derive = True
drink = False
both = drink and derive
print(both)
pset_time 15
sleep_time 8
derive True
drink False
both False
33
6.100L Lecture 2 37
YOU TRY IT!
Write a program that
Saves a secret number in a variable.
Asks the user for a number guess.
Prints a bool False or True depending on whether the guess
matches the secret.
34
6.100L Lecture 2 38
WHY bool?
35
6.100L Lecture 2 40
INTERESTING ALGORITHMS
INVOLVE DECISIONS
It’s midnight
Free
food
email
36
6.100L Lecture 2 41
If right clear, If right blocked, If right and If right , front,
go right go forward front blocked, left blocked,
go left go back
37
6.100L Lecture 2 42
BRANCHING IN PYTHON
if <condition>:
<code>
<code>
...
<rest of program>
sion>
<expression>
...
else:
<expression>
<expression>
...
<rest of program>
6.100L Lecture 2 43
BRANCHING IN PYTHON
if <condition>:
<code>
<code>
...
<rest of program>
if <condition>:
<code>
<code>
...
else:
<code>
<code>
...
<rest of program>
6.100L Lecture 2 44
BRANCHING IN PYTHON
if <condition>: if <condition>:
<code> <code>
<code> <code>
... ...
<rest of program>
elif <condition>:
<code>
if <condition>: <code>
<code> ...
<code> elif <condition>:
... <code>
else: <code>
<code> ...
<code> <rest of program>
...
<rest of program>
6.100L Lecture 2 45
BRANCHING IN PYTHON
if <condition>: if <condition>: if <condition>:
<code> <code> <code>
<code> <code> <code>
... ... ...
<rest of program>
elif <condition>: elif <condition>:
<code> <code>
if <condition>: <code> <code>
<code> ... ...
<code> elif <condition>: else:
... <code> <code>
else: <code> <code>
<code> ... ...
<code> <rest of program> <rest of program>
...
<rest of program>
6.100L Lecture 2 46
BRANCHING EXAMPLE
pset_time = ???
sleep_time = ???
if (pset_time + sleep_time) > 24:
print("impossible!")
elif (pset_time + sleep_time) >= 24:
print("full schedule!")
else:
leftover = abs(24-pset_time-sleep_time)
print(leftover,"h of free time!")
print("end of day")
42
6.100L Lecture 2 47
YOU TRY IT!
Semantic structure matches visual structure
Fix this buggy code (hint, it has bad indentation)!
43
6.100L Lecture 2 48
INDENTATION and NESTED
BRANCHING
Matters in Python
How you denote blocks of code
x = float(input("Enter a number for x: ")) 5 5 0
y = float(input("Enter a number for y: ")) 5 0 0
if x == y: True False True
print("x and y are equal") <- <-
if y != 0: True False
print("therefore, x / y is", x/y) <-
elif x < y: False
print("x is smaller")
else:
print("y is smaller") <-
print("thanks!") <- <- <-
44
6.100L Lecture 2 50
BIG IDEA
Practice will help you
build a mental model of
how to trace the code
Indentation does a lot of the work for you!
45
6.100L Lecture 2 51
YOU TRY IT!
What does this code print with
y=2
y = 20
y = 11
What if if x <= y: becomes elif x <= y: ?
answer = ''
x = 11
if x == y:
answer = answer + 'M'
if x >= y:
answer = answer + 'i'
else:
answer = answer + 'T'
print(answer)
46
6.100L Lecture 2 52
YOU TRY IT!
Write a program that
Saves a secret number.
Asks the user for a number guess.
Prints whether the guess is too low, too high, or the same as the secret.
47
6.100L Lecture 2 53
BIG IDEA
Debug early,
debug often.
Write a little and test a little.
Don’t write a complete program at once. It introduces too many errors.
Use the Python Tutor to step through code when you see something
unexpected!
48
6.100L Lecture 2 55
SUMMARY
6.100L Lecture 2 56
MITOpenCourseWare
https://ocw.mit.edu
50