Topic | Name | Description |
---|---|---|
Course Introduction | ||
1.1: Introduction to Python 3 | Python is an ideal language for learning to program. Watch this video to see just how useful Python can be. After this, we will introduce an integrated development environment (IDE) and begin programming. The IDE will make it simple to quickly visualize and experience the results of a set of Python programming instructions. |
|
1.2: Accessing the Repl.it IDE | In this course, we will use the Repl.it IDE. This web-based IDE requires no installation, which means that you can begin programming in Python immediately. We will use this IDE throughout the course. On the page, you should see three windows arranged side-by-side in columns. In this unit, we will focus on the rightmost window. This window has a command line prompt, which is indicated by the |
|
1.3: Python 3 Data Types: int and float | Programming languages must distinguish between different types of data. Since we want to introduce simple Python computations, it makes sense to discuss numerical data. The goal of this section is to introduce two fundamental numerical data types: int and float. The int data type refers to integer data. Numbers not containing digits to the right of the decimal point such as -
10
, 0 , and 357 are integers. The float data type refers to floating-point data. Numbers
containing digits to the right of the decimal point such as 1.3 , -3.14 ,
and 300.345567 are floating-point numbers.
After you complete this section, you should be able to explain the difference between int and float. There are deeper reasons (beyond the scope of this course) why you might distinguish between these data types; those have to do with how they are represented within a computer system. Our goal for this section is simply to be able to visually identify integer and floating-point numbers. On this page, you will see more examples of int and float. The int data type refers to integer numerical data. In the rightmost window of the Repl.it IDE, use your mouse to click to the right of the > command prompt. Next, type the integer The float data type refers to floating-point numerical data. In the rightmost window of the Repl.it IDE, use your mouse to click to the right of the > command prompt. Next, type the floating-point number It is of the utmost importance that you understand the value |
|
Another way of typing floating-point data is to use scientific notation. For instance, the number 0.0012 can also be entered as 1.2e-3. In this example, "e-3" means "10 to raised to the minus three power" and this value is multiplied by 1.2; hence, 1.2e-3
is equivalent to 0.0012. Try typing |
||
1.4: Variable Assignment | Computers must be able to remember and store data. This can be accomplished by creating a variable to house a given value. The assignment operator = is used to associate a variable name with a given value. For example, type the command: a=3.45 in the command line window. This command assigns the value 3.45 to the variable named a
in the command window and hit the enter key. You should see the value contained in the variable a=7.32 and then a
You should see the new value contained in the variable Although we will not discuss arithmetic operations in detail until the next unit, you can at least be equipped with the syntax for basic operations: + (addition), - (subtraction), * (multiplication), / (division) For example, entering these command sequentially into the command line window: a=7.32 b=a+5 b would result in 12.32 being echoed to the screen (just as you would expect from a calculator). The syntax for multiplication works similarly. For example: a=7 b=a*5 b would result in 35 being echoed to the screen because the variable After you read, you should be able to execute simple assignment commands using integer and float values in the command window of the Repl.it IDE. Try typing some more of the examples from this web page to convince yourself that a variable has been assigned a specific value. |
|
Python has its own set of reserved words that, in general, should not be chosen as variable names. As we dive deeper into the course, it will become clearer how to apply these reserved words. For now, just be aware that your variable name choices should avoid the words on this list. Otherwise, though, you can choose any variable name you like. It is important to think about how variable names should be chosen in practical applications. To help others understand your work, you should choose variable names that fit their applications. For example: account_balance=2034.12 might reflect the balance contained in a bank account. You will build the skill of sensibly choosing variable names naturally as you work through more programming examples. |
||
1.5: Basic Python Output Using the print Function | The "print" function is a Python instruction that will output variable values and results to the computer screen. This instruction will allow us to automatically output data results to the screen when running a program. This section reviews what we've covered so far and introduces examples of the print function. Try executing these instructions in the command line window to make sure you understand how to use the print function: z=1.45 print(z) Notice how the print function outputs the value of the variable It is possible to use the print command in a slightly more sophisticated way. Type this set of commands in the command window: temperature=40 print('Temperature outside = ', temperature) Observe, it is possible to "dress up" the screen output by adding some extra descriptive text. We will see more examples of this later on as we introduce and develop expertise with the string data type. But, as a preview of using the print function with text, try typing this command: print('Hello world!') Congratulations! You have now executed what is probably the most-used example in just about every introductory programming course. Read this page to see more examples of using the print function. Try typing some of those examples in the Repl.it IDE to be sure you are comfortable with the print function. Consider executing these instructions one after the other (that is, sequentially): var1=22 var1=-35 var1=308 What value will the variable |
|
1.6: More Python 3 Data Types: str | Our introduction would not be complete without discussing how to work with text and character data. In this section, you will learn about the string data type and assigning a variable of type "str". String data is text or character data. To assign a variable of type str, the text string must be placed in quotes: string_example='This is the text string' To see that this variable assignment has taken place, type the command: print(string_example) and you should see the text string echoed to the screen. To assign a variable of type str, you can use either single or double quotes, but single quotes are often the convention of choice. As we dive deeper into the course, many interesting operations and computations using the string data type will be presented. Read this page to learn more about the string variable type. Use the Repl.it IDE to practice some of the string commands. |
|
Read these examples of using the 'print' and 'type' functions. You can also try to use them in the Repl.it command line. |
||
2.1: Arithmetic Operators: +, -, *, /, **, %, and // | Practice these programming examples to internalize these concepts. |
|
2.2: Operator Precedence and Using Parentheses | Execute these two instructions in the Repl.it command line window: 8**(1/3) 8**1/3 You should recognize the first instruction from the previous section. Observe that these instructions yield two totally different answers. The reason is that there is an order in which operators are evaluated. The "order of operations" and "operator precedence" define how arithmetic calculations are to be evaluated. As expected from basic arithmetic, exponentiation takes place before multiplication and division which take place before addition and subtraction. In addition, operations are generally read from left to right. As an example, consider the expression |
|
Now, we will consider order precedence when operations are phrased within the Python programming language. Before running this set of instructions in the run window, try to predict the value each variable will contain. a=3 b=4 c=1 d=5 e=3 f=a+b-c*d+e/d g=a+b-c*(d+e)/d h=a+(b-c)*d+e/d i=(a+b-c)*d+e/d You may use the print statement to verify your answer. It is important to note that // and % are considered division operations and, because of that, have precedence equal to * and /. Try to predict the value of each variable in these commands: v=2 w=3 x=4 y=19 z=23 a=v**v//x%x+y%w*z//x b=v**(v//x)%x+y%(w*z)//x Again, you should use insert some print commands to verify your answer. A useful guiding principle when writing code is: if the order precedence is not clear to you by looking at the expression, use parentheses to make things obvious, since parentheses always take the highest precedence. |
||
2.3: Relational and Logical Operators | The bool data type is necessary for the evaluation of logical data (which is inherently different from the numerical or string data types introduced so far). "bool" stands for Boolean data which can only take on one of two possible values: True or False. You should recall from the previous unit that True and False are reserved words within the Python language. Try executing these commands in the Repl.it run window: a=True print(a) print(type(a)) b=False print(b) print(type(b)) You should see that True and False appear in your program as blue text indicating that they are reserved Python words. Furthermore, the data type should be identified as bool. Let's investigate how this data type can be used. Relational operators are those that compare values in order to determine their relationship. Here is a shortlist of very useful relational operators:
Copy and paste these commands into the Repl.it run window: a=2 b=3 print(a==b) print(a!=b) print(a>=b) print(a>=a) print(a<=a) print(a>b) print(a < b)
It should be clear why these are called relational operators. Also, note that the only possible answers when using these operators are either True or False. Be EXTREMELY careful to NEVER confuse the assignment operator (=) with the relational equals (==) operator. They serve two totally different purposes. Copy and paste and run this set of commands: a=2 b=5 a=b print(a) a=2 b=5 print(a==b) The assignment operator assigns the numerical value contained in the variable b to the variable a. The relational operator compares the variables a and b for equality which evaluates to the bool data type False. Finally, there are logical operators that allow us to form combinations of logical expressions. Watch the video for a description of relational and logical operators. Afterwards, you should understand these definitions for logical operators given two boolean variables x and y:
These operators will be incredibly important in the next unit. For now, we just need to practice using them in order to get used to the syntax. |
|
Try these exercises for more practice with relational and logical operators. |
||
2.4: Operator Precedence Revisited | Read this to learn more about operators and expressions. |
|
3.1: Reading Data from the Keyboard | The input command is necessary when we want to obtain input from a keyboard. So far, variables have been initialized or assigned values within a given Python script, with commands such as: a=3 b=27 c=a+b It is often the case that a program requires keyboard input from the user to perform its function. This is exactly what the 'input' command is for. This instruction can output a message, and the program will wait for the user to input a value. Try running this command in the Repl.it run window: city=input('Enter the name of the city where you are located: ') print(city) You should be aware that the input function returns data of type str (that is, string data). If numerical data is required, an extra step must be taken to perform a type conversion using either the int or float commands. Copy and paste this set of commands into the run window and then run code using an input value of 34 when prompted for user input: temperature_str=input('Enter the temperature: ') print(temperature_str) print(type(temperature_str)) print() temperature_int=int(input('Enter the temperature: ')) print(temperature_int) print(type(temperature_int)) print() temperature_float=float(input('Enter the temperature: ')) print(temperature_float) print(type(temperature_float)) print() The variable names have been chosen to emphasize and distinguish between their data types. The input command offers the convenience of creating user-defined values within a program. At the same time, it is important to make sure the input value's data type matches the intended use of the variable. |
|
3.2: Using Conditional Statements | Read this for more on conditional statements. |
|
3.3: Loop and Iterations | Loops are necessary when we need to perform a set of operations several times. The first type of loop we will discuss is called the while loop. The while loop checks a logical condition like the if statement. If the condition is true, the code inside the while loop will execute until the condition being checked becomes false. Run this code in Repl.it: avalue= int(input('Please enter the number 10: ')) while (avalue != 10): print('Your input value is not equal to 10') print('Please try again: ') avalue= int(input('Enter the number 10: ')) print('Thank you') print('You entered a value of 10') This while loop checks to see if the value input was equal to 10. If not, the while loop will continue to execute the indented code until a value of 10 is input. The syntax rules are similar to those of the if statements:
Make sure you run the examples provided in Repl.it. When we execute the code within a loop over and over again, the process is known as iteration. |
|
The for loop is useful when we know how many times a loop is to be executed. Rather than basing the number of iterations on a logical condition, the for loop controls the number of times a loop will iterate by counting or stepping through a series of values. Run this snippet of code in Repl.it: for i in range(5): print(i) The Consider this next snippet of code: n=8 sumval=0; for i in range(n): sumval = sumval+i print('Adding ', i,'to the previous sum = ',sumval) This loop counts from 0 to strval='forever' e_count=0 for letter in strval: if letter =='e': e_count = e_count + 1 print('The letter e occurred ', e_count, 'times') Notice how the "if" statement is "nested" (and, therefore, indented) within the "for" loop. The variable It is also possible to nest loops within loops. We will discuss more of these types of loops as we go deeper into the course. For now, run this code in Repl.it: m=4 n=3 for i in range(m): for j in range(n): print('i=',i,' j=',j) This is called a nested "for" loop because the inner "for" loop depending on the variable After you watch the video and test the examples in Repl.it, revisit the file in the "while" loop section and read through the section on "for" loops. Make sure to practice the for loop examples in Repl.it. |
||
Sometimes it is necessary to exit a loop abruptly when a certain condition is met. The "break" statement is sometimes useful for such an application. Consider this code: strval='forever' for letter in strval: if letter =='e': break print('The letter e has been found') In this case, the break statement terminates the loop if the character On the other hand, encountering a given condition within a loop may require skipping over a set of commands and effectively "fast-forward" to the next iteration. The "continue" statement is useful for these applications. Finally, the "pass" statement within a loop is a null statement that does nothing. It is sometimes useful when placed in a program where code is intended but has not yet been written. Read this page and practice the examples. |
||
3.4: Further Study | Here are some supplementary videos that you can review if you'd like a bit more practice the concepts in this unit. |
|
4.1: Python Lists | A list is a data structure capable of storing different types of data. Run this set of commands in Repl.it: a=2 b=3 alist_examp=[1,3.4,'asdf',96, True, 9.6,'zxcv',False, 2>5,a+b] print(alist_examp) print(type(alist_examp)) print('This list contains ', len(alist_examp), ' elements') You should see the list output to the screen as well as the data type of the variable The data contained within the list are called elements. The list you printed contains 10 elements. You can figure this out by counting them by hand. There is also a command called len that will give you this information, which you can see in the example. len is a very useful command. Pay very close attention to the syntax used to build the list. The left square bracket/right square bracket is known as a "container". Elements must be separated by a comma when building the list. Pay very close attention to this example: tmp=alist_examp print(tmp) print(alist_examp) tmp[3]='vbnm' print(tmp) print(alist_examp) Notice that changing the value in the variable tmp also changed the value in the variable alist_examp. Initially, this appears to go against what we have learned about the assignment operation (=). For reasons that will be discussed in a later unit, when
it comes to lists, Python views both variables as occupying the same space in memory. They are different names that refer to the same data. How then can we truly assign the list to a new variable that occupies a different place in memory and can be
modified independently of the variable tmp=alist_examp.copy() print(tmp) print(alist_examp) tmp[3]='vbnm' print(tmp) print(alist_examp) This example introduces some new syntax that will soon become second nature. The command "alist_examp.copy()" is your first introduction to object-oriented syntax. The "copy()" portion of this command is what is known as a method. It is connected to the variable alist_exmp using the period or 'dot notation'. This command makes a true hard copy of the variable alist_examp so that modifications of tmp do not affect alist_examp. Every variable type in Python is what is known as an "object". You will learn an immense amount about objects as we delve deeper into the course. The main point to realize is that there are several methods available for use with lists. The
|
|
Read this for more on indexing. |
||
It is often the case that a program requires referencing a group of elements within a list (instead of a single element using a single value of the index). This can be accomplished by slicing. Consider running this example: x=[101,-45,34,-300,8,9,-3,22,5] print() print(x) print(x[0:9]) The colon operator can be used to index multiple elements with the list. The index on the left side of the colon (:) is the starting index. By Python's indexing convention, the value on the right side of the colon (:) indexes that value minus one (be careful with the right index). Since the variable print() print(x[3:4]) print(x[3:5]) print(x[3:6]) print(x[3:7]) print(x[3:8]) print(x[3:9]) Again, you should be careful when using the right index since Python will sequence up to that value minus one. For the sake of convenience, there are also shorthand slicing techniques that do not require specifying the start or ending index when it assumed the complete rest of the list is being referenced: print() print(x[3:]) print(x[:4]) In addition to specifying the start and stop indices, you can also specify the "step". Here is an example that will count by twos from element 3 to element 7 (every other element starting at index 3). The step size is given by the index value after the second colon. print() print(x[3:8:2]) Finally, Python allows for negative indices where, by convention, the index -1 implies starting from the end of the list. print() print(x[-1]) print(x[-1:-3:-1]) print(x[-1:-len(x)-1:-1]) In these examples, the step size of -1 means to count backwards in steps of -1. This video reviews many of the list concepts we have discussed so far. At 6:11, it discusses and elaborates on the rules for slicing in Python. Be sure to follow along and practice the examples in Repl.it. |
||
Practice these examples using Repl.it to become more familiar with some methods commonly applied to lists. As you go through these examples, you should begin to see how powerful Python can be as a programming language. |
||
Python offers many opportunities for creating efficient programming structures. When it comes to writing loops, 'list comprehension' allows for very compact code. It is possible to pack quite a bit of power using just one line using lists. This is an optional topic that requires understanding how to write loops using lists. Practice the examples to expand your ability to write loops. |
||
4.2: Strings Revisited | Read this for more on strings. |
|
There are a host of methods available for processing string objects. Here are a few examples. At this point it is sensible to introduce the comment character, #. The comment character allows you to put comments into your code for the purpose of documentation. While comments are not considered executable code, they are extremely useful for making your code readable and understandable. #explore changing to uppercase and lowercase a='good' c=a.upper() d=c.lower() print(c) print(d) #join a list of strings together with a space in between the strings b='morning' e=' '.join([a,b,'today']) print(e) #find a string within a string #find method returns the first index where string was found x='a picture is worth a thousand words' x1=x.find('picture') print(x1) x2=x.find('worth') print(x2) x3=x.find('words') print(x3) #split up a string into a list of smaller strings #use the ' ' space character as the boundary (delimiter) to split up the string y=x.split(' ') print(y) print(type(y)) #try the replace method ... z=x.replace('thousand', 'million') print(x) print(z) Take some time to explore your own versions of these examples. |
||
4.3: Data Visualization Application | In this section, you will have a chance to exercise your understanding of lists and indexing and apply your knowledge to plotting data. You will also learn how to import libraries into Python. A library in Python generally contains several methods that can be used to perform a specific set of functions. The matplotlib library contains a host of methods useful for plotting data. Try running this snippet of code in Repl.it: import matplotlib.pyplot as plt x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y=[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] plt.plot(x,y) plt.xlabel('X') plt.ylabel('Y') plt.title('Test Plot') plt.show() plt.savefig('plot1.png') The Make sure to mirror and practice the examples provided in the video tutorial in Repl.it. |
|
5.1: The Basics of Functions | Read this for more on functions. |
|
5.2: Some Useful Modules | Before delving into some Python libraries dealing with applied mathematics, visit this optional site to review trigonometry if you need a refresher. |
|
Programming also involves simulating random experiments such as flipping coins or rolling dice. If you need to review these topics, visit this optional site for a refresher. |
||
We have already seen using the import command for importing the matplotlib library and the numpy package. Much of Python's power rests in the vast collection of packages, libraries, and modules available for just about any application you could think of. The math module contains a host of mathematically oriented methods typical of what a programmer would need to perform basic calculations. Consider executing this set of instructions: import math a=math.exp(1) print(a) b=math.pi print(b) x=100 print(math.log(x,10)) print(math.log10(x)) y=math.pi/2 print(math.cos(y)) print(math.sin(y)) y=8 z=1/3 print(math.pow(y,z)) Notice once again the object-oriented dot notation for calling a method. Just about any function that can be calculated on a sophisticated calculator can be performed using the math module. For the sake of simplifying the code, if you know exactly what methods are needed from a given library, you can select a subset using the from math import exp, pi, log, log10, cos, sin, pow a=exp(1) print(a) b=pi print(b) x=100 print(log(x,10)) print(log10(x)) y=pi/2 print(cos(y)) print(sin(y)) y=8 z=1/3 print(pow(y,z)) Now all the math method calls look exactly like function calls. Sometimes it is more convenient to use the reduced representation. |
||
5.3: Application | While this example is not how we would perform encryption in practice, it is highly instructive for reviewing concepts covered so far regarding user-defined functions. Implement this example in Repl.it in order to solidify your working knowledge of Python. |
|
6.1: Immutable Collections | We have introduced the concepts of mutable and immutable objects in Python. Recall that lists are mutable while strings are immutable. This section introduces two more immutable data types useful for holding collections of objects: tuples and sets. In short, tuples are immutable lists. Similar to strings, they cannot be changed once they have been assigned. Everything that you have learned so far about indexing and slicing also applies to tuples. The syntax for forming a tuple uses parentheses (instead of square brackets for forming a list): a=[23.7, 45, 78] b='asdfasdf' c=(4,9,a,b,'zxcv') print(c) print(type(c)) Notice that we can put any object we please into the tuple defined as the variable Sets are another immutable data type that holds a unique collection of objects. Sets can be used to perform typical set operations such as union, intersection, set differences, and so on. Duplicates values are not possible within a set. Left and right squirrely brackets are used to assign sets. a={3,4,5,6,7,9} print(a) print(type(a)) b={3,3,3,4,4,4,5,5,6,7,8} print(b) print(type(b)) You should observe that both a={3,4,5} b={4,5,6,7,8,9} c=a.intersection(b) print(c) d=a.union(b) print(d) e=8 print(e in b) print(e in a) f=b.difference(a) print(f) This code introduces fundamental operations such as set membership (using the |
|
6.2: Mutable Collections | Read this for more on dictionaries. |
|
One major application of dictionaries is to be able to efficiently sequence through a set of values. Read this section to practice writing loops using dictionaries. |
||
Another application of tuples is to use them as keys in dictionaries. Follow and practice the examples presented in this section in order to understand how tuples can be used with dictionaries. |
||
6.3: A Comprehensive Review of Data Structures | We have introduced several basic Python data structures: lists, strings, sets, tuples and dictionaries. Take some time to review, compare and contrast these constructs for handling various kinds of collections. |
|
7.1: File Input and Output | File input and output (or File I/O) is the ability to read data from and write data to files stored in a location such as a directory or a folder. The ability to handle files is actually a pretty deep subject that requires some measure of interaction with the computer operating system. Fortunately, for high-level languages such as Python, the nuts and bolts of file I/O are absorbed into a relatively simple set of methods. There are three major steps to referencing a file:
Here is an example of the three steps you can try in Repl.it: fhandle = open('examp.txt','w') fhandle.write('This is a write example. ') fhandle.write('Text will be sequentially written until a newline control character occurs. \n') fhandle.write('Then a new line will begin with \n') fhandle.write('and another new line, etc \n') fhandle.close()
The syntax for implementing the above step is fairly straightforward:
Try adding the following code to the above script: f2 = open('examp.txt','r') print(f2.read()) #the 'read' method reads the file f2.close() You now have the ability to create a file, as well as read data from and write data to a file. The files source.txt, source2.txt, and source3.txt are provided here. You should upload them into the leftmost window in Repl.it for your code to reference them for a file read. You can then practice the examples on this page. |
|
Now that you're familiar with file input and output, read this for more on syntax and usage. |
||
7.2: Visualizing Data from a File | The next project will require a couple of steps to set up. First, download these files. Then, Start a new Repl.it session and either upload or 'drag and drop' these three files into the leftmost window. The "csv" stands for comma-separated values. This is a common data file type that is readable by programs such as Excel. We do not need to grab the other data files as we will challenge the Repl.it graphics capability with these three files. Once you can see the data files listed in the Repl.it leftmost window, feel free to copy the code in the example provided into the Repl.it run window and run the code. This example is very instructive as it ties together the reading of multiple data files and the use of numpy combined with matplotlib introduced earlier in the course. After the code runs, you should see a graph appear in the rightmost window. On the graphic, click on the resize box in the upper left-hand corner to resize the figure. Make sure you see plots similar to those given in the example. |
|
After you download the files above, complete this exercise. |
||
8.1: The "re" Module | A regular expression (or "regex") is a character sequence used to search for patterns within strings. You've already seen examples of pattern searching when we looked at strings. Regular expressions have their own syntax, which enables more general and flexible constructs to search with. The "re" module in Python is the tool that will be used to build regular expressions in this unit. Practice these examples to familiarize yourself with some common methods. You will also practice building more general regular expression patterns using the table of special characters. |
|
The subject of regular expressions is quite deep, and it takes an immense amount of practice to get used to the special character syntax. Furthermore, the re module contains a vast set of methods available for performing searches using regular expressions. Upon completing the examples in this section, you should have a much deeper appreciation for how powerful regular expressions can be. |
||
8.2: Processing File Data | Now, we will practice regular expressions and file handling. First, download this text file. After you download this file, upload it into the leftmost window in Repl.it to ensure file reads will be able to access the data. |
|
Watch these videos and follow along using the file you just downloaded. |
||
9.1: Catching and Handling Errors | When writing software, as you may have experienced already, errors can occur. As we gain experience, we will learn to anticipate what kinds of errors can occur during program execution. For example, when performing a division calculation num/den between two variables "num" and "den", it is possible for the variable den to contain a value of zero. If this happens, a "division by zero" error should be generated to avoid a catastrophic calculation. Exceptions are a way of catching and handling potential errors so that a program will not crash and stop executing in an abrupt, untimely fashion. The video provided in this subsection is essential for new programmers because the types of errors that can occur must be identified, discussed, and understood. The discussion on handling errors will be used as a springboard for understanding the rest of this unit. |
|
The "try" and "except" commands are the gateway for handling errors. "try" allows you to try to execute your code, and "except" identifies the type of error to be handled. Python contains many built-in exceptions that can be raised using the "except" command. For example,
|
||
This example shows how to handle a division by zero error by raising the built-in ZeroDivisionError exception. Make sure to practice executing this code in Repl.it. |
||
Well-structured code attempts to identify everything that can go wrong as well as everything that can go right. The "else" and "finally" commands, while optional, are important components of professionally written code. The "else" command can be used as part of a "try-except" block to execute code if no errors in the set of errors being tested have occurred. The "finally" section of code will always run, but it helps to programmatically delineate such code from a software organization perspective to distinguish it from code that is being checked for errors. |
||
Now that the motivation and some syntax for exceptions has been presented, we can delve a bit deeper into the structure of writing programs containing exceptions. The following lesson is designed to help put into context the rudiments just presented. In addition, one more important component of exception handling is the 'raise' statement which is useful for raising an exception if, for example, it occurs inside an exception handler. |
||
This set of examples reviews the try, except, and raise commands. Make sure to practice them. All too often in introductory programming courses, the practice of handling errors, if taught at all, is brought up as an afterthought or some ancillary programming feature. Nothing can be further from the truth. To become a professional programmer, testing, debugging, and creating bulletproof software lies at the heart of software design. This is why alpha and beta versions exist. You can set yourself apart by refining your expertise in exception handling. |
||
9.2: Handling a File Error | As already pointed out in the exceptions lesson, Python contains a vast set of built-in exceptions. One important class has to do with file handling. The example presented in the lesson will help to review file handling methods and put them in the context of handling exceptions. |
|
10.1: Overview of Object-Oriented Programming | We have been learning, accessing, and applying methods available in Python (it would be impossible to teach Python without doing so). Although the syntax and use of these methods are inherently object-oriented, we have been using them in the context of procedural program design and in the form of structured programs. Recall that procedural programs use functions as a way of breaking a program down into a set of procedures to solve a problem. Read this page to learn why we have been arranging our programs the way we have. |
|
It is important to understand how object-oriented programs differ from procedural programs. The main goal of object-oriented programming is to allow the problem being solved to dictate the class design. For instance, a house is organized as a function of its rooms: living room, kitchen, bedroom, and so on. Each room is organized as a function of its furniture and its use. Each room could define a new class containing attributes that define the furniture and methods that define their use. The process of breaking a problem down into a set of classes each with its own set of attributes and methods is called data abstraction. This process is in stark contrast to procedural programming. Read this page to see how these approaches differ. |
||
10.2: Object-Oriented Programming (OOP) | Read this page to learn more. |
|
Read this for more on creating classes and methods. |
||
Python is packed with a vast set of magic methods. Before delving deeper into class constructions, it is a good idea to gain some more perspective on this subject. |
||
This video demonstrates class construction with a balanced mix of magic methods and user-defined methods. You may need to refer back to the Basic Terminology section to understand how the |
||
10.3: Derived Classes | Read this for more on inheritance. |
|
The inheritance examples we've looked at so far have been short so that we can get the basic points across. Consider this example to practice working with a larger-scale object-oriented program. |
||
10.4: Applying Object-Oriented Programming | This is an excellent example of boolean operations like AND, OR, and NOT. Following and implementing this example in Repl.it will help you review the OOP concepts in this unit. |
|
Study Guide | ||
Course Feedback Survey |