Welcome!
- In previous weeks, you were introduced to the fundamental building blocks of programming.
- You learned about programming in a lower-level programming language called C.
- Today, we are going to work with a higher-level programming language called Python.
- As you learn this new language, you’re going to find that you are going to be more able to teach yourself new programming languages.
Hello Python!
- Humans, over the decades, have seen how previous design decisions made in prior programming languages could be improved upon.
- Python is a programming language that builds upon what you have already learned in C.
- Python additionally has access to a vast number of user-created libraries.
- Unlike in C, which is a compiled language, Python is an interpreted language, where you need not separately compile your program. Instead, you run your program in the Python Interpreter.
- Up until this point, the code has looked like this:
Notice how this C program is more complex than the Python version below. You can download this code here.
- Today, you’ll find that the process of writing and compiling code has been simplified.
- For example, the above code will be rendered in Python as:
Notice that the semicolon is gone and that no library is needed. You can run this program in your terminal by typing python hello.py. You can download this code here.
- Python notably can implement what was quite complicated in C with relative simplicity.
- Among the goals of this week is to be more comfortable with being uncomfortable not knowing exactly how to solve a problem or correctly, syntactically implement a solution: Searching yourself for resources to help you (within the course’s academic honesty policy)!
Speller
- To illustrate this simplicity, let’s type ‘code dictionary.py’ in the terminal window and write code as follows:
Notice that there are four functions above. In the check function, if a word is in words, it returns True. It is so much easier than an implementation in C! Similarly, in the load function, the dictionary file is opened. For each line in that file, we add that line to words. Using rstrip, the trailing new line is removed from the added word. size simply returns the len or length of words. unload only needs to return True because Python handles memory management on its own. You can download this code here.
- The above code illustrates why higher-level languages exist: To simplify and allow you to write code more easily.
- However, speed is a tradeoff. Because C allows you, the programmer, to make decisions about memory management, it may run faster than Python – depending on your code. While C only runs your lines of code, Python runs all the code that comes under the hood with it when you call Python’s built-in functions.
- You can learn more about functions in the Python documentation
Filter
- To further illustrate this simplicity, create a new file by typing
code blur.pyin your terminal window and write code as follows:
Notice that this program imports modules Image and ImageFilter from a library called PIL. This takes an input file and creates an output file. You can download this code here.
- Further, you can create a new file called
edges.pyas follows:
Notice that this code is a small adjustment to your blur code but produces a dramatically different result. You can download this code here.
- Python allows you to abstract away programming that would be much more complicated within C and other lower-level programming languages.
- One of the trade-offs of using Python is an interpreted language, instead of being compiled (as we strictly defined earlier in the course). Accordingly, there is some (usually very small) slow-down that may not be expected in a compiled program.
Functions
- In C, you may have seen functions as follows:
- In Python, you will see functions as follows:
Libraries, Modules, and Packages
- As with C, the CS50 library can be utilized within Python.
- The following functions will be of particular use:
-
You can import the cs50 library as follows:
-
You also have the option of importing only specific functions from the CS50 library as follows:
Strings
- In C, you might remember this code:
Notice how this C program uses the CS50 library to get user input. You can download this code here.
- This code is transformed in Python to:
You can write this code by executing code hello.py in the terminal window. Then, you can execute this code by running python hello.py. Notice how the + sign concatenates "hello, " and answer. You can download this code here.
- Similarly, this can be done without concatenation:
Notice that the print statement automatically creates a space between the hello statement and the answer.
- Similarly, you could implement the above code as:
Notice how the curly braces allow for the print function to interpolate the answer such that answer appears within. The f is required to include the answer properly formatting. You can download this code here.
Positional Parameters and Named Parameters
- Functions in C like
fread,fwrite, andprintfuse positional arguments, where you provide arguments with commas as separators. You, the programmer, must remember what argument is in which position. These are referred to as positional arguments. - In Python, named parameters allow you to provide arguments without regard to positionality.
- You can learn more about the parameters of the
printfunction in the documentation. - Accessing that documentation, you may see the following:
Notice that various objects can be provided to print. A separator of a single space is provided that will display when more than one object is given to print. Similarly, a new line is provided at the end of the print statement.
Variables
- Variable declaration is simplified too. In C, you might have
int counter = 0;. In Python, this same line would readcounter = 0. You need not declare the type of the variable. - Python favors
counter += 1to increment by one, losing the ability found in C to typecounter++.
Types
-
Data types in Python do not need to be explicitly declared. For example, you saw how
answerabove is a string, but we did not have to tell the interpreter this was the case: It knew on its own. -
In Python, commonly used types include:
Notice that
longanddoubleare missing. Python will handle what data type should be used for larger and smaller numbers. -
Some other data types in Python include:
- Each of these data types can be implemented in C, but in Python, they can be implemented more simply.
Calculator
- You might recall
calculator.cfrom earlier in the course:
Notice this C implementation of a simple calculator. You can download this code here.
- We can implement a simple calculator just as we did within C. Type
code calculator.pyinto the terminal window and write code as follows:
Notice how the CS50 library is imported. Then, x and y are gathered from the user. Finally, the result is printed. Notice that the main function that would have been seen in a C program is gone entirely! While one could utilize a main function, it is not required. You can download this code here.
- It’s possible for one to remove the training wheels of the CS50 library. Modify your code as follows:
Notice how executing the above code results in strange program behavior. Why might this be so?
- You may have guessed that the interpreter understood
xandyto be strings. You can fix your code by employing theintfunction as follows:
Notice how the input for x and y is passed to the int function, which converts it to an integer. Without converting x and y to be integers, the characters will concatenate. You can download this code here.
Conditionals
- In C, you might remember a program like this:
Notice how conditionals work in C. You can download this code here.
- In Python, it would appear as follows:
Notice that there are no more curly braces. Instead, indentations are utilized. Second, a colon is utilized in the if statement. Further, elif replaces else if. Parentheses are also no longer required in the if and elif statements. You can download this code here.
- Further looking at comparisons, consider the following code in C:
Notice how logical operators work in C. You can download this code here.
- The above can be implemented as follows:
Notice that the two vertical bars utilized in C is replaced with or. Indeed, people often enjoy Python because it is more readable by humans. Also, notice that char does not exist in Python. Instead, strs are utilized. You can download this code here.
- Another approach to this same code could be as follows using lists:
Notice how we are able to express multiple keywords like y and yes in a list. You can download this code here.
Object-Oriented Programming
- It’s possible to have certain types of values not only have properties or attributes inside of them but have functions as well. In Python, these values are known as objects
- In C, we could create a
structwhere you could associate multiple variables inside a single self-created data type. In Python, we can do this and also include functions in a self-created data type. When a function belongs to a specific object, it is known as a method. - For example,
strsin Python have built-in methods. Therefore, you could modify your code as follows:
Notice how we use s.lower() to normalize input, using the built-in lower method of strs. You can download this code here.
- Similarly, you may recall how we copied a string in C:
Notice the number of lines of code. You can download this code here.
- We may implement the above in Python as follows:
Notice how much shorter this program is than its counterpart in C. You can download this code here.
- In this class, we will only scratch the surface of Python. Therefore, the Python documentation will be of particular importance as you continue.
- You can learn more about string methods in the Python documentation
Loops
- Loops in Python are very similar to C. You may recall the following code in C:
forloops can be implemented in Python as follows:
Notice that i is never explicitly used. However, Python will increment the value of i. You can download this code here.
- Further, a
whileloop could be implemented as follows:
You can download this code here.
- To further our understanding of loops and iteration in Python, let’s create a new file called
uppercase.pyas follows:
Notice how end= is used to pass a parameter to the print function that continues the line without a line ending. This code passes one string at a time. You can download this code here.
- Reading the documentation, we discover that Python has methods that can be implemented upon the entire string as follows:
Notice how .upper is applied to the entire string. You can download this code here.
Abstraction
- As we hinted at earlier today, you can further improve upon our code using functions and abstracting away various code into functions. Modify your earlier-created
meow.pycode as follows:
Notice that the meow function abstracts away the print statement. Further, notice that the main function appears at the top of the file. At the bottom of the file, the main function is called. By convention, it’s expected that you create a main function in Python. You can download this code here.
- Indeed, we can pass variables between our functions as follows:
Notice how meow now takes a variable n. In the main function, you can call meow and pass a value like 3 to it. Then, meow utilizes the value of n in the for loop. You can download this code here.
- Reading the above code, notice how you, as a C programmer, are able to quite easily make sense of the above code. While some conventions are different, the building blocks you previously learned are very apparent in this new programming language.
Truncation and Floating Point Imprecision
- Recall that in C, we experienced truncation where one integer is divided by another could result in an imprecise result.
- You can see how Python handles such division as follows by modifying your code for
calculator.py:
Notice that executing this code results in a value, but that if you were to see more digits after .333333 you’d see that we are faced with floating-point imprecision. Truncation does not occur. You can download this code here.
- We can reveal this imprecision by modifying our codes slightly:
Notice that this code reveals the imprecision. Python still faces this issue, just as C does. You can download this code here.
Exceptions
- Let’s explore more about exceptions that can occur when we run Python code.
- Modify
integer.pyas follows:
Notice that inputting the wrong data could result in an error. You can download this code here.
- We can
tryto handle and catch potential exceptions by modifying our code as follows:
Notice that the above code repeatedly tries to get the correct type of data, providing additional prompts when needed. You can download this code here.
Mario
-
Recall a few weeks ago our challenge of building three blocks on top of one another, like in Mario.
three vertical blocks -
In Python, we can implement something akin to this as follows:
This prints a column of three bricks. You can download this code here.
- In C, we had the advantage of a
do-whileloop. However, in Python, it is conventional to utilize awhileloop, as Python does not have ado-whileloop. You can write code as follows in a file calledmario.py:
Notice how the while loop is used to obtain the height. Once a height greater than zero is inputted, the loop breaks. You can download this code here.
-
Consider the following image:
four horizontal question blocks -
In Python, we could implement by modifying your code as follows:
Notice that you can override the behavior of the print function to stay on the same line as the previous print. You can download this code here.
- Similar in spirit to previous iterations, we can further simplify this program:
Notice that we can utilize * to multiply the print statement to repeat 4 times. You can download this code here.
-
What about a large block of bricks?
three by three block of mario blocks -
To implement the above, you can modify your code as follows:
Notice how one for loop exists inside another. The print statement adds a new line at the end of each row of bricks. You can download this code here.
- You can learn more about the
printfunction in the Python documentation
Lists
lists are a data structure within Python.lists have built-in methods or functions within them.- For example, consider the following code:
Notice that you can use the built-in sum method to calculate the average. You can download this code here.
- You can even utilize the following syntax to get values from the user:
Notice that this code utilizes the built-in append method for lists. You can download this code here.
- You can learn more about lists in the Python documentation
- You can also learn more about
lenin the Python documentation
Searching and Dictionaries
- We can also search within a data structure.
- Consider a program called
phonebook.pyas follows:
Notice how this implements linear search for each name. You can download this code here.
- However, we don’t need to iterate through a list. In Python, we can execute linear search as follows:
Notice how in is used to implement linear search. You can download this code here.
- Still, this code could be improved.
- Recall that a dictionary or
dictis a collection of key and value pairs. - You can implement a dictionary in Python as follows:
Notice that the dictionary is implemented having both name and number for each entry. You can download this code here.
- Even better, strictly speaking, we don’t need both a
nameand anumber. We can simplify this code as follows:
Notice that the dictionary is implemented using curly braces. Then, the statement if name in people searches to see if the name is in the people dictionary. Further, notice how, in the print statement, we can index into the people dictionary using the value of name. Very useful! You can download this code here.
- Similarly, one could implement a list of dictionaries:
Notice how people is implemented as a list of dictionaries, separated by commas. You can download this code here.
- Python has done their best to get to constant time using their built-in searches.
- You can learn more about dictionaries in the Python documentation
Command-Line Arguments
- As with C, you can also utilize command-line arguments. Consider the following code:
Notice that argv[1] is printed using a formatted string, noted by the f present in the print statement. You can download this code here.
- You can learn more about the
syslibrary in the Python documentation
Exit Status
- The
syslibrary also has built-in methods. We can usesys.exit(i)to exit the program with a specific exit code:
Notice that dot-notation is used to utilize the built-in functions of sys. You can download this code here.
CSV Files
- Python also has built-in support for CSV files.
- Modify your code for
phonebook.pyas follows:
Notice writerow adds the commas in the CSV file for us. You can download this code here.
- While
file.closeandfile = openare commonly used and available syntax in Python, this code can be improved as follows:
Notice that the code is indented under the with statement. This automatically closes the file when done. You can download this code here.
- Similarly, we can write a dictionary as follows within the CSV file:
Notice this code is quite similar to our prior iteration but with csv.DictWriter instead. You can download this code here.
Third-Party Libraries
- One of the advantages of Python is its massive user base and similarly large number of third-party libraries.
- You can install the CS50 Library on your own computer by typing
pip install cs50, provided you have Python installed. - Considering other libraries, David demoed the use of
cowsayandqrcode.
Summing Up
In this lesson, you learned how the building blocks of programming from prior lessons can be implemented within Python. Further, you learned about how Python allowed for more simplified code. Also, you learned how to utilize various Python libraries. In the end, you learned that your skills as a programmer are not limited to a single programming language. Already, you are seeing how you are discovering a new way of learning through this course that could serve you in any programming language – and, perhaps, in nearly any avenue of learning! Specifically, we discussed…
- Python
- Variables
- Conditionals
- Loops
- Types
- Object-Oriented programming
- Truncation and floating point imprecision
- Exceptions
- Dictionaries
- Command-line arguments
- Third-Party libraries
See you next time!