Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Introduction to CS and Programming in Python, Lecture 2_ Strings, Input_Output, and Branching - mit6_100l_f22_lec02

This document covers key concepts in Python programming, including strings, input/output, and branching. It explains string manipulation, such as concatenation and slicing, as well as the use of input and print functions. Additionally, it discusses the importance of comparison and logical operators for controlling program flow.

Uploaded by

lokesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Introduction to CS and Programming in Python, Lecture 2_ Strings, Input_Output, and Branching - mit6_100l_f22_lec02

This document covers key concepts in Python programming, including strings, input/output, and branching. It explains string manipulation, such as concatenation and slicing, as well as the use of input and print functions. Additionally, it discusses the importance of comparison and logical operators for controlling program flow.

Uploaded by

lokesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

STRINGS, INPUT/OUTPUT,

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

 Think of a str as a sequence of case sensitive characters


 Letters, special characters, spaces, digits
 Enclose in quotation marks or single quotes
 Just be consistent about the quotes
a = "me"
z = 'you'
 Concatenate and repeat strings
b = "myself" a "me"
c = a + b
d = a + " " + b b "myself"

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

 len() is a function used to retrieve the length of a string in


the parentheses

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

 Can slice strings using [start:stop:step]


 Get characters at start
up to and including stop-1
taking every step characters

 If give two numbers, [start:stop], step=1 by default


 If give one number, you are back to indexing for the character
at one location (prev slide)
 You can also omit numbers and leave just colons (try this out!)

6.100L Lecture 2 9
SLICING EXAMPLES

 Can slice strings using [start:stop:step]


 Look at step first. +ve means go left-to-right
-ve means go right-to-left

s = "abcdefgh"
index: 0 1 2 3 4 5 6 7
index: -8 -7 -6 -5 -4 -3 -2 -1

s[3:6]  evaluates to "def", same as s[3:6:1]


s[3:6:2]  evaluates to "df"
s[:]  evaluates to "abcdefgh", same as s[0:len(s):1]
s[::-1]  evaluates to "hgfedcba"
s[4:1:-2] evaluates to "ec"

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

 Strings are “immutable” – cannot be modified


 You can create new objects that are versions of the original one
 Variable name can only be bound to one object
s = "car"
s[0] = 'b'  gives an error
s = 'b'+s[1:len(s)]  is allowed,
s bound to new object
"car"

"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

 Used to output stuff to console


In [11]: 3+2
Out[11]: 5
 Command is print
In [12]: print(3+2)
5
 Printing many objects in the same command
 Separate objects using commas to output them separated by spaces
 Concatenate strings together using + to print as single object
 a = "the"
b = 3
c = "musketeers"
print(a, b, c)
print(a + str(b) + c)
14

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:

Type anything: howdy

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:

"howdy" Type anything: howdy

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:

text "howdy" Type anything: howdy

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:

text "howdy" Type anything: howdy


howdyhowdyhowdyhowdyhowdy

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

#Try Newton Raphson for cube root


x = int(input('What x to find the cube root of? '))
g = int(input('What guess to start with? '))
print('Current estimate cubed = ', g**3)

next_g = g - ((g**3 - x)/(3*g**2))


print('Next guess to try = ', next_g)
26

6.100L Lecture 2 29
F-STRINGS

 Available starting with Python 3.6


 Character f followed by a
formatted string literal
 Anything that can be appear in a
normal string literal
 Expressions bracketed by curly braces { }
 Expressions in curly braces evaluated at runtime, automatically
converted to strings, and concatenated to the string preceding
them
num = 3000
fraction = 1/3
print(num*fraction, 'is', fraction*100, '% of', num)
print(num*fraction, 'is', str(fraction*100) + '% of', num)
print(f'{num*fraction} is {fraction*100}% of {num}')
27

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

 In CS, there are two notions of equal


 Assignment and Equality test

 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 and j are variable names


 They can be of type ints, float, strings, etc.
 Comparisons below evaluate to the type Boolean
 The Boolean type only has 2 values: True and False

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 and b are variable names (with Boolean values)


not a  True if a is False
False if a is True
a and b  True if both are True
a or b  True if either or both are True

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?

 When we get to flow of control, i.e. branching to different


expressions based on values, we need a way of knowing if a
condition is true
 E.g., if something is true, do this, otherwise do that

35

6.100L Lecture 2 40
INTERESTING ALGORITHMS
INVOLVE DECISIONS

It’s midnight

Free
food
email

Go get it! Sleep

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>

 <condition> has a value True or False


 Indentation matters in Python!
 Do code within if block if condition is True
38

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>

 <condition> has a value True or False


 Indentation matters in Python!
 Do code within if block when condition is True or code within else
block when condition is False. 39

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>

 <condition> has a value True or False


 Indentation matters in Python!
 Run the first block whose corresponding <condition> is True
40

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>

 <condition> has a value True or False


 Indentation matters in Python!
 Run the first block whose corresponding <condition> is True.
The else block runs when no conditions were True
41

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)!

x = int(input("Enter a number for x: "))


y = int(input("Enter a different number for y: "))
if x == y:
print(x,"is the same as",y)
print("These are equal!")

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

 Strings provide a new data type


 They are sequences of characters, the first one at index 0
 They can be indexed and sliced
 Input
 Done with the input command
 Anything the user inputs is read as a string object!
 Output
 Is done with the print command
 Only objects that are printed in a .py code file will be visible in the shell
 Branching
 Programs execute code blocks when conditions are true
 In an if-elif-elif… structure, the first condition that is True will
be executed
 Indentation matters in Python!
49

6.100L Lecture 2 56
MITOpenCourseWare
https://ocw.mit.edu

6.100L Introduction to Computer Science and Programming Using Python


Fall 2022

Forinformation aboutciting these materials orourTerms ofUse,visit: https://ocw.mit.edu/terms.

50

You might also like