Variables & Strings - blogs.umass.edu · 7/2/2019 · • Introduce print statements. Exercise...
Transcript of Variables & Strings - blogs.umass.edu · 7/2/2019 · • Introduce print statements. Exercise...
Variables & Strings
Goals
• Introduce the use of variables• Introduce a new data type: strings• Introduce print statements
Exercise Review: Making Change
• Let’s make change for 91¢Number of quarters: 91 // 25 = ?Number of dimes: (91 % 25) // 10 = ?Number of nickels: ((91 % 25) % 10) // 5 = ?Number of pennies: ((91 % 25) % 10) % 5 = ?
Exercise Review: Making Change
• Let’s make change for 91¢Number of quarters: 91 // 25 = ?Number of dimes: (91 % 25) // 10 = ?Number of nickels: ((91 % 25) % 10) // 5 = ?Number of pennies: ((91 % 25) % 10) % 5 = ?
• This is a bit clunky and the same amount is represented multiple times
Total owed 91¢
Amount owed after quarters: 91 % 25 = 16¢
Amount owed after quarters and dimes: (91 % 25) % 10 = 6¢
Amount owed after quarters, dimes, and nickels: ((91 % 25) % 10) % 5 = 1¢
Variables
• A cleaner way is to use a variable and update it• The = sign is used to assign a value to a variable• Use an informative name to keep code readable
totalAmount = 91
• Variables can be defined using other variablesnumberQuarters = totalAmount // 25
• Variables can be updatedtotalAmount = totalAmount % 25totalAmount %= 25
• Try finishing the rest!
Variables
numberDimes = totalAmount // 10totalAmount %= 10
numberNickels = totalAmount // 5totalAmount %= 5
numberPennies = totalAmount
Variables
numberPennies = totalAmount
• These two variables have the same value, but they are different objects; modifying one does not affect the otherx = 14y = xx += 2x = ?y = ?
Naming Variables
• Variable names must start with a letter
Naming Variables
• Variable names can only contain letters, numbers, and underscores
Naming Variables
• Variable names are case-sensitivenum = 3NUM = 2num – NUM = ?NUM – num = ?
• It’s important is to always use informative names• Read more about naming style here
https://www.python.org/dev/peps/pep-0008/
Assigning multiple variables
• Multiple variables can be assigned on one linex, y = 1, 2
• This makes swapping values very simplex, y = y, x
• How would you swap values without this?
Assigning multiple variables
• Multiple variables can be assigned on one linex, y = 1, 2
• This makes swapping values very simplex, y = y, x
• How would you swap values without this?• You would need to use a temporary variable
temp = xx = yy = temp
Assigning multiple variables
Exercise: Computing the Fibonacci sequence• The nth term is defined as the sum of the previous
two terms: Fn = Fn-2 + Fn-11, 1, 2, 3, 5, 8, 13, 21, …
Assigning multiple variables
Exercise: Computing the Fibonacci sequence• The nth term is defined as the sum of the previous
two terms: Fn = Fn-2 + Fn-11, 1, 2, 3, 5, 8, 13, 21, …
• Initialize two variablesx, y = 1, 1
• Update the variablesx, y = y, x + y
• Run the line multiple times to iterate
Review: Data types
• So far, we’ve seen three data typesIntegers …, -3, -2, -1, 0, 1, 2, 3, …Floats 3.14159, 1.41421, 18.0, …Booleans True, False
• Now we add strings• Strings are enclosed within single or double quotes
“this is a string”‘so is this’
Strings
• You can put unlike quotes in strings“Mary’s dog”‘John said “hello” quietly’
• Or use the backslash to escape quotes‘Mary\’s dog’“John said \“hello\” quietly”
• Backslash also encodes other special characters\t tab\n linebreak\\ backslash
Strings
• Strings can be concatenated using +• Unlike adding numbers, order matters
a = ‘race’b = ‘car’a + b = ?b + a = ?
• Python doesn’t add spaces automatically!• Strings can be compared using == and !=
a + b == b + ab != ‘CAR’
Strings
Exercise: Generating palindromes• A palindrome is a word that reads the same
forwards and backwards, like racecar• Generate a long palindrome using a’s and b’s
Strings
Exercise: Generating palindromes• A palindrome is a word that reads the same
forwards and backwards, like racecar• Generate a long palindrome using a’s and b’s• Initialize the string
palindrome = ‘a’
• Add to both sidespalindrome = ‘a’ + palindrome + ‘a’palindrome = ‘b’ + palindrome + ‘b’
• Run these lines multiple times to grow the string
Ambiguous operators
• + means different things for numbers and strings• Different types cannot be combined
Type casting
• Data types can be cast into other data typesstr() returns a stringint() returns an integerfloat() returns a floatbool() returns a Boolean
• bool() has special mappings• 0 returns False, non-zero returns True• Empty string “” returns False, other strings return True
• type() returns the type of an object
Type casting
• What will these lines return?type(‘a’)bool(2) == bool(‘’)str(3.0>2.8)str(3)+str(2)str(3+2)type(True) != type(‘True’)
Type casting
• Functions like str() take an input and return an output -- they do not necessarily change the inputx = ‘2’y = str(x)type(x) = ?
z = 4bool(z)type(z) = ?
Organizing output
• How can we combine these variables into a string?numberQuarters = 2numberDimes = 1numberNickels = 1numberPennies = 2
Organizing output
• How can we combine these variables into a string?numberQuarters = 2numberDimes = 1numberNickels = 1numberPennies = 2
str(numberQuarters) + “quarters,” + str(numberDimes) + “dimes,” + str(numberNickels) + “nickels, and” + str(numberPennies) + “pennies.”
Organizing output
• How can we combine these variables into a string?numberQuarters = 2numberDimes = 1numberNickels = 1numberPennies = 2
str(numberQuarters) + “ quarters, ” + str(numberDimes) + “ dimes, ” + str(numberNickels) + “ nickels, and ” + str(numberPennies) + “ pennies.”Don’t forget to add spaces!
Organizing output
• Colab is an interactive environment where typing the name of an object will display its valuex = ‘Hello!’x
• Not all coding environments work this way – often a script is written and run in a non-interactive way
• We need a way to tell Python to display an output
Print statements
• The function print() sends output to the screenprint(‘hello’)• Automatically adds a linebreak to its outputprint(‘hello’)print(‘world’)• This can be changed by provided an end argumentprint(‘hello’, end=“ “)print(‘world’)
Print statements
• The function print() sends output to the screenprint(‘hello’)• Can take multiple arguments, automatically separated
by a spacex = ‘hello’y = ‘world’print(x, y)
Print statements
• The function print() sends output to the screenprint(‘hello’)• Arguments do not have to be stringsx = ‘hello’y = ‘world’z = 2print(x + y, z)print(x, y, z)print(x + y + z)
Print statements
Exercise: Printing a tic-tac-toe board• Tic-tac-toe takes place on a 3x3 board, where each
cell can be empty or contain an X or an O• Given a string board with 9 characters in it print
out the corresponding board• You have to use indices to refer to individual
charactersboard[0] board[1] board[2]
board[3] board[4] board[5]
board[6] board[7] board[8]
Print statements
Exercise: Printing a tic-tac-toe boardboard = “XO OX X”print(board[0],board[1],board[2])print(board[3],board[4],board[5])print(board[6],board[7],board[7])
Print statements
Exercise: Printing a tic-tac-toe boardboard = “XO OX X”print(board[0] + “|” + board[1] + “|” + board[2])print(“-----”)print(board[3] + “|” + board[4] + “|” + board[5])print(“-----”)print(board[6],board[7],board[7])
Let’s add the lines on the board in
More printing options
• You can use string formatting to align text, truncate floats, and many other useful formatting options
• Read about string formatting here:https://www.learnpython.org/en/String_Formattinghttps://realpython.com/python-string-formatting/
+ and * by type
Exercise
• What do these evaluate to• If error explain why• Variables must be defined first • X = • “python”*2*3• “python”*2+3• Things that depend on type