How can we tell Python to output to the screen a smiley face?
print(":)")
print(':)')
How about the number of states in the USA?
print(50)
How about the first 6 digits of $\pi$?
print(3.14159)
So print is a function that takes as its argument a value to output (we will encounter many useful functions in this class!)
Every value in Python has a type -- this matters because functions will be very picky about what kind of data they operate on!
We can tell the type of an element of data using the type function...
print(type(":)"))
print(type(50))
print(type(50.))
print(type(3.14159))
print(type("50"))
print(type("50.0"))
It's often useful to be able to convert between types...
print(len("50"))
# print(len(50)) # why doesn't this make sense?
print("50")
print(type("50"))
print(type(int("50")))
print(int("50"))
print("3.14159")
print(type("3.14159"))
print(type(float("3.14159")))
print(float("3.14159"))
print(3.14159)
print(type(3.14159))
print(type(int(3.14159)))
print(int(3.14159))
print(int(3.94159))
print(3.14159)
print(type(3.14159))
print(type(str(3.14159)))
print(str(3.14159))
And here's one more type that we'll use a LOT in this class: a list, which is a sequence of values...
print([1, 2, 3])
print(len([1,2,3]))
print(type([1, 2, 3]))
print(["a", "b", "c"])
print(len(["a", "b", "c"]))
print(type(["a", "b", "c"]))
We can even have lists that contain lists - OMG!
print([1, "b", [3, 1, 4, 1, 5, 9]])
Where do lists come from? We can create lists from other types via the list and split functions...
print(list("abc"))
# Challenge: how many digits are in the number 50?
print(len(list(str(50))))
print(len(str(50)))
print("programming is fun :)".split())
print("programming is fun :)".split(" "))
We can also join a list to re-form a string...
print(" ".join(['programming', 'is', 'fun', ':)']))
print("-".join(['I', "know", "a", "song", "that", "gets", "on", "everybody's", "nerves"]))
An operator is a special symbol or word that allows you to act upon values -- there are several in Python, but here are some basics...
print(1 + 2)
print(125 * 0.8)
print(50 / 7)
# integer division: 50 divide 7 is 7 remainder 1
print(50 // 7)
print(50 % 7)
print(17 ** 2)
print(17 * 17)
They don't only apply to numbers!
print("a" + "b")
print("hi" * 7)
print([1, 2, 3] * 3)
print(["howdy", "how"] + ["are", "you?"])
We can access values inside lists and strings via the [] operator -- it's important to note that computer scientists, for good reason, start counting at 0...
print([1, 2, 3][0])
print([1, 2, 3][1])
print([1, 2, 3][2])
print([1, "abc", [3, 1, 4, 1, 5, 9]][0])
print([1, "abc", [3, 1, 4, 1, 5, 9]][1])
print([1, "abc", [3, 1, 4, 1, 5, 9]][1][0])
print([1, "abc", [3, 1, 4, 1, 5, 9]][1][1])
print([1, "abc", [3, 1, 4, 1, 5, 9]][1][2])
print([1, "abc", [3, 1, 4, 1, 5, 9]][2])
print([1, "abc", [3, 1, 4, 1, 5, 9]][2][0])
You can string together many operators... which introduces the question of operator precedence (like PEMDAS)!
Python has such an ordering (https://docs.python.org/3/reference/expressions.html#operator-precedence) and parenthases can be used for clarity or to overwrite such ordering.
print(125 * 0 + 0.8)
print(125 * (0 + 0.8))
An expression is a combination of values, variables, operators, and calls to functions. Expressions need to be evaluated. If you ask Python to print an expression, the interpreter evaluates the expression and displays the result.
# Challenge: produce a string that has as many !'s as there are strings in a list
print(len(["life", "liberty", "pursuit of happiness"]) * "!")
It can be quite useful to have a place to store information, such as when we want to reference it in multiple places...
print(", ".join(["life", "liberty", "pursuit of happiness"]) + len(["life", "liberty", "pursuit of happiness"]) * "!")
A variable provides you the ability store a value and then change it later -- think of it as a named container.
The following is an assingment: take the expression on the right, evaluate it, and store it in the variable on the left...
words = ["life", "liberty", "pursuit of happiness"]
And now we can write the previous expression much more succinctly: referencing a variable's name tells Python to retrieve its current value...
print(", ".join(words) + len(words) * "!")
And we are free to change the contents of the variable at any time...
words = ["a", "b", "c", "d"]
print(", ".join(words) + len(words) * "!")
Now we are starting to see the power of programming -- we can write instructions that don't depend on precisely the data we encounter!
Let's look at one more common use of variables...
counter = 0
print(counter)
counter = counter + 1
print(counter)
Follow the statement closely: the right-hand side said to get the current value of counter (0), add 1 (totaling 1), and store that result back into counter -- this pattern lets us count occurrences (e.g., how many tickets are sold), we'll come back to this later :)
FYI: A similar pattern is seen when creating/adding to a list (though the append function is used instead of an operator)...
mylist = [] # empty list
print(mylist)
mylist.append("first element") # similar to, but more efficient than: mylist = mylist + ['first element']
print(mylist)
mylist.append(2)
print(mylist)
One of the most common uses of variables it to store input supplied by a user, such as via the input function...
user_name = input("Please enter your name: ")
print(user_name)
print(len(user_name))
Importantly, the result of the input function is always a string... so consider figuring out months from years
num_years = input("Please enter number of years: ")
print(num_years * 12)
print(int(num_years) * 12)
Notice that in the prior examples we weren't being very nice to our user -- they had to guess what the number meant, as opposed to us making readable outputs.
Formatted strings allows us to provide a template and fill in values in particular parts of our string where we need to...
In the "template", a {} indicates a place to fill in a value...
out = "Your name, {}, has {} letter(s).".format(user_name, len(user_name))
print(out)
print("{} year(s) = {} months".format(num_years, int(num_years)*12))
There are many additional options that can go between the {}'s, here are a couple common ones:
big_num = 525600
print("{} (minutes in a year) is so much easier to read with group separation {:,d}".format(big_num, big_num))
print()
really_big_num = 6.02214076e23
print("How many moles in a guacamole? Avocado's number! ({:,d})".format(int(really_big_num)))
small_num = 3.14159
print("{} rounded to two places is {:.2f}".format(small_num, small_num))
print("{} rounded to one place is {:.1f}".format(small_num, small_num))
print("{} rounded to zero places is {:.0f}".format(small_num, small_num))
print()
really_small_num = 6.626068e-34
print("What's the key to amazing abs? Constant planks! ({:.38f})".format(really_small_num))
print("What's the key to amazing abs? Constant planks! ({:.3g})".format(really_small_num))
# Let's help the poor Americans understand distances :)
km_to_miles = 0.621371
decimal_places = 2
num_kms = float(input("Enter kilometers: "))
template = "{} km = {:.{}f} miles (rounded to {} decimal places)"
print(template.format(num_kms, num_kms*km_to_miles, decimal_places, decimal_places))