Lecture 2

Knowledge Check

>>> x = 5
>>> type(x) #what does this give back?
>>> y = float(x % 2)
>>> y #what does this display?
>>> type(y)(x) #what does this display?

List of Variables

From last time: How can you get a list of variables?

Python provides a couple of functions to tell you about the variables (and functions/methods, modules, and classes - more on these later) currently in existence:

Assignment Operator, Revisited

Last class, we saw the assignment operator (=). There are actually many assignment operators. To create them, basically combine the arithmetic operator with the assignment operator. For example:

>>> x = 5 #basic variable assignment, x = 5
>>> x += 1 #add 1 to x and store the new value back into x, x = 6 now
>>> x **= -1 #raise x to the -1 power and store the result into x, x now equals 1/6 (or 0.16666)

The above examples are short-hand for:

>>> x = 5
>>> x = x + 1
>>> x = x**-1

These combined arithmetic/assignment operators are for the convenience of programmers. It's ok if you don't use them much. They are mostly used to increment/decrement variables (usually by one).

Print Function

The Python interpreter will display the result of a statement. That's nice for now, but it'd be nice to get fancier output. Plus, as we get to bigger programs, we won't be using the interpreter, so it'd be good to know how to display output to the user.

Python has a function called print that we can use to display output. I'm introducing it now so we can see what strings of text actually look like. Since we haven't seen strings yet, let's just see how to use print with numbers, but it'll be the same with strings.

print takes a comma-delimited list of things (called "arguments") to print, e.g.:

>>> print(15)
15
>>> print(-38.5, 16)
-38.5 16

Notice that each argument in the print function is separated by a comma. Notice that when they're printed out, the comma doesn't show up. Instead, there's a space there. That space isn't because there was a space in the print function:

>>> print(-38.5,16)
-38.5 16

You can put as many arguments in a print function as you want (and they can all be different types):

>>> x = 12
>>> print(-38.5, 16, -0.02, 16, 1e5, x)
-38.5 16 -0.02 16 100000.0 12

What do you think happens if you put nothing in the parentheses? In other words, what does this do: print()

Strings

In programming, "string" means "collection of characters" (or basically "text"). To create a string in Python, surround your text with quotes. It doesn't matter if you use single quotes (') or double quotes ("), as long as you're consistent.

>>> 'This is a string.'
'This is a string.'
>>> "This is also string."
'This is also string.'
>>> "The next line is also a string, even though it is just numbers."
The next line is also a string, even though it is just numbers.
>>> "14"
'14'
>>> This is not a string since it is not surrounded by quotes.
  File "<stdin>", line 1
This is not a string since it is not surrounded by quotes.
                   ^
SyntaxError: invalid syntax
>>> 'This string will not work because it opens with a single quote and ends with a double quote."
  File "<stdin>", line 1
    'This string will not work because it opens with a single quote and ends with a double quote."
                                                                                                 ^
SyntaxError: EOL while scanning string literal

What if you want your string to contain a quote? Just use the other kind of quote.

>>> "This string'll work because it's surrounded by double quotes and uses single quotes inside it."
"This string'll work because it's surrounded by double quotes and uses single quotes inside it."
>>> 'Since this string is surrounded by single quotes, it can contain double quotes (") if I want it to.'
'Since this string is surrounded by single quotes, it can contain double quotes (") if I want it to.'

What if you want your string to contain both kinds of quotes? You have two options: escape sequences or multi-line strings.

Escape Sequences

Certain characters are hard to represent in a string, but you may want them in a string. One way to get them into a string is with an escape sequence. Below are the escape sequences Python supports:

Escape Sequence Represents Description
\n newline Advances the cursor to the next line
\r carriage return Causes the cursor to go to the beginning of the current line, not the next line
\b backspace Causes the cursor to back up, or move left, one position
\t tab Causes the cursor to skip over to the next tab stop
\' single quote Causes a single quote to be printed
\" double quote Causes a double quote to be printed
\\ backslash Causes a backslash to be printed

Here's an example of using some of them:

>>> 'Here\'s a line that spans\nmultiple lines and has a singlr\be quote'
"Here's a line that spans\nmultiple lines and has a singlr\x08e quote"
>>> #Notice that it doesn't quite display properly. Instead of spanning two lines,
... #it just displays "\n" and instead of deleting the 'r' in "singlr", it displays
... #"\x08". Here's where the print function can be helpful!
...
>>> print('Here\'s a line that spans\nmultiple lines and has a singlr\be quote')
Here's a line that spans
multiple lines and has a single quote

Notice that using the print function displays the string correctly. It also no longer displays the outputted string surrounded by quotes.

Multi-line Strings

If you want a string to span multiple lines, using '\n' is good, but sometimes it makes reading your code harder. Instead, you can create multi-line strings. To do that, surround your string with three quotes on either side instead of just one quote:

>>> '''This line spans three lines and contains
... double quotes ("), single quotes ('), and even three double quotes in a row (""")!
... It doesn't end until there's a closing '''
'This line spans three lines and contains\ndouble quotes ("), single quotes (\'), and even three double quotes in a row (""")!\nIt doesn\'t end until there\'s a closing '

Notice that the interpreter puts all of it into one string and escapes all of the characters that need to be escaped. But, it didn't display nicely. Again, to get it to display nicely, we really should be using the print function:

>>> print('''This line spans three lines and contains
... double quotes ("), single quotes ('), and even three double quotes in a row (""")!
... It doesn't end until there's a closing ''')
This line spans three lines and contains
double quotes ("), single quotes ('), and even three double quotes in a row (""")!
It doesn't end until there's a closing

Variables Revisited

Assigning strings into a variable is the same way as with numbers.

>>> x = 12
>>> msg = 'x is equal to'
>>> print(msg, x)
x is equal to 12

Notice that there is no space at the end of msg but there is a space between the end of msg and the value stored in x.

String Operations

Just like with numbers, strings have a lot of operations you can do with them.

Operation Description Example
Concatenation Combine two strings into one (new) string >>> str1 = "Here is a string "
>>> str2 = "that was in two parts."
>>> str3 = str1 + str2
>>> print(str3)
Here is a string that was in two parts.
Combined Concatenation
and Assignment
Combine two strings into one (new) string >>> str1 = "Here is a string "
>>> str1 += "that was in two parts."
>>> print(str1)
Here is a string that was in two parts.
Length The number of characters in the string. Returns an int. >>> str1 = "This string is short."
>>> len(str1)
21
Convert to Lowercase Return a new string where all characters in the string are lowercase. >>> str1 = "This string is short."
>>> print(str1.lower())
this string is short.
Convert to Uppercase Return a new string where all characters in the string are uppercase. >>> str1 = "This string is short."
>>> uppercase_str1 = str1.upper()
THIS STRING IS SHORT.
Capitalize Return a new string. If the first character of the existing string is a letter, then it is capitalized, otherwise there is no change to the string. >>> str1 = "This string is short."
>>> print(str1.capitalize())
This string is short.
Count Count the number of times a substring appears in the string. >>> str1 = "This string is short."
>>> count_s = str1.count('s')
>>> print('In the string "'+str1+'", the letter "s" appears', count_s, 'times.')
In the string "This string is short.", the letter "s" appears 4 times.
>>>
>>> count_is = str1.count('is')
>>> print('In the string "'+str1+'", the substring "is" appears', count_is, 'times.')
In the string "This string is short.", the substring "is" appears 2 times.
Find Find the first occurrence of the specified substring and return it starting position in the string. Note: The positions start at 0. If the substring is not found, it returns -1. >>> str1 = "This string is short."
>>> pos_is = str1.find('is')
>>> print("The first occurrence of 'is' is at ", pos_is)
The first occurrence of 'is' is at  2
Index Just like Find, but raises a ValueError exception if the substring is not found. >>> str1 = "This string is short."
>>> pos_zzz = str1.index('zzz')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
In Just tells you whether or not a substring is in the string. Doesn't tell you where it is or how many there are. >>> str1 = "This string is short."
>>> 'is' in str1
True
>>> 'zzz' in str1
False
Substring Get just part of an existing string. You specify the starting position and the position to go up to, but not include. Note: In Python (and almost every other language), you start counting at 0. >>> str1 = "This string is short."
>>> str1[0:6]
'This s'
>>> str1[5:10]
'strin'
>>> str1[str1.find('sh'):length(str1)]
'short.'

Notice that some of these are functions belonging to a string object (e.g. find and index), others are functions that take a string object (len), some have a math-like operation (+), and others use a Python keyword (in). While these may seem inconsistent now, it makes sense in the larger context of the Python language. There are many different data structures that have a length or can contain things, so it makes sense to have a uniform way to get the length of something or to see if one thing is contained in another thing.

There are many other string operations you can perform. You can find a list in the Python documentation. We will talk about some of these later in the semester.

What do you think happens with:

>>> val1 = "Convert to uppercase".upper()
>>>
>>> val2 = "My name is Zeus!"
>>> val2.lower().capitalize()

Strings and Numbers

Converting between strings and numbers is fairly easy. To convert a string into a number, use the int or float functions we saw last time. To convert a number into a string, use the str function. If you want to combine a string and a number, you'll first need to convert a number into a string. The simplest way is to use the str function:

>>> str1 = "This string is short."
>>> count_s = str1.count('s')
>>> output = 'In the string "'+str1+'", the letter "s" appears '+str(count_s)+' times.'
>>> print(output)
In the string "This string is short.", the letter "s" appears 4 times.

Formatting Numbers

There are a lot of options when it comes to formatting numbers in Python (Format specification). Today, we will cover only the very basics of formatting.

Python provides a function called format that formats something according to a specified format and returns a string. The formatting is similar to the %-notation you may be familiar with from other languages.

If you don't want a string back, but just want a number rounded to a certain number of decimal places, use the round function:

>>> x = 5.39485
>>> round(x, 2) #round to 2 decimal places
5.39
>>> round(x, 0) #round to 0 decimal places
5.0
>>> round(x, 15) #round to 15 decimal places (or however many are needed to fully represent the number
5.39485

Getting Help

Python offers a lot of help to programmers, if you know where to look. The documentation online is great, but sometimes you won't have access to it or you're using a module that doesn't have documentation available. Python still has some help for you!

The help function takes a function, module, or class and offers some documentation on it. It will describe how to use the thing and what is needed to use it. However, this requires that the writer of the function, module, or class also wrote documentation. If they didn't, this won't offer much help.

The dir function takes any object in Python (function, module, class, variable, etc) and tells you all of the functions and variables that it has. It doesn't tell you what they do, but it's at least something.

>>> help(dir)
Help on built-in function dir in module builtins:

dir(...)
    dir([object]) -> list of strings
    
    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object: its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.
>>> x = "string"
>>> dir(x)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Notice that x has all of the string functions mentioned above.

<< Previous Notes Next Notes >>