Last time we learned about Lists, a very useful Python object. Today we add another Python object called the Tuple. On the surface they share some similar functionality. However, a Tuple is an immutable object (Lists are mutable) which means once you create it, you can't change it. Remember that strings are also immutable! You can't make tuples longer, and you can't change their elements. Today we'll talk about why that is useful, how to use tuples, and when it is most appropriate to use them.
We will also cover a few miscellaneous items that make using Lists and Tuples a delight.
You can jump to Chapter 10 here.
We will discuss and learn about:
This program lets the user type in anything, "My name is Samuel" or "It's Samuel" or "Well you want to know huh? Fine I'm Samuel", and it easily pulls the name off the end of the sentence.
# Input a full sentence from the user
sentence = input("What's your name? ")
words = sentence.split()
name = words[-1]
print("Hello", name, " nice to meet you!")
An example of a tuple and also variable unpacking.
MONTHS = ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')
date = input("Enter today's date (Nov XX YYYY): ")
mon,day,year = date.split()
while MONTHS.index(mon) == -1:
date = input("Enter today's date (Nov XX YYYY): ")
mon,day,year = date.split()
month_num = MONTHS.index(mon)
print("Reformatted date: " + str(month_num) + "/" + day + "/" + year[2:])
Here is a basic calculator to input things like "3 + 6 - 3 + 8 + 6 - 2 - 6 ="
cmd = input("calculator: ")
parts = cmd.split()
total = 0
addition = True
for x in parts[0:-1]: # don't include the final = sign
if x == '+':
addition = True
elif x == '-':
addition = False
else:
if addition:
total = total + int(x)
else:
total = total - int(x)
print("=", total)