Table Of Contents
- Overview
- Development Shells/Environments
- Introduction to Simple Python Commands
- Algorithms and Programs
- Identifiers and Variables
- Comments
- User Input and Program Format
- Operators and Operands
- Execution Sequence Control
- Exception Handler
- Python Modules
- Integrated Development Environment
- Object-Oriented Python
- Large Python Projects
- Footnotes and Additional Websites with Python Information
Overview
Python is an object-oriented interpreted language. It is designed as a cross between compiled and shell-script languages and is often used in web page design. Being an interpreted language, it is machine independent. Downloads and Tutorials are available on Python’s website, along with connections between Python programmers and organizations who need Python programmers. It can be used like an UNIX shell-script since Python has its own interpreter. To enhance C and C++ code, you can embed the Python interpreter in each. There are ways of also working with Java. It is an extensible language with module development encouraged. According to the developers of Python, it is the best of both worlds being able to do what compiled languages do without the overhead of compiling and linking and being easily portable like other interpreted languages.
I have primarily used the Python website and the edX Python course from the University of Texas [1] as the basis of this discussion.
Python is named after the Monty Python Flying Circus, references to that show in any code you write is encouraged. They emphasize that it is not named after the snake. Guido van Rossum is the original author of Python. Guido invented Python while working at CWI (Stichting Mathematisch Centrum) in the Netherlands. He had worked with an instructional language named ABC, but found it too restrictive. During a Christmas break, he decided to make a more open system that could be easily used by UNIX/C programmers. He drew some ideas from Module-3. To be able to be executed on multiple platforms, the character set that is used by all commands within the program is ASCII (American Standard Code for Information Interchange) while strings can use the UNICODE character set UTF-8 co-developed by the International Standards Organization (ISO). The UTF-8 link is to the Python history of character set development, which is a good starting point for that discussion. Most of the time you will only need the ASCII character set so that you do not have to worry about the needed character encoding that is required with UNICODE use. If you do require true UNICODE usage, you may have to put different headers on your file depending on if you are using a UNIX or WINDOWS based system. I am sure there might be variations for iOS and Android systems also.
Development Shells/Environments
The Python Command Line Shell (left) is white on black with a fixed-size font. The Python “Integrated DeveLopment Environment” – IDLE (right) is black on white with a variable sized font and many other options. Since I plan to show Python Development, I will only use the Python IDLE. IDLE is used by Python to differentiate it from other Integrated Development Environments (IDE). Both have the version information at the top and a prompt (“>>>”) at the bottom. The IDLE has a Tool Bar or Menu Bar. The first thing I did when bringing up the IDLE is to increase the font size to make it easier to read. This can be done under the Option menu.
Introduction to Simple Python Commands
Here is a sample of the Python IDLE with a sampling of some basic commands. Simple calculations can be done. It does honor the PEMDAS rules, doing parenthesis before multiplication. Variables can be defined and stored. If you try to use a variable before it is defined, it will give you an error message. The print() command will print out all arguments listed, with a space in-between each parameter (this is different than most other languages, so be aware of this in the various languages you program). As you are typing a command, Python will display a yellow banner with the syntax for that command.
Algorithms and Programs
Programs are based on Algorithms. An Algorithm is a set of instructions on how to do a particular task. They can come in any language and the human brain is smart enough to see any small misstatements that may need to be corrected. For example, if I created an algorithm about how to change a tire and went straight from loosen the lug-nuts to take off the tire most people would realize that I would have to take off the lug-nuts before I could take off the tire. Computers are not as “smart.” They need to be told every step and will do exactly as you tell them to do each of the steps. Programs can be written in many different computer languages, from machine code (binary) through Assembler and into higher-level languages like Python. Be grateful for the higher-level languages.
In Python you can continue to type in all the lines of a program in the Python shell or you can create a program file and store the steps there. For example, I want to convert kilometers to miles, I know the algorithm is to divide the number of kilometers by 1.6 to calculate the distance in miles. In the example, I print what the purpose of the program is, then enter the value of the kilometers, do the calculations, and then print the results in a way that is easy for a user to understand those results. Make sure that all of your Python executables are saved with the suffix .py.
Identifiers and Variables
Identifiers and Variables are not the same. Variables are defined by their data type and name. Identifiers are the name of variables, methods (routines usually found within a class), and other needed items in a program. There are certain rules for naming variables.
- Variable names must start with either a letter or underscore.
- They can contain underscores, letters, or numbers.
- They cannot contain spaces or special characters.
- Variable names are limited to the ASCII character set.
- Variable names are case sensitive. “m” is not the same variable as “M” in any circumstance.
- Variable names cannot be a reserved word (like “if” and “else”).
- In most object-oriented languages, variables begin with a lower case letter. They consist of words strung together with each new word being started with a capital letter (like “iAmVariable”).
- Some Python users prefer using underscores between the words (like I_am_variable).
- Special purpose variables that the programmer wants to distinguish from other variables will begin with an underscore (“_”).
- Variable names should be descriptive as possible (like “miles”, “squareRoot”, “studentName”, “student_address”, “circle_radius”).
Types of Variables
Python has many types of variables, but we will cover the four basic ones here.
Type | Example | x | print(x) | print(type(x)) |
---|---|---|---|---|
Integer (int) | x=3 | 3 | 3 | <class ‘int’> |
Decimal (float) | x=3.0 | 3.0 | 3.0 | <class ‘float’> |
String (str) | x=”Programs” | ‘Programs’ | Programs | <class ‘str’> |
Boolean (bool) | x=True | True | True | <class ‘bool’> |
Please note on Boolean variables, they can have the value of True or False with an upper-case first letter. Any other spelling is not understood and will produce an error message. Also notice the difference between the x and print(x) outputs for the x=”Programs” line.
Python does not use variable declarations like most other computer languages. It determines the type of variable based on what it is assigned. As the above table indicates, if you reassign the same variable name to a different type, the variable type will change as needed. Declaring variable types in python cannot be done.
Comments
Comments are used to describe some aspect of a program. They are especially useful describing the purpose of the program or module, who wrote it, who is maintaining it, any needed information to help in the maintenance of the product. Within the code, explaining the underlying algorithms and how they are used can be very helpful. This is especially true if you have run into problems in a certain part of code where you know how it is to be maintained to avoid re-introducing defects that have been hard to find in the past.
In Python, all comments start with a pound or hash sign (“#”). All characters after the # are part of the comment. The way I would comment the code I used above would be:
# KM_to_Miles.pv - 30 September 2016 # Programmed by Wayne Cook Revision 1.1 # This program takes the distance in Kilometers and translates it into # miles. It then prints out the answer in a form that is easily read. print("Convert kilometers to miles") km=260 # For now, the kilometer distance is hard coded. miles=km/1.6 # There are 1.6 km to the mile, do the conversion. print(km,"kilometers is",miles,"miles")
User Input and Program Format
The example above used a fixed value for input for kilometers (km). Normally, most programs will allow a user to input the value for km. This is done by an input command with an optional prompt for the following form. Input() reads the user input as a string. In order to convert it to a floating point number, the input has to be converted (or cast) to a floating point number:
var=input([Prompt]) i.e. km=float(input("Distance in kilometers: "))
Since going through the program once would not be a satisfactory program for me, I allow the user to enter as many kilometer distances to convert as is wanted. I just request that the user types a zero (“0”) when no more conversions are desired. In Python this is done in a while loop. I then also determine, based on the km input, whether an output is desired or a flag set to end the while loop. This is done with an if-else statement pair. Please notice in the example below that Python uses a colon (“:”) at the start of a new indented block of code and uses no curly braces like many other languages. It uses a format more akin with the POSIX shell. The number of lines to be executed in each block is strictly determined by the indent (created by a TAB). Please use your indent wisely. Also notice that there are no semicolons (“;”) at the end of each line. The code I created for this is:
#KM_to_Miles.pv - 30 September 2016 # Programmed by Wayne Cook Revision 1.2 # This program asks for the distance in Kilometers and translates it into # miles. It then prints out the answer in a form that is easily read. loopCheck = True # Set up so while will execute the first time through. print("Convert kilometers to miles, type 0 to exit.") while loopCheck: km=float(input("Distance in kilometers: ")) # Ask the user for km distance if ( km > 0 ): miles=km/1.6 # There are 1.6 kilometers to the mile, do conversion. print(km,"kilometers is",miles,"miles") else: loopCheck=False print("Thank you for using our conversion program.")
If I had left the last print() statement at the same indent level as the if: and else: statements, the program would have probably worked just fine. Since I want to have the print() statement execute just before the program exits, I put it on the same level as the while loopCheck: statement. This means it is not in the while loop. After writing this program, to execute it, press F5. The output (and input) for this program in the shell is:
>>> RESTART: C:\<Path>\KM_to_Miles\KM_to_Miles.py Convert kilometers to miles, type 0 to exit. Distance in kilometers: 25 25.0 kilometers is 15.625 miles Distance in kilometers: 67 67.0 kilometers is 41.875 miles Distance in kilometers: 0 Thank you for using our conversion program.
One more variable Python is a list, which could be considered a set of any variables in a list. The list can be accessed either starting from the left at list[0] or from the right starting at list[-1]. An example of code that will take a list and average it looks like the following. I do append one item to the list. To add some value to the variable without typing the variable name twiceOperators , I use the assignment “+=” to indicate I am adding something to the variable named on the left of the += sign. The code looks like:
# Sample list - Wayne Cook sample_list = [2, 10, 3, 5] sample_list.append(15) # Append can take only one argument list_size = len(sample_list) print("The list size is", list_size) print("The list is:", sample_list) list_index = 0 list_sum = 0 while list_index < list_size: list_sum += sample_list[list_index] list_index += 1 list_average = list_sum/list_size print("The list average is",list_average) # Positive indexing starts from left with the first item being index "0" print("First item", sample_list[0]) print("Third item", sample_list[2]) print("Last item", sample_list[-1]) print("Third item", sample_list[-3])
And the output looks like:
The list size is 5 The list is: [2, 10, 3, 5, 15] The list average is 7.0 First item 2 Third item 3 Last item 15 Third item 3
Operators and Operands
Operators are the mathematical symbols that represent mathematical constructs that tell the computer what to do with the operands surrounding the operator. Operands can either be binary, where they have operands (values) on both sides or unary where they only modify one operand.
5 - 3 # Binary operator -3 # Unary operator
Types of Operators
Operators either do some calculation and perhaps assign that result to a value or they create a < span="">< span=""> href=”https://cookhealthalliance.com/computers/software-languages/boolean-algebra/”>Boolean (True or False) answer. The Calculation/assign operators are mathematical, assignment, and bitwise operators. The Boolean operators are logical, comparison, membership, and identity. Each serve a specific purpose. Because the carrot or up-arrow (“^”) is used in bitwise operations, it cannot be used as a mathematical operator.
Calculation and Assignment Operators
This Operators produce non-Boolean results, actual calculations for the Mathematical operators. The Assignment Operators may do some calculations, but their main purpose is to point a variable to the resulting calculation.
Mathematical Operators
Mathematic operators are the standard symbols used by most other programming languages, except for the symbol for exponents. Most other programming languages use the carrot or up-arrow (2^3) to indicate 2 to the third power. In Python the double asterisk is used instead (2**3) for 2 to the third power. Mathematical Operators require numbers as operands. Any other variable type will cause an error and a halt to the execution of any program.
Operator | Definition | Example |
---|---|---|
+ | binary addition operand, unary positive number sign | 3+2, +6 |
– | binary subtraction operand, unary negative number sign | 3-2, -6 |
* | binary multiplication operand | 3*2 |
/ | binary division operand – answer always calculated as a float. | 3/2 |
** | binary exponent operand – this is different from the often used carrot (“^”> used by many other languages. It means you multiply the number to the left of the ** by itself the number to the right number of times. | 3**2 |
% | binary modulus operand – remainder of x divided by y where x%y. | 3%2 |
// | binary floor division operand – answer always calculated as a whole number, may be presented as either an int or float. | 3//2 |
~ | unary compliment operand – Gives the complementary integer surrounding “0”. The complement of 0 is -1, the complement of -6 is 5. Actually a bitwise inverse, 0 is all 0’s, so its inverse is all 1’s which is -1. | ~8 or ~-71 |
Assignment Operators
Assignment operators all include the equal sign. The first is a straight equal sign (“=”), the rest have a mathematical operator in front of the equal sign. The purpose of the combination operator is to allow a user to use the mathematical operator with the first Operand to it being the variable listed to the left of the combined operand. I will give short examples in the combination assignment statements
Operator | Definition | Example |
---|---|---|
= | do the calculation to the right of the equal sign and assign the resulting value to the variable named on the left of the equal sign. | x = 2*2-3 |
+= | add the value calculated on the right of the assignment operand to the value of the variable to the left of the operand, store the resulting answer in the left variable. | a += b use instead of a = a + b |
-= | subtract the value calculated on the right of the assignment operand from the value of the variable to the left of the operand, store the resulting answer in the left variable. | a -= b use instead of a = a – b |
*= | multiply the value calculated on the right of the assignment operand by the value of the variable to the left of the operand, store the resulting answer in the left variable. | a *= b use instead of a = a * b |
/= | divide the variable to the left of the operand by the value calculated on the right of the assignment operand, store the resulting answer in the left variable. | a /= b use instead of a = a / b |
**= | take the value of the variable to the left of the operand to the power calculated on the right of the assignment operand, store the resulting answer in the left variable. | a **= b use instead of a = a ** b |
%= | divide the variable to the left of the operand by the value calculated on the right of the assignment operand, store the remainder (modulus) in the left variable. | a %= b use instead of a = a % b |
//= | divide the variable to the left of the operand by the value calculated on the right of the assignment operand, store the truncated whole number answer in the left variable. | a //= b use instead of a = a // b |
Bitwise Operators
Bitwise operators act on the bits of integer(s).
Operator | Definition | Example |
---|---|---|
Test Values | These will be the test values used for the examples. | a=53=’0b0110101′ b=85=’0b1010101′ |
& or AND | If the same bit in both operands is 1, then the resulting bit in the resulting operand would be 1. | a&b 21 or ‘0b0010101’ |
| Binary OR | If a bit in either operand is 1, then the resulting bit in the resulting operand would be 1. | a|b 117 or ‘0b1110101’ |
^ Binary XOR | If a bit in either, but not both, operands is 1, then the resulting bit in the resulting operand would be 1. | a^b 96 or ‘0b1100000’ |
~ Binary ones complement | Flip all the bits in a binary number from 0 to 1 or 1 to 0. Note that a negative sign in front of a binary means all the bits in the binary number are flipped. | ~a=-54=’-0b110110′ ~b=-86=’-0b1010110′ |
<< Binary Left Shift | Move the bits in the left operand to the right by the number of positions specified in the right operand. | a<<2 212 or ‘0b11010100’ |
>> Binary Right Shift | Move the bits in the left operand to the right by the number of positions specified in the right operand. | b>>2 21 or ‘0b00010101’ |
The operators “and” and “or” are overloaded operators. They can either do logical (Boolean) tests or they can do bitwise “and” or “or” functions. To see this more clearly do the following steps.
bin(4) bin(5) bin(4 and 5) bin(4 or 5)
You can see the proper bitwise “and” and “or” are done. Be careful of how you use “and” and “or” to make sure that you are using them correctly.
Boolean Operators
Boolean operators produce a True or False answer. If other values are passed into an operator that expects a Boolean value, it will interpret non-zero values as True and zero values as False.
Logical Operators
Logical operators are the standard Boolean operators. The binary operators are AND & OR, while the unary operator is NOT. XOR is not an implemented Logical Operator. For an example of how to use Logical Operators with the “if” statement, please see the User Input and Program Format section above.
Operator | Definition | Example |
---|---|---|
AND | Test to see if both operands are True | bool1 AND bool2 |
OR | Test to see if either operand is True | bool1 OR bool2 |
NOT | Test to see if the compliment of the operand is True | NOT bool1 |
Comparison Operators
Comparison operators use Boolean logic to determine the truthfulness of the comparison. They compare the computed values to the left and the right of the operator. The following information is based on the other referenced sources and Tutorial Point’s Python Basic Operators Page.
Operator | Definition | Example |
---|---|---|
== | Test to see if both operands have the same values. Be sure to use the two equal signs, one equal sign is an assignment statement and not a comparison. | a == b |
< | Test to see if the left operand is less than the right operand. | a < b |
> | Test to see if the left operand is greater than the right operand. | a > b |
<= | Test to see if the left operand is less than or equal to the right operand. | a <= b |
>= | Test to see if the left operand is greater than or equal to the right operand. | a >= b |
!= | Test to see if the operands do not have the same values. This one has worked for me on tests with Python 3.5. | a != b |
<> | Test to see if the operands do not have the same values. This one is documented but has NOT worked for me on tests with Python 3.5. | a <> b |
Membership Operators
Membership operators use Boolean logic to determine the truthfulness of the membership query. They determine if the item or content of the variable to the left of the operator is a member of the list to the right of the operator. The following information is based on the other referenced sources and Tutorial Point’s Python Basic Operators Page. Please remember that a single quoted string is really a list of characters. If there are quoted strings as elements of a list, tests for portions of element strings will return false.
Operator | Definition | Example |
---|---|---|
Defined | Variables in the Example column use the following variable assignments. | sample_list = [2, 10, 3, 5, 15, “science”] a=5 b=7 string=”computer science” |
in | Returns True if the item referenced to the left of the operand is in the list to the right of the operand and False otherwise. | a in sample_list -> True b in sample_list -> False “sci” in string -> True> “sci” in my_list -> False |
not in | Returns False if the item referenced to the left of the operand is in the list to the right of the operand and True otherwise. | a not in sample_list -> False b not in sample_list -> True “sci” not in string -> False “sci” not in string -> True |
Identity Operators
Identity operators use Boolean logic to determine whether both variables are referencing the same memory location. They compare the items being reference to the left and the right of the operator. The following information is based on the other referenced sources and Tutorial Point’s Python Basic Operators Page.
Operator | Definition | Example |
---|---|---|
Defined | Variables in the Example column use the following variable assignments. | a=5 b=7 c=a |
is | Returns True if the item referenced to the left of the operand points to the same memory location as the variable to the right of the operand and False otherwise. | a is b -> False a is c -> True a is 5 -> True |
is not | Returns False if the item referenced to the left of the operand points to the same memory location as the variable to the right of the operand and True otherwise. | a is not b -> True a is not c -> False a is not 5 -> False |
Execution Sequence Control
All programs executed a statement after the previous statement in the order they are written. This can be changed by specific commands, like If, Elif, Else conditional executions, loops, and procedure, method, or subroutine calls. This section addresses some of those Execution Sequence Controls. As was stated previously, Python does not use curly braces (“{“,”}”) to group statements under Executive Sequence Control statements like if and loops (i.e. while). Python uses tab indentation. Everything that follows one of these that is at the same tab indent level is part of the sequence.
If…Elif…Else
The most basic control is the if statement. It has the form:
if <Boolean Operator>: Statement(s) to be executed # One tab stop in
The else statement is added when there is something that needs to be executed when the if statement Boolean Operator is false. The elif is used after the group of statements under the if statement, if an additional Boolean Operator check needs to be performed before some addition statements need to be executed.
If I wanted to assign grades to test scores, I could use a series of if…elif…else statements. For example:
#grades clculator - Wayne Cook # 3 October 2016 # Given a score based on a 100 point scale, calculate letter grade # Since I am starting at the top and working down, I only need to check # for the low end of the range for each elif, not both ends. score = int(input("Enter student score (0-100): ")) if score == 100: grade = "A+" elif score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F" print("The student's grade is", grade)
When calculating the grades on my own, I use a lookup table. This shows how to use the statements being described. Again, as a reminder, the input() command returns a string. Therefore, I have to cast the input to an integer value in the statement score = int(input(“Enter student score (0-100): “)). Also, the print statement is purposely put back at the same indent level as the if statement so that it will always be executed. The printstatement always puts in a space between each print element, so a space is not needed to be added to the end of a string. When you become a more advanced programmer, you will also always put a check to make sure the input typed is valid. In this example, if you typed in a letter instead of a number, the program would have an error exit.
While Loop
The while loop iterates until the test condition is no longer True. For example, if I wanted the user to type in a number and find its factorial, my code would look like:
# factorial_loop - Wayne Cook # 3 October 2016 # Print the factorial of the entered number number = int(input("Enter a positive integer: ")) factorial = number count = number while count > 1: count -= 1 factorial *= count print("The factorial of", number ,"is", factorial)
For Loop
The for loop is used to either sequence through a list or do a loop n number of times. An example of using lists is to see if a member of one list is also a member of another list. As a side note, the python environment will show you the approximate position of an error. I accidently put a period (“.”) in a list instead of a comma (“,”). The error showed up on the closing quote (“) of the following string element. Just be careful. The sample for loop for lists code is:
# pet_check - Wayne Cook # 3 October 2016 # This program has two lists, my_pets list and a to_check list. # It will go through the to_check list using a for loop to see which pets # actually are mine. my_pets = ["parakeet", "cat", "goldfish"] to_check = [ "python", "parakeet", "dog", "giraffe", "goldfish", "kangaroo"] for x in to_check: if x in my_pets: own = "is" else: own = "is not" print("the", x, own, "one of my pets") print("That is the end of the pet check list")
If you want to traverse a number list and you know the starting point, stopping point, and increment step; then using a range instead of a list is preferred. The format for range() is:
range([start,] stop [,step]) # The start and step are optional, the test for stop # is the increment less than the absolute value of the stop # value, possible values could be: range(4) # Values 0 through 3 increment 1 range(3,7) # Values 3 through 6 increment 1 range(3, 12, 3) # Values 3 through 9 increment 3 range (7, -5, -2) # Values 7 through -3 increment -2
The final test for where to stop the incrementing is less than the absolute value of the stop value. For example, the range(3, 12, 3) can only go up to 9 before the for loop exits. Likewise, range (7, -5, -2) can only go to -3 before the for loop exits. An examples is:
# for_temperature - Wayne Cook # First range examples for range([start,] stop [, step]) print("Start for loop 1") for i in range(4): print("Count", i) print("Start for loop 2") for i in range(3,7): print("Count", i) print("Start for loop 3") for i in range(3, 12, 3): print("Count", i) print("Start for loop 4") for i in range (7, -5, -2): print("Count", i) # Do a conversion table from Celcius to Farenheit. print("Start temperature conversion for loop") steps_input = input("Type 1 for 1 increments, otherwise increments of 5: ") if steps_input == "1": steps = 1 else: steps = 5 for celcius in range(0,101, steps): farenheit = int((celcius / 5) * 9 + 32) print(celcius, "Celcius is", farenheit, "Farenheit") print("Table Complete")
Which produces
Start for loop 1 Count 0 Count 1 Count 2 Count 3 Start for loop 2 Count 3 Count 4 Count 5 Count 6 Start for loop 3 Count 3 Count 6 Count 9 Start for loop 4 Count 7 Count 5 Count 3 Count 1 Count -1 Count -3 Start temperature conversion for loop Type 1 for 1 increments, otherwise increments of 5: 5 0 Celcius is 32 Farenheit 5 Celcius is 41 Farenheit 10 Celcius is 50 Farenheit 15 Celcius is 59 Farenheit 20 Celcius is 68 Farenheit 25 Celcius is 77 Farenheit 30 Celcius is 86 Farenheit 35 Celcius is 95 Farenheit 40 Celcius is 104 Farenheit 45 Celcius is 113 Farenheit 50 Celcius is 122 Farenheit 55 Celcius is 131 Farenheit 60 Celcius is 140 Farenheit 65 Celcius is 149 Farenheit 70 Celcius is 158 Farenheit 75 Celcius is 167 Farenheit 80 Celcius is 176 Farenheit 85 Celcius is 185 Farenheit 90 Celcius is 194 Farenheit 95 Celcius is 203 Farenheit 100 Celcius is 212 Farenheit Table Complete
A simpler example is summing all the even numbers between 1 and 101. I start at 2 because that is the first even number.
# even_sums - Wayne Cook # 3 October 2016 # write a program to find the sum of all even numbers bewteen 1 and 101. sum = 0 for num in range(2, 101, 2): sum += num print(sum)
Another example is summing the numbers between 1 and a number the user types:
# sum_user_num - Wayne Cook # 3 October 2016 # write a program to find the sum of all numbers bwtween 1 and n inclusive. sum = 0 n = int(input("Type in any integer number: ")) for num in range(1, n+1): sum += num print("The sum between 1 and",n,"is",sum)
Notice how I have it go to one number larger than the one the user typed into the program so that the entered number is included in the sum. The default increment step is one.
Continue and Break
Continue and Break are used within a Loop to either skip all the remaining statements in the current iteration of the loop (continue) or leave the loop completely (break). In this example, I take a string and create a new string, ignoring all negative numbers and breaking if a string is one of the elements of the original string:
# continue_break - Wayne Cook # 3 October 2016 # On a list, go through the elements. If str, break. If +num include, # If -num ignore. start_list = [5,6,4,2,-7,8,0,1,-2,"string",5,4] end_list = [] for element in start_list: if type(element) == str: # Check the element variable type. break # String found stops list creation. if element < 0: continue # Ignore negative numbers end_list.append(element) # append to the end_list # Now print the new list print(end_list)
The results are:
[5, 6, 4, 2, 8, 0, 1]
Comments can either take the entire line or be placed at the end of the line. I find that if I line up my end line comments, it makes them much more readable.
Nested Loops
A nested loop is where one for or while loop is nested inside an outer loop. This is usually done when you have two variables or lists you want to manipulate separately, where both are needed for calculations. An example of nested for loops is a multiplication table. Because range does a less than check against the stop value, the upper limit on both loops is 13 so that it will go through 12. Notice the end option in the print statement so that I can add information to a line before printing it.
# Nested for loops - Wayne Cook # 4 October 2016 # Create a times table for x in range(1,13): for y in range(1,13): val = x * y print(val, end=' ') print()
The results would be as follows. When we get to functions, this will be cleaned up to make a nice looking table.
1 2 3 4 5 6 7 8 9 10 11 12 2 4 6 8 10 12 14 16 18 20 22 24 3 6 9 12 15 18 21 24 27 30 33 36 4 8 12 16 20 24 28 32 36 40 44 48 5 10 15 20 25 30 35 40 45 50 55 60 6 12 18 24 30 36 42 48 54 60 66 72 7 14 21 28 35 42 49 56 63 70 77 84 8 16 24 32 40 48 56 64 72 80 88 96 9 18 27 36 45 54 63 72 81 90 99 108 10 20 30 40 50 60 70 80 90 100 110 120 11 22 33 44 55 66 77 88 99 110 121 132 12 24 36 48 60 72 84 96 108 120 132 144
Functions
There are times when the same code needs to be executed multiple times in an application. This is when a function is used. How functions are defined is with the keyword def/. All functions return a value. Either a return statement is included as the last statement executed in the function or the function returns the value “None”. To make the nested loop example have a nice looking output, I added a function to determine the length of an integer:
# Nested for loops - Wayne Cook # 4 October 2016 # Count the number of digits in a number def count_digits(n): return len(str(n)) # Create a times table for x in range(1,13): for y in range(1,13): val = x * y length = count_digits(val) if (length == 1): print(end=' ') if (length == 2): print(end=' ') print(val, end=' ') print()
The output would now be:
1 2 3 4 5 6 7 8 9 10 11 12 2 4 6 8 10 12 14 16 18 20 22 24 3 6 9 12 15 18 21 24 27 30 33 36 4 8 12 16 20 24 28 32 36 40 44 48 5 10 15 20 25 30 35 40 45 50 55 60 6 12 18 24 30 36 42 48 54 60 66 72 7 14 21 28 35 42 49 56 63 70 77 84 8 16 24 32 40 48 56 64 72 80 88 96 9 18 27 36 45 54 63 72 81 90 99 108 10 20 30 40 50 60 70 80 90 100 110 120 11 22 33 44 55 66 77 88 99 110 121 132 12 24 36 48 60 72 84 96 108 120 132 144
When first designing your code, you may want to just be able to call your function, but not include any code. This is done with the keyword pass. For example
# function_pass - Wayne Cook # 4 October 2016 # Function to create a Fibonacci sequence def fibonacci(n): pass # Place holder until I can implement this routine. # Main program print("This program calculates and prints a Fibonacci Sequence") # Until a later section, we need to assume that the input is an integer number = int(input("Enter the maximum number for your sequence: ")) print(fibonacci(number))
The output would be:
This program calculates and prints a Fibonacci Sequence Enter the maximum number for your sequence: 25 None
Completing this program, it would include two functions. A nice feature of python is the double assignment statement. To calculate the Fibonacci Sequence the next number is the sum of the previous two numbers, in a double assignment, the current and next numbers can be changed in one assignment statement:
current, next = next, current + next
The working Fibonacci Sequence Program is:
# fibonacci_sequence - Wayne Cook # 4 October 2016 # Function to create a Fibonacci sequence def fibonacci(n): if n <= 0: list = [0] # I prefer to have only one return per function elif n < 2: list = [1] # You may prefer return's though, your choice else: current = 1 next = 2 list = [1,2] while next < n: current, next = next, current + next if next > n: # There is a chance that next will be larger than n break # Do not include it in the list. list.append(next) #print(next) # Debug check, leave out for now. return list # This is my one return for this function # Count the number of digits in a number def count_digits(n): return len(str(n)) # Main program print("This program calculates and prints a Fibonacci Sequence") # Until a later section, we need to assume that the input is an integer number = int(input("Enter the maximum number for your sequence: ")) list = fibonacci(number) # Now we can choose how we print out the list length = len(list) count = 0 while count < length: print(list[count], end=' ') count += 1 print()
A Sample output is:
This program calculates and prints a Fibonacci Sequence Enter the maximum number for your sequence: 1000 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Python can help you with functions, there are several built-in functions available to help you with your programs. They are on the Python Software Foundation Built-in Functions page. This page includes definitions for each of the built-in functions.
Built-In Functions
Python provides commonly used functions as built-in functions. There is a list that the Python Software Foundation provides. Many of these common functions have been used in the examples on this page. Follow the link to the Python Software Foundation page to see all the available built-in functions.
Exception Handler
The Fibonacci Sequence example had a disclaimer that we had to assume that the user would only type in integers. The way to check for this is exception handling. To add an exception handler it is added where you think the problem may occur. For example, if the input is anything but an integer, doing an int cast of the input will cause an exception. The way around this is to put a try: in front of the command that is of concern and then immediately follow it by the exception handler.
# fibonacci_sequence - Wayne Cook # 4 October 2016 # Function to create a Fibonacci sequence def fibonacci(n): if n <= 0: list = [0] # I prefer to have only one return per function elif n < 2: list = [1] # You may prefer return's though, your choice else: current = 1 next = 2 list = [1,2] while next < n: current, next = next, current + next if next > n: # There is a chance that next will be larger than n break # Do not include it in the list. list.append(next) #print(next) # Debug check, leave out for now. return list # This is my one return for this function # Count the number of digits in a number def count_digits(n): return len(str(n)) # Main program print("This program calculates and prints a Fibonacci Sequence") # Until a later section, we need to assume that the input is an integer while True: # Continue this loop until an integer is typed. try: number = int(input("Enter the maximum number for your sequence: ")) except: print("A non-integer was entered, please be careful.") continue # A non-integer input was found break # Now we can go on with the program list = fibonacci(number) # Now we can choose how we print out the list length = len(list) count = 0 while count < length: print(list[count], end=' ') count += 1 print()
The output with exception handling would be:
This program calculates and prints a Fibonacci Sequence Enter the maximum number for your sequence: bad entry A non-integer was entered, please be careful. Enter the maximum number for your sequence: another A non-integer was entered, please be careful. Enter the maximum number for your sequence: 10000 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
Python Modules
Python Modules are independent files that can be imported (included) in code that you are writing. You may write your own module to save code you want to use in multiple programs or you can use modules provided by the Python Software Foundation. By default, Python knows the path to their built-in modules, so they can be used directly. One of the provided modules is the math module which provides most of the mathematical tools you may need. Modules you have created can be imported from your current directory. There are three methods of importing functions from a module. The first is to import the module and then use its name as a prefix to the function you want to call.
import math # import the math library ... ans_sqrt = math.sqrt(num) # state module.function to execute ... ans_tan = math.tan(radians) # find the tangent, given radians
The second way to import is to state the from module and the functions to import
from math import sqrt,tan # import all functions from the math library ... ans_sqrt = sqrt(num) # module already specified, state function to execute ... ans_tan = tan(radians) # find the tangent, given radians
The third way is to state the from module and import all functions. This is best if you have multiple functions from the module to import.
from math import * # import all functions from the math library ... ans_sqrt = sqrt(num) # module already specified, state function to execute ... ans_tan = tan(radians) # find the tangent, given radians
Your own modules need to have a .py suffix to indicate they are Python files. An example would be some of the common functions I have designed and used in previous examples. A problem is coming up with a good name for each module. The module where I put all functions related to the Fibonacci Sequence is named fibonacci.py. The other module is where I have placed all my basic functions for my examples is named my_basics.py. Look carefully at the is_perfect() definition at the end of the file. I included this to show how optional parameters are handle. It has a parameter prFactors which by default is false. If I set it to True on a call to this function, then the factors of a number and its sum will be printed. Otherwise this routine prints nothing.
# my_basics.py - Wayne Cook # 5 October 2016 # Functions I find basic and needed in multiple modules # I am using one function from the math library from math import ceil # Count the number of digits in a number def count_digits(n): return len(str(n)) # Check if input is integer def is_int(n): return_val = True # Assume the answer is True, unless an exception. try: number = int(n) except: return_val = False # A non-integer input was found return return_val # Check if input is a perfect number (sum of factors, except for self, = self # The option prFactors allows the users to print all of the factors and sum. def is_perfect(n,prFactors = False): sum = 0 if prFactors: print("Factors for",n,end=':') for factor in range(1,ceil(n/2)+1): if n%factor == 0 and n != factor: # Make sure 'self' not added in. if prFactors: print(factor,end=' ') sum += factor if prFactors: print("with sum",sum) if sum == n: return True else: return False
Fibonacci.py
# fibonacci.py - Wayne Cook # Module that contains all functions related to the Fibonacci Sequence # Import my_basics functions to use here, if needed from my_basics import * # Import all functions from this module. # Function to create a Fibonacci sequence def fibonacci(n): if n <= 0: list = [0] # I prefer to have only one return per function elif n < 2: list = [1] # You may prefer return's though, your choice else: current = 1 next = 2 list = [1,2] while next < n: current, next = next, current + next if next > n: # There is a chance that next will be larger than n break # Do not include it in the list. list.append(next) #print(next) # Debug check, leave out for now. return list # This is my one return for this function
Main program, please note that I important the functions in two different ways, to show the difference.
# fibonacci_sequence.py - Wayne Cook # 5 October 2016 # Import needed functions from my own modules from my_basics import * # Import all functions from this module. import fibonacci # Import just the module. # Main program print("This program calculates and prints a Fibonacci Sequence") # Until a later section, we need to assume that the input is an integer while True: # Continue this loop until an integer is typed. number = input("Enter the maximum number for your sequence: ") if not(is_int(number)): print("A non-integer was entered, please be careful.") continue # A non-integer input was found break # Now we can go on with the program number = int(number) list = fibonacci.fibonacci(number) # Now we can choose how we print out the list length = len(list) count = 0 while count < length: print(list[count], end=' ') count += 1 print() # Determine the perfect numbers (sum of factors == number) in this range print("The perfect numbers are") for factor in range(1,number+1): if (is_perfect(factor)): print(factor,end=" ") print() # Use the optional parameter to print the factors of the number if (is_perfect(number,prFactors=True)): perfTest = "is" else: perfTest = "is not" print("Number", number, perfTest, "a perfect number")
The output would be:
This program calculates and prints a Fibonacci Sequence Enter the maximum number for your sequence: bad entry A non-integer was entered, please be careful. Enter the maximum number for your sequence: still again A non-integer was entered, please be careful. Enter the maximum number for your sequence: 1000 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 The perfect numbers are 6 28 496 Factors for 1000:1 2 4 5 8 10 20 25 40 50 100 125 200 250 500 with sum 1340 Number 1000 is not a perfect number
Integrated Development Environment
There are two IDEs that I use, Eclipse and Visual Studios. The recommended environment for Python in Eclipse is PyDev. To load, Eclipse with Java 7 must already be installed. PyDev has an installation license that references Brainwy Software Pydev; Brainwy. It supplies a page that explains how to download the Python add-ons for Eclipse. The installation must be done from Eclipse.
- Click the Help tab and choose the Instaqll New Software… menu
- An Install dialog box pops up. At the end of the blank line, press the [Add] button
- In the Add Site dialog box in the Name: line, type “Pydev and Pydev Extensions”
- In the Location: line, type “http://pydev.org/updates”
- In the Work with: line, Eclipse writes “Pydev and Pydev Extensions – http://pydev.org/updates”
- In the large box below is a list of Pydev products to install, press [Select All]
- Eclipse helps you through the rest of the process, be careful on the accepting the license dialog box as the owner of Pydev may not be a recognized owner and license. The owner is listed as Brainwy Software Pydev; Brainwy
- When you are done, you will need to restart Eclipse.
- To verify that PyDev was installed correctly, click the menu item Window>Preferences and make sure that Pydev is listed in the Dialog box
- To configure, go to Window>Preferences. On the left side of the Preferences dialog box, select Pydev>Interpreters>Python Interpreter and select all then click one of the Auto-Config boxes. The Python interpreter should be listed in the top box. If it is, click OK.
- Check the PyDev trouble shooting page if all the directories have not properly loaded.
After going through these steps, I then did a final set-up of the environment and loaded the Fibonacci Sequence example listed above. The Eclipse PyDev environment looks like:
I can then run the program and it runs correctly. But if you look carefully at the window, you will notice that the environment thinks there is a problem with the line print(list[count], end=’ ‘). When I hover over the red circle with the white X, the message is Syntax error while detecting tuple.. Something more to track down.
Object-Oriented Python
In going through this page, you have already been doing some Object-Oriented programming in Python. Objects are created with a class with methods that allow you to manipulate any instance you create. The easiest example is the Python List class. Whenever you create a list object, you are creating an instance of the List class. In most OO programming, referring to the class, the name is always capitalized. When referring to an instance (an instantiation) of the class, the name always starts with a lower case letter.
List Class
For example, you may have had an instance of the List class as:
sample_list = [2, 10, 3, 5]
If you wanted to add an element to that list, you would use the append method, like:
sample_list.append(15) # Append can take only one argument
Notice that the format for a method is instance.method() where the parenthesis at the end indicate that this is a method. Another example is when you want to make sure a list is empty, this can either be done by setting the variable to an empty list like s = [] or clearing it with s.clear(). The list class also has methods invoked by adding square brackets at the end of the list name. One dimensional lists have already been used, like print(s[i]). There are other built-in methods that the List class has that you can use. As I further explain Object-Oriented programming, I will go over how to create your own class and methods.
File Input/Output
Sometimes you might want to read the input from a file instead of always typing it in and then write the output to a file to save for later analysis. File Input and Output can be performed by the file handling class. This file I/O is based on the Python “io” class, as described in the Python Software Foundation page.
Example
You can create you own class, with defined functions that are actually class methods and act like the sample_list.append(15) instance of the List class shown above. The Class definition comes first followed by the methods. As usual in Python, attributes (variable) can either be passed into the method or defined within. Global variables are possible, but they are not recommended.
class MyWork: # Define a class to do MyWork def deal_with(self): # Define a public method that anyone can call. pass # Remember that 'pass' causes a successful exit. def __hidden(self): # __ in front of a method will cause a mangled name # mangled to _MyClass__hidden so not easily seen outside of this class, thus local pass ---------------- # Start main program cl = MyWork # Create an instance of MyClass results = cl.deal_with(1) # Calls method correctly. try = cl.__hidden(2) # Unknown method here, errors out
Large Python Projects
Many Open Source projects are now under Source Forge, including several Python projects. The base project that provides an environment for making useful tools is PyQt. One good example of what can be developed is PythonCAD. Some efforts have also been made to integrate Python with Microsoft COM and HTML based web pages. These integrations include with Microsoft Visual Studios and ActiveState.
Footnotes and Additional Websites with Python Inform
[1] University of Texas-Arlington course CSE1309X : Introduction to Programming Using Python as taught by Farhad Kamangar, Professor in Computer Science and Engineering Department.IDE
[2] Python Software Foundation Home Page.
[3] GURU99 – Python Operators Tutorial Home Page.