Steps in software developement
A floating-point literal
A floating-point literal is written with the fractional part even if that fraction is 0, as in 1.0, 0.0, or 99.0.
A nested loop
A nested loop is a loop that appears as part of the body of another loop. The nested loops are commonly referred to as the outer loop and inner loop.
Exit conditions
Exit conditions: The Boolean expression that is evaluated to determine when the loop will exit or stop
The range function
The set of all possible output values of a function
Dictionaries
A dictionary is another type of container object that is different from sequences like strings, tuples, and lists. Dictionaries contain references to objects as key-value pairs - each key in the dictionary is associated with a value, much like each word in an English language dictionary is associated with a definition. Unlike sequences, the elements of a dictionary do not have a relative ordering of positions. The dict type implements a dictionary in Python.
What is a graphical method to show program flow and execution?
Flowchart
Loop iterations
Loop iterations: What happens each time the loop body is executed; called a pass through the loop
Python interpreter
The Python interpreter is a computer program that executes code written in the Python programming language. An interactive interpreter is a program that allows the user to execute one line of code at a time.
The for loop
The for loop is the other repetition structure available in Python. Although the while loop is ideal for an indefinite loop, the for loop is an ideal loop for definite loop where we know the exact number of times of the loop execution.
Code in Python
This code in Python looks like the following. We will discuss how to write the code in later modules, so don't worry if you don't understand it at first.
A function that uses a local variable:
def calculate_taxes(amount, rate): tax = amount * rate return tax #tax is a local variable def main(): tax = calculate_taxes(100, .05) print("Tax is ", tax)#tax is a local variable #The following code checks whether the current module is the main module if __name__ == "__main__": main();
miscellaneous
(adj.) mixed, of different kinds Good practice is to use list methods to add and delete list elements, rather than alternative add/delete approaches. Alternative approaches include syntax such as my_list[len(my_list):] = [val] to add to a list, or del my_list[0] to remove from a list. Generally, using a list method yields more readable code. The list.sort() and list.reverse() methods rearrange a list element's ordering, performing in-place modification of the list. The list.index() and list.count() return information about the list and do not modify the list.
Interacting with file systems
A program commonly needs to interact with the computer's file system, such as to get the size of a file or to open a file in a different directory. The computer's operating system, such as Windows or Mac OS X, controls the file system, and a program must use functions supplied by the operating system to interact with files. The Python standard library's os module provides an interface to operating system function calls and is thus a critical piece of a Python programmer's toolbox. A programmer should consider the portability of a program across different operating systems to avoid scenarios where the program behaves correctly on the programmer's computer but crashes on another. Portability must be considered when reading and writing files outside the executing program's directory since file path representations often differ between operating systems. For example, on Windows the path to a file is represented as "subdir\\bat_mobile.jpg", but on a Mac is "subdir/bat_mobile.jpg". The character between directories, e.g., "\\"or "/", is called the path separator, and using the incorrect path separator may result in that file not being found.1 A common error is to reduce a program's portability by hardcoding file paths as string literals with operating system specific path separators. To help reduce such errors, good practice is to use the os.path module, which contains many portable functions for handling file paths. One of the most useful functions is os.path.join(), which concatenates the arguments using the correct path separator for the current operating system. Instead of writing the literal path = "subdir\\bat_mobile.jpg", a programmer should write path = os.path.join('subdir', 'bat_mobile.jpg'), which will result in "subdir\\bat_mobile.jpg" on Windows and "subdir/bat_mobile.jpg" on Linux/Mac.
summery
In this lesson, you learned that in Python errors are called exceptions and there are many types. Some of these include ZeroDivisionError, IndexError, NameError, TypeError, and so forth. To handle exceptions, try/except code is used. Multiple exceptions can be handled as well. The following code shows the format of a try block. Try: code that may raise an exception Except ExceptionType_1: code block to handle exception of type ExceptionType_1 Except ExceptionType_2: code block to handle exception of type ExceptionType_2 Except: code block to handle unexpected exceptions of any type Finally: code that will always execute whether an exception was raised or not
Introduction to plotting and visualizing data
Many programs interact with sets of data, such as a list of ocean temperatures or daily calorie expenditure. A program can graphically plot, or visualize, such data. The matplotlib package can be used for plotting in Python. matplotlib replicates the plotting capability of MATLAB, an engineering-oriented programming language. matplotlib is short for "MATLAB plotting library."
Debugging Tools
Most IDEs have debugging tools. Below are images of Spyder, Visual Studio Code, and IDLE debugging tools and windows.
Standard library
Python includes by default a collection of modules that can be imported into new programs. The Python standard library includes various utilities and tools for performing common program behaviors. Ex: The math module provides progress mathematical functions, the datetime module provides date and calendar capabilities, the random module can produce random numbers, the sqlite3 module can be used to connect to SQL databases, and so on. Before starting any new project, good practice is to research what is available in the standard library, or on the internet, to help complete the task. Methods to find many more useful modules made available on the internet by other programmers are discussed in another section.
Breakpoints
These can be added to the code by the programmer which will halt the program's execution when it readhes that point. They allow the programmer test the code at those points Example Debugger Breakpoints are places of interest in your code. Your program will run until it hits a line that you have marked as a breakpoint. It will pause there so that you can take a look at what's going on. The following code has a breakpoint set. By clicking Debug -> Set breakpoint, you can add a breakpoint to your code.
Variable Explorer
When running the code (Debug - >Debug), the variable explorer lists the values of each of the variables as you step through the code. The console shows the individual steps in the process. Using the debug menu, you can step through the code one step at a time. You can also stop the code at any time with the debug - stop menu. for a in range(1,11):for b in range(1,11): result = a*b if result %2==0: typ ="Even"else: typ ="Odd"print("The results of {0} times {1} is {2}, a {3} number".format(a,b,result,typ))
Multiple Exceptions
import sys filename = input("Enter filename: ") movies =[]try:with open(filename)as file:for line in file: line = line.replace("\n","") >>>movies.append(line)exceptFileNotFoundError:print("Could not find the file named "+ filename) sys.exit()exceptOSError:print("File found - error reading file") sys.exit()exceptException:print("An unexpected error occurred") sys.exit() The console when a FileNotFoundError occursCould not find the file named films.txt The console when an OSError occursFile found—error reading file The console when any other exception occursAn unexpected error occurred.
Accessing list elements
An index is a zero-based integer matching to a specific position in the list's sequence of elements. A programmer can reference a specific element in a list by providing an index. Ex: my_list[4] uses an integer to access the element at index 4 (the 5th element) of my_list. An index can also be an expression, as long as that expression evaluates into an integer. Replacing the index with an integer variable, such as in my_list[i], allows the programmer to quickly and easily lookup the (i+1)th element in a list.
Incremental programming
As programs increase in complexity, a programmer's development process becomes more important. A programmer should not write the entire program and then run the program—hoping the program works. If, as is often the case, the program does not work on the first try, debugging at that point can be extra difficult because the program may have many distinct bugs. Experienced programmers practice incremental programming, starting with a simple version of the program, and then growing the program little-by-little into a complete version. Example: Phone number program
Modifying a list and common list operations
Unlike the string sequence type, a list is mutable and is thus able to grow and shrink without the program having to replace the entire list with an updated copy. Such growing and shrinking capability is called in-place modification. The highlighted lines in the list below indicate ways to perform an in-place modification of the list:
Local and Global Variables
When creating a program, the issue of scope comes up referring to the visibility of variables in a program. Global variables are variables that are defined outside of all of the functions and can be accessed by any of the functions. Local variables, however, are defined within functions and can only be used in the functions that have defined them. Generally, it is good programming practice to avoid using global variables. Passing variables and returning variables to and from functions is a preferred method. For example, look at the following two functions.
Divide and Conquer Approach
You typically solve a large problem by breaking it down into more manageable pieces. This is called a divide and conquer approach to problem solving, and it is the approach used by every program designer today. The chart below is an example of a hierarchy chart. The hierarchy chart illustrates that the Main() function controls the execution of the program by its ability to call the loan(), menu(), and pValue() functions. Advantages of Creating Functions It reduces the complexity of the analysis, design, and coding. Different people can work on different functions. Functions can be reused. It's easier to see the big picture. It's easier to desk-check the algorithms. It's easier to find errors in the algorithms.
A function that uses a global variable:
tax=0.0 #global variable def calculate_taxes(amount, rate): global tax #access global variable named tax tax = amount * rate #tax is a global variable do not need to return def main(): calculate_taxes(100, .05) print("Tax is ", tax)#tax is a global variable #The following code checks whether the current module is the main module if __name__ == "__main__": main();
Using Try/Catch Blocks
try: number = int(input("Enter an integer: ")) print("You entered a valid integer of " + str(number) + ".") except ValueError: print("You entered an invalid integer. Please try again.") print("Thanks!")
A floating-point number
A floating-point number is a real number, like 98.6, 0.0001, or -666.667. The term "floating-point" refers to the decimal point being able to appear anywhere ("float") in the number. Thus, float is a data type for floating-point numbers.
A break loop
A break statement in a loop causes the loop to exit immediately. A break statement can sometimes yield a loop that is easier to understand.
Changing list size
A common error is to add or remove a list element while iterating over that list. Such list modification can lead to unexpected behavior if the programmer is not careful. Ex: Consider the following program that reads in two sets of numbers and attempts to find numbers in the first set that are not in the second set.
A common error
A common error is to forget the comma between items, as in print('Name' user_name).
Avoid writing redundant code
A function can be defined once, then called from multiple places in a program, thus avoiding redundant code. Examples of such functions are math module functions like sqrt() that relieve a programmer from having to write several lines of code each time a square root needs to be computed. The skill of decomposing a program's behavior into a good set of functions is a fundamental part of programming that helps characterize a good programmer. Each function should have easily-recognizable behavior, and the behavior of the main program (and any function that calls other functions) should be easily understandable via the sequence of function calls. A general guideline (especially for beginner programmers) is that a function's definition usually shouldn't have more than about 30 lines of code, although this guideline is not a strict rule.
Hierarchical function calls
A function's statements may include function calls, known as hierarchical function calls or nested function calls. Code such as user_input = int(input()) consists of such a hierarchical function call, wherein the input() function is called and evaluates to a value that is then passed as an argument to the int() function.
line
A line is a row of text.
Common list methods
A list method can perform a useful operation on a list such as adding or removing elements, sorting, reversing, etc. The table below shows the available list methods. Many of the methods perform in-place modification of the list contents — a programmer should be aware that a method that modifies the list in-place changes the underlying list object, and thus may affect the value of a variable that references the object.
string concatenation.
A program can add new characters to the end of a string in a process known as string concatenation. The expression "New" + "York" concatenates the strings New and York to create a new string NewYork. Most sequence types support concatenation. String concatenation does not contradict the immutability of strings, because the result of concatenation is a new string; the original strings are not altered.
List slicing
A programmer can use slice notation to read multiple elements from a list, creating a new list that contains only the desired elements. The programmer indicates the start and end positions of a range of elements to retrieve, as in my_list[0:2]. The 0 is the position of the first element to read, and the 2 indicates last element. Every element between 0 and 2 from my_list will be in the new list. The end position, 2 in this case, is not included in the resulting list. A table of common list slicing operations are given below. Note that omission of the start or end positions, such as my_list[:2] or my_list[4:], has the same meaning as in string slicing. my_list[:2] includes every element up to position 2. my_list[4:] includes every element following position 4 (including the element at position 4). The interpreter handles incorrect or invalid start and end positions in slice notation gracefully. An end position that exceeds the length of the list is treated as the end of the list. If the end position is less than the start position, an empty list is produced.
List iteration
A programmer commonly wants to access each element of a list. Thus, learning how to iterate through a list using a loop is critical. Looping through a sequence such as a list is so common that Python supports a construct called a for loop, specifically for iteration purposes. The format of a for loop is shown below. Each iteration of the loop creates a new variable by binding the next element of the list to the name my_var. The loop body statements execute during each iteration and can use the current value of my_var as necessary. 1 Programs commonly iterate through lists to determine some quantity about the list's items. Ex: The following program determines the value of the maximum even number in a list: If the user enters the numbers 7, -9, 55, 44, 20, -400, 0, 2, then the program will output Max even #: 44. The code uses three for loops. The first loop converts the strings obtained from the split() function into integers. The second loop prints each of the entered numbers. Note that the first and second loops could easily be combined into a single loop, but the example uses two loops for clarity. The third loop evaluates each of the list elements to find the maximum even number. Before entering the first loop, the program creates the list nums as an empty list with the statement nums = []. The program then appends items to the list inside the first loop. Omitting the initial empty list creation would cause an error when the nums.append() function is called, because nums would not actually exist yet. The main idea of the code is to use a variable max_num to maintain the largest value seen so far as the program iterates through the list. During each iteration, if the list's current element value is even and larger than max_num so far, then the program assigns max_num with current value. Using a variable to track a value while iterating over a list is very common behavior.
The first bug
A sidenote: The term "bug" to describe a runtime error was popularized in 1947. That year, engineers working with pioneering computer scientist Grace Hopper discovered their program on a Harvard University Mark II computer was not working because a moth was stuck in one of the relays (a type of mechanical switch). They taped the bug into their engineering log book, which is still preserved today
Flowcharting
A third design tool is flowcharting. A flowchart consists of standard geometric symbols that graphically indicate the actions to be executed and the exact order in which those actions should be executed. Once you have completed your design, you can translate the design into actual programming code.
Sequence Control Structure Example
A typical sequence might be to get the input, process the data, and display the output. Here is another way to think of a sequence control structure. The flowlines within the flowchart will only flow downward and there is no branching or repeating of instructions.
while loop
A while loop is a construct that repeatedly executes an indented block of code (known as the loop body) as long as the loop's expression is True. At the end of the loop body, execution goes back to the while loop statement and the loop expression is evaluated again. If the loop expression is True, the loop body is executed again. But, if the expression evaluates to False, then execution instead proceeds to below the loop body. Each execution of the loop body is called an iteration, and looping is also called iterating.
If statements
An if statement executes a group of statements if an expression is true. The statements in a branch must be indented some number of spaces, typically four spaces.
If-else statement
An if-else statement executes one group of statements when an expression is true and another group of statements when the expression is false.
Syntax errors
As soon as a person begins trying to program, that person will make mistakes. One kind of mistake, known as a syntax error, is to violate a programming language's rules on how symbols can be combined to create a program. An example is putting multiple prints on the same line. The interpreter will generate a message when encountering a syntax error. The error message will report the number of the offending line, in this case 7, allowing the programmer to go back and fix the problem. Sometimes error messages can be confusing, or not particularly helpful. Below, the message "invalid syntax" is not very precise, but is the best information that the interpreter is able to report. With enough practice a programmer becomes familiar with common errors and is able to avoid them, avoiding headaches later. Note that syntax errors are found before the program is ever run by the interpreter. In the example below, none of the prints prior to the error is in the output.
Basic text output
Basic text output Printing of output to a screen is a common programming task. This section describes basic output; later sections have more details. The primary way to print output is to use the built-in function print(). Printing text is performed via: print('hello world'). Text enclosed in quotes is known as a string literal. Text in string literals may have letters, numbers, spaces, or symbols like @ or #. Each print statement will output on a new line. A new output line starts after each print statement, called a newline. A print statement's default behavior is to automatically end with a newline. However, using print('Hello', end=' '), specifying end=' ', keeps the next print's output on the same line separated by a single space. Any space, tab, or newline is called whitespace. A string literal can be surrounded by matching single or double quotes: 'Python rocks!' or "Python rocks!". Good practice is to use single quotes for shorter strings and double quotes for more complicated text or text that contains single quotes (such as print("Don't eat that!")).
Basics
Basics An expression is a combination of items, like variables, literals, operators, and parentheses, that evaluates to a value, like 2 * (x + 1). A common place where expressions are used is on the right side of an assignment statement, as in y = 2 * (x + 1). A literal is a specific value in code like 2. An operator is a symbol that performs a built-in calculation, like +, which performs addition. Common programming operators are shown below.
Booleans and Boolean operators
Booleans and Boolean operators A Boolean refers to a value that is either True or False. Note that True and False are keywords in Python and must be capitalized. A programmer can assign a Boolean value by specifying True or False, or by evaluating an expression that yields a Boolean.
Code
Code is a common word for the textual representation of a program (and hence programming is also called coding).
Condition-Controlled Repetition:
Condition-Controlled Repetition: Condition-controlled repetition structures are very similar to counter-controlled structures; however, you do not know the number of times your user will go through your loop. For example, will you always know how many items a customer will buy? Will you always know how many transactions a user at an ATM will perform? In these situations, an event will be used to control the entry and exit conditions of your loop.
Continue statements
Continue statements A continue statement in a loop causes an immediate jump to the while or for loop header statement. A continue statement can improve the readability of a loop. The example below extends the previous meal finder program to find meal options for which the total number of items purchased is evenly divisible by the number of diners. In addition, the following program will output all possible meal options, instead of reporting the first meal option found. The program uses two nested for loops to try all possible combinations of tacos and empanadas. If the total number of tacos and empanadas is not exactly divisible by the number of diners (e.g., num_tacos + num_empanadas) % num_diners != 0, the continue statement will immediately proceed to the next iteration of the for loop.
Counter-Controlled Loops
Counter-Controlled Loops: This type of repetition, counter-controlled repetition, is used when the number of repetitions is known in advance. For example, you may have 200 employees to process payroll or a specific number of computers to inventory. In this loop, a counter is set to hold the initial value of a range.
Counting with a while loop
Counting with a while loop Commonly, a loop should iterate a specific number of times, such as 10 times. The programmer can use a variable to count the number of iterations, called a loop variable. To iterate N times using an integer loop variable i, a loop1 with the following form is used:
Relational Operators and String Comparison
Decisions in our design algorithms are most often made based on a comparison of two or more values, and the relational operators are used to implement these comparisons. Expressions that involve relational operators are called Boolean or conditional expressions, and a key point to remember is that conditional expressions have only two possible outcomes, which are true or false. But before we cover how to create conditional expressions, we will define the relational operators that are used for our comparisons because they are the basic building blocks used to create conditions. Examples:age == 5quantity != 0distance>=5.6 String Comparison Although it makes sense to compare numbers, you can also compare strings. Just keep in mind that string comparisons look at alphabetical order. For example, "If three < five" is false, because three is considered greater than five. You can use any of the operators with string literals and string variables, just as you do with numbers. fname == "Gina"
Step 6
Deploy the solution. When everything is completed, the final step is to put your solution live. You will deploy, or put, your solution into production. The customers will begin using your solution. How exciting is that? Your solution may now be used by thousands upon thousands of customers, maybe from even around the world.
Step 2
Plan and design the logic. Once you understand the problem, you will use the information gathered to plan the logic to your solution. During this planning, the design of your solution will take shape. Sometimes, during the planning process, you determine that you need more information. It is okay to go back to the first step in the process to gather more information in order to understand the problem. Usually, the planning involves a three-step process: identify the input, identify the processes, and identify the outputs. The input is what the program will receive while it executes or runs. The processes are the calculations. The outputs are the results sent to the customer or user of the progra
Step4
Desk-check the design. During this step, you will complete a desk-check of your logic. You will develop some sample test data to test your logic and ensure that the solution will work. You will look for logic mistakes (errors). Remember, your solution needs to produce the correct results. If your solution gives you the wrong answer, then your solution is not valid. Think of it this way. You deposited $50 into your checking account using your ATM. Your previous balance was $100. You expect your new checking account balance to be $150. Your deposit receipt says that your checking account balance is $50, not $150. You are not happy. The solution was incorrect. The program deducted the deposit amount instead of adding it to your balance. By completing a test with sample test data, you will be able to resolve many mistakes (errors) well before the customer or user sees it live. Complete a walk-through of the logic.
Step3
Develop the logical solution. After you understand the problem and plan and design the logic, you are ready to develop the logical solution to the original problem. The logical solution is determined by using design tools, such as pseudocode and flowcharts, to develop documentation to be passed to the programmers for coding. Pseudocode designs are English-like statements that can easily be translated to actual programming code. Flowcharts are a visual representation of the flow or process of the solution. During the design, you will determine the data variables necessary to store the data and the step-by-step algorithm for the solution
step3
Develop the logical solution. After you understand the problem and plan and design the logic, you are ready to develop the logical solution to the original problem. The logical solution is determined by using design tools, such as pseudocode and flowcharts, to develop documentation to be passed to the programmers for coding. Pseudocode designs are English-like statements that can easily be translated to actual programming code. Flowcharts are a visual representation of the flow or process of the solution. During the design, you will determine the data variables necessary to store the data and the step-by-step algorithm for the solution
Step 7
Documentation: The two types of documentation, internal and external, are useful when changes or troubleshooting are necessary. Examples of internal documentation would be comments after lines of code that explain what it does. External documentation can consist of hierarchy charts and desk-checking tools in order to validate the program's requirements and make adjustments if necessary.
infinite loop
Each iteration of the program below prints one line with the year and the number of ancestors in that year. (Note: the program's output numbers are large due to not considering breeding among distant relatives, but nevertheless, a person has many ancestors.) The program checks for year_considered >= user_year rather than for year_considered != user_year, because year_considered might be reduced past user_year without equaling it, causing an infinite loop. An infinite loop is a loop that will always execute because the loop's expression is always True. A common error is to accidentally create an infinite loop by assuming equality will be reached. Good practice is to include greater than or less than along with equality in a loop expression to help avoid infinite loops. A program with an infinite loop may print output excessively, or just seem to stall (if the loop contains no printing). A user can halt a program by pressing Control-C in the command prompt running the Python program. Alternatively, some IDEs have a "Stop" button.
Equality operators
Equality operators An equality operator checks whether two operands' values are the same (==) or different (!=). Note that equality is ==, not just =. An expression involving an equality operator evaluates to a Boolean value. A Boolean is a type that has just two values: True or False.
Common Syntax Errors and Handling Messages
Errors often result in Python error handling messages. Errors are often the result of incorrect user input. For example, look at the following code. milesDriven=float(input("Enter miles driven: ")) gallonsUsed=float(input("Enter gallons used: ")) mpg = milesDriven/gallonsUsed print("Miles Per Gallon: ", mpg) Error when 0 entered for gallonsUsed: File "C:/Users/D99003734/Documents/pythonCode/newprogram.py", line 10, in <module> mpg = milesDriven/gallonsUsed ZeroDivisionError: float division by zero Error when letter entered for milesDriven: File "C:/Users/D99003734/Documents/pythonCode/newprogram.py", line 9, in <module> gallonsUsed=float(input("Enter gallons used: ")) ValueError: could not convert string to float: 'a'
Example IPO Problem
Example Problem Write a program that will input a cashier's payroll information (name, hours worked, and pay rate). The program will calculate the salary and output the name, hours worked, and salary. We want to create the IPO, pseudocode, and flowchart as design tools. Start with the IPO.
Format specifications
Format specifications A format specification inside of a replacement field allows a value's formatting in the string to be customized. Ex: Using a format specification, a variable with the integer value 4 can be output as a floating-point number (4.0) or with leading zeros (004). A common format specification is to provide a presentation type for the value, such as integer (4), floating point (4.0), fixed precision decimal (4.000), percentage (4%), binary (100), etc. A presentation type can be set in a replacement field by inserting a colon : and providing one of the presentation type characters described below.
Function basics
Function basics:A function is a named series of statements. A function definition consists of the new function's name and a block of statements. Ex: def print_pizza_area():. An indented block of statements follows the definition. A function call is an invocation of the function's name, causing the function's statements to execute.
Modular program development
Programmers commonly use functions to write programs modularly. Modular development is the process of dividing a program into separate modules that can be developed and tested separately and then integrated into a single program. A programmer can use function stubs (described in depth elsewhere) to capture the high-level behavior of the required functions (or modules) before diving into details of each function, like planning a route for a road trip before starting to drive.
Pseudocode
Pseudocode is considered fake or false code. It is an English-like design template that can be easily translated to actual programming language. This design tool is used to develop the step-by-step instructions that will eventually be performed by a computer. Skipping over one step can cause your entire program to have errors. Therefore, each step needs to be in its simplest form.
Python def Keyword
In Python, we use the def keyword to define the function. A set of parentheses can contain zero or more parameters (also called arguments), depending on the function. After the parenthesis, there will be a colon followed by the code block. These statements must be indented as part of the function. In the print_welcome function, the name of the function starts with a verb. This is good practice when naming functions. In the body of the function, a return statement can return a value to the calling function. It is also good practice when using functions to define a main function. Put all of the code that is not in a function in a def main(). When you have defined a main function, you must call the main function to start the program. This is done by using the internal name variable and checking to see if the current module is the main module. Below is an example. #this function will display a message. The message is passed to the function as an argument def print_welcome(message): print(message) print() def main(): message="Welcome to our program!" print_welcome(message) #The following code checks whether the current module is the main module if __name__ =="__main__": main();
Logical Operators
In cases where a simple condition is not sufficient (e.g., when the value of a variable should be less than some number but greater than another number), conditional expressions can be combined to create compound Boolean expressions. Logical operators are used to combine simple Boolean expressions that are created with the relational operators. There are three logical operators that are commonly used: (1) AND, (2) OR, and (3) NOT. When we combine two or more simple Boolean expressions together using the logical operators, we are creating compound Boolean, or compound conditional, expressions.
Built-in functions that iterate over lists
Iterating through a list to find or calculate certain values like the minimum/maximum or sum is so common that Python provides built-in functions as shortcuts. Instead of writing a for loop and tracking a maximum value, or adding a sum, a programmer can use a statement such as max(my_list) or sum(my_list) to quickly obtain the desired value.
Loop body
Loop body: Contains the statements inside the loop from the conditional statement to the end loop delimiter
Loop control variables
Loop control variables: The variables that are used to create an expression controlling the entry and exit condition and must be modified each time through the loop
Newline characters
Newline characters Output can be moved to the next line by printing \n, known as a newline character. Ex: print ('1\n2\n3') prints "1" on the first line, "2" on the second line, and "3" on the third line of output. \n consists of two characters, \ and n, but together are considered by the Python interpreter as a single character.
Simple Selection Statements
Now that we have covered how to create Boolean (or conditional) expressions using the relational and logical operators, we can begin the investigation of how to make decisions in our program designs in order to select alternative processing paths based on the outcome of the Boolean expression. Let's look at the following flowchart to see how to use Boolean expressions to select different processing paths in our designs. Notice that we make our choices just as we would in real life. If a condition is true, then we will perform one set of actions. The following shows the pseudocode and flowchart form of the simple selection statements.
Variables
Now that you have seen the design tools, you need to understand how data (information) can be used by the computer. Variables are named with locations in the computer's memory that hold the data (information) required by a program. This data may be changed by the programming when it runs (such as calculations), or the data may not change (such as constants). Each variable needs to have a name so that the programs and programmers can easily access the data from the computer. Variable names should be unique and descriptive. X can be a variable name, but what does it really mean? Age is a better variable name, and cashierAge is even better. You may not be the only person using your design, so the more meaningful the variable name, the better. For every input, process, or output, you need to develop or create variable names. Variable names follow certain rules (known as naming conventions). Each programming language may have some rules to follow. If you follow these basic rules, however, they should be interchangeable in most languages. Use no spaces; the variable name must be one word. Use no special characters (avoid @, #, $, ^, &, *, etc.). Underscores are usually allowed. The first character cannot be a number. Name the variable something that indicates what may be stored in it. A popular naming convention is camelCase.
Functions and Returning Values
Once you determine the general structure of the large problem, you can determine what step-by-step instructions are required to solve each of the modules and then integrate the modules to solve the general problem. Complex programs are easier to analyze, design, code, and debug when they are refined into smaller, independent problems or functions for the following reasons. A function is a relatively small, independent block of instructions that performs a single task. Moreover, all of your designs should have a hierarchical organization. The goal is to partition your program into logically independent functions in which each function performs a specific task. Each function performs one specific task (input, calculate tax, calculate pay, enter new data, etc.). This can be a very natural concept that you see and use every day. The main program can also be created within a function. The main function performs many tasks and can include a call to another function. When a call is reached, the main will transfer control to the called function. The function will execute until it reaches the end of the code (or reaches another call statement). Once it reaches the end of the function, it will transfer control back to the main, and execution in the main will continue with the statement immediately following the call statement. One of the key characteristics of our functions is that they should be functionally independent. That is, a function should have a single-minded function (they do only one thing); and no excessive interaction with other modules.
Input-Process-Output (IPO) Model
Once you understand the problem, you will need to analyze the problem with an input-process-output (IPO) model.
Sorting lists
One of the most useful list methods is sort(), which performs an in-place rearranging of the list elements, sorting the elements from lowest to highest. The normal relational equality rules are followed: numbers compare their values, strings compare ASCII/Unicode encoded values, lists compare element-by-element, etc. The following animation illustrates.
While Loop
Python's while statement is one of the most general repetition structures offered in the language. The Python while statement repeats a block (the while loop body) as long as the loop condition remains true. When the loop condition becomes false, the program execution passes to the statement that follows the while body. A typical while statement consists of a header line with a Boolean expression as the loop condition, the body of the loop consisting of one or more indented statements, and an optional else part that is executed if loop execution exits the loop without a break statement being encountered. #this is a counter controlled loop count = 1 # Initialize counter while count <=10:# Should we continue? print(count)# Display counter, then count +=1# Increment counter by one at a time
Referencing format()
Referencing format() values correctly The colon : in the replacement field separates the "what" on the left from the "how" on the right. The left "what" side references a value in the format() parentheses. The left side may be omitted (inferred positional replacement), a number (positional replacement), or a name (named replacement). The right "how" side determines how to show the value, such as a presentation type. More advanced format specifications, like fill and alignment, are provided in a later section.
Relational operators
Relational operators A relational operator checks how one operand's value relates to another, like being greater than. Some operators, like >=, involve two characters. A programmer cannot arbitrarily combine the >, =, and < symbols; only the shown two-character sequences represent valid operators.
Removing Elements .empty() .remove()
Removing Elements Adding elements to our HTML documents is great, but without the ability to remove them, our pages can quickly become cluttered. Thankfully, we have two jQuery functions, .empty() and .remove(), that help us delete content from our pages. .empty() deletes an element's content and all its descendants. For instance, if you .empty() an 'ol', you'll also remove all its 'li's and their text. .remove(), not only deletes an element's content, but deletes the element itself.
Scientific notation
Scientific notation is useful for representing floating-point numbers that are much greater than or much less than 0, such as 6.02x1023. A floating-point literal using scientific notation is written using an e preceding the power-of-10 exponent, as in 6.02e23 to represent 6.02x1023. The e stands for exponent. Likewise, 0.001 is 1x10-3, so it can be written as 1.0e-3.
Logic errors
Some errors may be subtle enough to silently misbehave, instead of causing a runtime error and a crash. An example might be if a programmer accidentally typed "2 * 4" rather than "2 * 40" - the program would load correctly, but would not behave as intended. Such an error is known as a logic error, because the program is logically flawed. A logic error is often called a bug. The programmer clearly made an error, but the code is actually correct syntax - it just has a different meaning than was intended. So the interpreter will not generate an error message, but the program's output is not what the programmer expects - the new computed salary is much too high. These mistakes can be very hard to debug. Paying careful attention and running code after writing just a few lines can help avoid mistakes.
Loops modifying lists
Sometimes a program iterates over a list while modifying the elements. Sometimes a program modifies the list while iterating over the list, such as by changing some elements' values, or by moving elements' positions. Changing elements' values The below example of changing element's values combines the len() and range() functions to iterate over a list and increment each element of the list by 5.
why use python
The Python programming language was developed by Guido van Rossum in the 1990s. Python's features include the following. Simple syntax Accessible for beginning programmers Valuable skill set Software quality Program portability Developer productivity promotion Libraries support Component integration Free Powerful Easy to use Portable To write a program in Python you need an integrated development environment (IDE). This combines an editor, debugger, and programming aid in one package. Several IDEs exist for Python. Anaconda comes with Spyder and Visual Studio Code, IDLE, Pycharm, and other tools are also available. The process for creating and running a program is as follows. A programmer uses an IDE to enter source code into the editor windows. Python programs end with a .py extension. The source code gets compiled by the Python interpreter into bytecode. The bytecode is translated by the Python virtual machine into target code so the CPU can understand it directly.
modulo operator
The basic arithmetic operators include not just +, -, *, /, but also %. The modulo operator (%) evaluates the remainder of the division of two integer operands. Ex: 23 % 10 is 3. Examples: 24 % 10 is 4. Reason: 24 / 10 is 2 with remainder 4. 50 % 50 is 0. Reason: 50 / 50 is 1 with remainder 0. 1 % 2 is 1. Reason: 1 / 2 is 0 with remainder 1.
Common Syntax Errors
The following are common syntax errors. Misspelling keywords Forgetting the colon at the end of the opening line of a function definition, if clause, else clause, while statement, for statement, try clause, or except clause Forgetting an opening or closing quotation mark or parenthesis Using parentheses when you should be using brackets or vice versa Indenting improperly Misspelling or incorrectly capitalizing a variable or function name Using a keyword as a variable or function name Not checking that a value is the right data type before processing it (i.e., using a number when it needs to be converted to a string or vice versa)
The format() function
The format() function Program output commonly includes variables as a part of the text. The string format() function allows a programmer to create a string with placeholders that are replaced by values or variable values at execution. A placeholder surrounded by curly braces { } is called a replacement field. Values inside the format() parentheses are inserted into the replacement fields in the string. PARTICIPATION
List Basics
The list object type is one of the most important and often used types in a Python program. A list is a container, which is an object that groups related objects together. A list is also a sequence; thus, the contained objects maintain a left-to-right positional ordering. Elements of the list can be accessed via indexing operations that specify the position of the desired element in the list. Each element in a list can be a different type such as strings, integers, floats, or even other lists. A list can also be created using the built-in list() function. The list() function accepts a single iterable object argument, such as a string, list, or tuple, and returns a new list object. Ex: list('abc') creates a new list with the elements ['a', 'b', 'c'].
The range() function
The range() function While loops are commonly used for counting a specific number of iterations, and for loops are commonly used to iterate over all elements of a container. The range() function allows counting in for loops as well. range() generates a sequence of numbers, starting at zero and ending before a value given inside the parentheses. Ex: for i in range(3) sets i to 0 during the first iteration of the for loop, i to 1 during the second iteration, and finally i to 2 on the third iteration. The value within the parentheses is not included in the generated sequence. The range() function can take up to three arguments to indicate the starting value of the sequence, the ending value of the sequence minus 1, and the interval between numbers.
Repetition Control Structure Example
The repetition control structure allows the design algorithm to repeat blocks of code based on some condition. This is called a loop or repetition control structure. This repetition of the logic is done while a condition (or test) stays true. Once the condition (or test) becomes false, the repeating will stop. Often, the condition is a question such as, "Do you want to enter another transaction?" Think of an ATM. You are typically taken to the beginning set of tasks (deposit, withdraw, fast cash) if you answer yes (true) to the question of entering another transaction. You are in a loop until you answer no (false).
Selection Control Structure Example
The selection control structure allows the design algorithm to take different paths or alternatives to the sequential process. This is called a decision control structure, or an if-then-else structure. The selection or decision is based on a choice or a condition that can only be true or false. The choice is dependent on whether the condition is true when one path is taken or false when a different path is taken. The flowlines within the flowchart begin to branch to alternative processing paths for true and false alternatives.
Software Development Process
The software development process consists of the following steps. Understand the problem: In this first step, you will work with your client or customer to define and understand precisely what the problem is and why a solution is needed. You will ask many questions of your client or customer. You will then review the information you received with your client or customer. You need to ensure that you answer the what, where, why, and when questions as thoroughly as possible during this review. Plan and design the logic: Once you understand the problem, you will use the information gathered to plan the logic to your solution. During this planning, the design of your solution will take shape. The input is what the program will receive while it executes or runs. The processes are the calculations. The outputs are the results sent to the customer or user of the program. Develop the logical solution: The logical solution is determined by using design tools, such as pseudocode and flowcharts, to develop documentation to be passed to the programmers for coding. Desk-check the design: You will develop some sample test data to test your logic and ensure that the solution will work. You will look for logic mistakes (errors). Complete a walk-through of the logic. Translate the design into code: Translating the design into code means completing the program in the selected programming language (Python, C#, C++, Java, etc.), which is comprised of human readable instructions that represent the program design. However, in order to execute on a computer, the human readable programming language code must be either compiled or interpreted into machine language in order for the computer to understand the program, and this compilation is part of the programming process. With compiled languages, the entire program is translated into machine language that is understood by the computer before it runs. With interpreted languages, each line of instruction is translated into machine language just prior to executing or running. Deploy the solution: When everything is completed, the final step is to put your solution live and deploy it into production. Documentation: The two types of documentation, internal and external, are useful when changes or troubleshooting are necessary. Examples of internal documentation would be comments after lines of code that explain what it does. External documentation can consist of hierarchy charts and desk-checking tools in order to validate the program's requirements and make adjustments if necessary.
Error Handling and Debugging
There are several ways for programmers to track down logic errors in their code. It's often helpful, for example, to be able to look at the value of a variable and see how it changes after some operation. It might also be useful to see the value of a conditional expression. If you see that the value of a variable does not match your expectations, then this information can help you track down the problem. For example, did I forget to increment a value? Did I use the wrong formula in my assignment statement? Did I pass the right value to the module? Did I get the expected return value? By peeking into your program as it runs, you can track down errors in formulas, program flow, and more. You can, of course, simply add some print() statements throughout your code to display on the screen the values of variables or location of program execution. However, the debugger built into Python is a more elegant approach that doesn't require you to modify your code by adding temporary print statements that just have to be removed later as you complete your program.
Types of Errors
There are three types of errors. Syntax errors violate the rules for how Python statements must be written. These errors, also called compile-time errors, are caught by the IDE before you run the program. Runtime errors don't violate the syntax rules, but they throw exceptions that stop the execution of the program. Many of these exceptions are due to programming errors that need to be fixed. But some exceptions need to be handled by the program so the program won't crash. Logic errors are statements that don't cause syntax or runtime errors, but produce the wrong results. Desk-Checking is a technique used to resolve all types of errors up front and is a method of manually tracing through the logic of a program with some chosen test data; for example, logic walk-throughs, code walk-throughs, or design walk-throughs.
Step 5
Translate the design into code. Translating the design into code means completing the program in the selected programming language (C#, C++, python, etc.), which is comprised of human-readable instructions that represent the program design. However, in order to execute on a computer, the human readable programming language code must be either compiled or interpreted into machine language in order for the computer to understand the program, and this compilation is part of the programming process.
Type conversions
Type conversions A calculation sometimes must mix integer and floating-point numbers. For example, given that about 50.4% of human births are males, then 0.504 * num_births calculates the number of expected males in num_births births. If num_births is an integer type, then the expression combines a floating-point and integer. A type conversion is a conversion of one type to another, such as an int to a float. An implicit conversion is a type conversion automatically made by the interpreter, usually between numeric types. For example, the result of an arithmetic operation like + or * will be a float only if either operand of the operation is a float. 1 + 2 returns an integer type. 1 + 2.0 returns a float type. 1.0 + 2.0 returns a float type. int-to-float conversion is straightforward: 25 becomes 25.0. float-to-int conversion just drops the fraction: 4.9 becomes 4.
step1
Understand the problem. Work with your client or customer to define and understand precisely what the problem is and why a solution is needed. You will ask many questions of your client or customer. You will then review the information you received with your client or customer. You need to ensure that you answer the what, where, why, and when questions as thoroughly as possible during this review. The more information that you gather to understand the problem, the more requirements that you will obtain before moving on to the next step.