Perform Operations using Data Types and Operators
Evaluate an expression to identify the data type Python will assign to each variable
str()
: a sequence of characters enclosed in a pair of single, double, or triple quotes
int()
: a number without any decimal points
float()
: a number with decimals
bool()
: type that is either >> True or False
Perform data and data type operations
Convert from one data type to another data type
Changing from int to str
: The reason that the code in example one works is because the variable age was changed into a string in line two. On line three, the age has to be a string for the statement to be printed because you can't join a string and number.
Changing from str to int
: The reason that the code in example two works is because the variable age was changed into a integer in line two. On line three, the age has to be a integer for the statement to be printed because you can't join a string and numbers.
Changing from float to int
: The reason that the code in example three works is because the variable age was changed from a float into an integer in line two.
Indexing and Slicing Operations
Slice object
: Used to specify when to slice a sequence. There are three things that you can specify in a slice object-- starting point, ending point, and the step size.
Basic slicing syntax
: [i:j:k] >> i is the starting index, j is the stopping index, and k is the step size
Fetching section syntax: [i:] >> i is the starting index, and the rest of the values that follow the starting index will be printed as well
Reverse syntax
: [::-i] >> this will give the reverse of the characters in the sequence that you printed. See example 4 for clarification.
Negative slicing: If i is negative that means that you will count from the right of the sequence to the left. If the step size is negative that means you count down from the starting index instead of up.
Indexing
: Because each character in a Python string has an index number associated with it, we can manipulate strings to give us specific outputs
Isolating characters: If you want to isolate one character within a string, you have to put the index number in square brackets like in example two below. You can also use the negative index number to isolate a character; the index counts from -1, -2, -3... as you each character to the left.
len()
: total number of characters in a string
str.count()
: total number of times the character specified in the () appears
str.find()
: return position of a character based on index number. If there are multiple of the same character and you want to find one that is later in the string, you will have to specify what index number you want to start at.
Determine the Sequence of Execution Based on the Operator Precedence
Operator: Special characters that carry out arithmetic or logical computation
Assignment: To assign a variable a value you use specific symbols
The
=
operator: assigns the value on the right to the variable on the leftThe
+=
operator: assigns the value on the right plus the value of the previous variable to the variable on leftThe
/=
operator: takes the previous value of the variable divided by the value on the right and assigns this to the variable on the left
Comparison: There are six different kinds of comparison operators
The
==
operator: If the values of two operands are equal, then the condition becomes trueThe
!=
operator: If the values of two operands aren't equal, then the condition becomes trueThe
<
operator: If the value of operand on the left is less than the operand on the right, then the condition becomes trueThe
>
operator: If the value of operand on the left is greater than the operand on the right, then the condition becomes trueThe
<=
operator: If the value of operand on the left is less than OR EQUAL TO the operand on the right, then the condition becomes trueThe
>=
operator: If the value of operand on the left is greater than OR EQUAL TO the operand on the right, then the condition becomes true
Logical: There are three different kinds of logical operators
The
and
operator: True if both of the operands are trueThe
or
operator: True if one of the operands are trueThe
not
operator: True if the operand is false
Arithmetic: Used to perform mathmatical operations
The
+
operator: add two operands togetherThe
-
operator: subtract the right operand from the leftThe
*
operator: multiplies two operands togetherThe
/
operator: divides the left operand by the right oneThe
%
operator: (called modulus) gives the remainder of the left operand by the rightThe
//
operator: (called floor division) division that results in the whole number answer taking away any decimalThe
**
operator: (called exponent) left exponent raised to the power of the right
Identity: There are two different types of these operators. They are used to determine whether a variable is of a specific class or type.
The
is
operator: evaluates to true if the variables on either side of the operator point to the same object and false otherwiseThe
is not
operator: evaluates to false if the variables on either side of the operator point to the same object and true otherwise
Containment: Used to validate the membership of a value
The
in
operator: used to check if a value exists in a sequence or not; evaluates to true if it finds a variable in the specified sequence and false if it doesn'tThe
not in
operator: evaluates to true if it doesn't find a variable in the specified sequence and false if it does
Control Flow with Decisions and Loops
Construct and Analyze Code Segments That use Branching Statements
if
, elif
, else
, and compound conditional expressions
There are three major contitional expressions in python, if
, elif
, else
, they all will pass an argument, basically anything that takes an input decides if it is true or false and then spits out an output, is an argument. Here is an example in use:
As you can see in the previoue example the code is used to deteremine if a number is greater than, equal to, or less than 5. Using the if
and elif
conditional operators the code was instructed to take an input as a string and then it converted the input into an interger, using the line n = int(n_string)
. The integer was used as an input in this conditional expression.
Here is an example using strings and else
.
else
is really useful if you're done checking. In the previous example we asked people what type of phone Apple makes, the answer is "iPhones", so if anything else was entered it would be wrong.
Construct and analyze code segments that perform iteration
while
loops
A while
statement is like an if
statement, except that it it is run until the statement is false. They are the most basic type of loop. In this example we've take one from x
and if x
is less than 5 it stops printing.
This example shows how in the loop you can decrease what the loop is checking for to make the loop fail, or end the loop.
for
loops
While loops are for when you want to preform an action on every variable stored in a list. In this example we will add "sister" before every word in the list.
In this example we've taken a whole bunch of words and added "sister" to the front of each word.
A for
loop isn't just useful for adding words infront of other words. You can also pereform a function on everything on a list.
In this next example we will square each of the numbers on the list, then print the number. Although this use in specific isn't very useful it does a good job at showing the basic function of the for
loop.
break
, continue
, and pass
in loops
break
, continue
, and pass
are all things we can use in loops to make them more dynamic.
The break
statement can be used in both while and for loops. If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.
This loop was set to stop when 4
is greater than 5
, which will never happen. However we only allow it to run 5 times because the loop gets stopped by the break
function after being run 10 times. This break can stop a loop from running indefnitley which could potentially hurt this server or any other computer.
The continue
returns the control to the beginning of the loop. The continue
statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. The continue statement can be used in both while
and for loops
. In the following example we will print this is a number
for every number and it will continue
if the number is odd or print this is an even number
if the number is even.
pass
is a null operation -- when it is executed, nothing happens. It is useful as a placeholder.
We used pass
as a placeholder, basically just saying "do nothing". This way if the number was anything other than 9 it would just say What a nice number
instead of saying This number is nine.
before. In this case it is kind of redunant because it would still work just as well without the else:
and pass
lines.
Preform Input and Output Operation
Document and Structure Code
Document Code Segments Using Comments and Document Strings
Indentation
: white space at the beginning of a line used to delimit blocks of code; it won't run unless the coder indents properly
When do you indent:
Body of loops (for or while)
Body of conditional statement (if, elif, else)
Body of a function (def)
White space
: includes new lines, tabs, and spaces; these are used to denote blocks
Comments
: when making a comment on a line of code explaining what is happening you must use a #
Documentation string
: a string literal that occurs as the first statement in a module, function, class, or method definition; used for block commenting
Notation for a docstring: """ Insert comment here """
Construct and Analyze Code Segments that Include Function Definitions
Call signatures
: when you are calling a function, you have to use the function notation > function_name(parameter1, parameter2) > filling in the parameters to be either numbers or strings
Default values
: using an assignment operator, you can give an argument a value that always appears when the argument appears
Return
: this causes your function to exit and hand back a value to its caller
Def
: (followed by the function name and (parenthesis))this is how you create a function... you can call the function with specific parameters to have the code run
Pass
: used when a statement is required syntactically, but you don't want any command or code to execute; example of a null operation
Perform Troubleshooting and Error Handling
Analyze, detect, and fix code segments that have errors
Syntax errors
Syntax errors are the easiest errors to spot, it is when a character or string incorrectly placed in a command or instruction that causes a failure in execution. Here are some common syntax errors:
Misspelling a Python keyword
Making a typo
Not ending a statement with a colon
Syntax errors usually appear at compile time and are reported by the interpreter. The following is an example of a synatx error.
File "<ipython-input-1-cba350a2e1f2>", line 1
whille 2 != 1:
^
SyntaxError: invalid syntax
The problem stem from a typo: the while
command is spelled as whille
. It's easily fixed.
Logic Errors
Logical errors are the most difficult to fix. They occur when the program runs without crashing, but produces an incorrect result. The error is caused by a mistake in the program's logic. You won't get an error message. For example if you forget to use PEMDAS in your equations then it can turn out a little weirdly. Let's check out the following example where we want our input to output 15.
The problem with the code is that the logic precived by the computer is a little bit off with the way we want it to be in our heads. We're expecting 15, but we ended up with 11 because PEMDAS stated that multiplication and division go before addition and subtraction. You'll see in the next example we changed the logic slightly to reflect the 15 that we originally wanted the sum to be.
See, by adding the parentesis we could get the output we wanted.
Runtime Errors
Runtime errors are different from syntax and logic erros because it's happens when Python tried to understand what you say but runs into issues executing the command. Check out the following example.
A NameError
is being returned because python knows that it needs to print something it just doesn't know what to print. You can change the error by adding quotations around Hello
or setting Hello
as a variable and printing that. Let's see that in action.
Analyze and construct code segments that handle exceptions
Exceptions
Exeptions occur when something goes wrong, due to incorrect code or input. When an exception occurs, the program immediately stops, they're errors. For example (as you can see in the code below) whe you try to divide 29
by 0
python produces a ZeroDivisionError
exception.
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-5-2f0f7691dc45> in <module>()
----> 1 print(29/0)
ZeroDivisionError: division by zero
Here are some common exceptions:
ImportError
s occur when a module doesn't import properlyAn
IndexError
would occur when a number that is not present in a list is calledA
NameError
could happen when a variable that hasn't been defined yet is called (like in example 4)SyntaxError
(discussed above)TypeError
s happen when a item is acted with in a way that isn't suitable for the typeA
ZeroDivisionError
would occur when a number is divided by zero
try
and except
These are two command that can be used to handle expressions. If a Exception in the try
code happens it will just stop running the code and jump down to the except
block of the code.
Notice that the way to use the except
command, when you're only checking for a specific error is to put error *exception type*
.
Perform Troubleshooting and Error Handling
Analyze, detect, and fix code segments that have errors
Syntax errors
Syntax errors are the easiest errors to spot, it is when a character or string incorrectly placed in a command or instruction that causes a failure in execution. Here are some common syntax errors:
Misspelling a Python keyword
Making a typo
Not ending a statement with a colon
Syntax errors usually appear at compile time and are reported by the interpreter. The following is an example of a synatx error.
File "<ipython-input-1-cba350a2e1f2>", line 1
whille 2 != 1:
^
SyntaxError: invalid syntax
The problem stem from a typo: the while
command is spelled as whille
. It's easily fixed.
Logic Errors
Logical errors are the most difficult to fix. They occur when the program runs without crashing, but produces an incorrect result. The error is caused by a mistake in the program's logic. You won't get an error message. For example if you forget to use PEMDAS in your equations then it can turn out a little weirdly. Let's check out the following example where we want our input to output 15.
The problem with the code is that the logic precived by the computer is a little bit off with the way we want it to be in our heads. We're expecting 15, but we ended up with 11 because PEMDAS stated that multiplication and division go before addition and subtraction. You'll see in the next example we changed the logic slightly to reflect the 15 that we originally wanted the sum to be.
See, by adding the parentesis we could get the output we wanted.
Runtime Errors
Runtime errors are different from syntax and logic erros because it's happens when Python tried to understand what you say but runs into issues executing the command. Check out the following example.
A NameError
is being returned because python knows that it needs to print something it just doesn't know what to print. You can change the error by adding quotations around Hello
or setting Hello
as a variable and printing that. Let's see that in action.
Analyze and construct code segments that handle exceptions
Exceptions
Exeptions occur when something goes wrong, due to incorrect code or input. When an exception occurs, the program immediately stops, they're errors. For example (as you can see in the code below) whe you try to divide 29
by 0
python produces a ZeroDivisionError
exception.
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-5-2f0f7691dc45> in <module>()
----> 1 print(29/0)
ZeroDivisionError: division by zero
Here are some common exceptions:
ImportError
s occur when a module doesn't import properlyAn
IndexError
would occur when a number that is not present in a list is calledA
NameError
could happen when a variable that hasn't been defined yet is called (like in example 4)SyntaxError
(discussed above)TypeError
s happen when a item is acted with in a way that isn't suitable for the typeA
ZeroDivisionError
would occur when a number is divided by zero
try
and except
These are two command that can be used to handle expressions. If a Exception in the try
code happens it will just stop running the code and jump down to the except
block of the code.
Notice that the way to use the except
command, when you're only checking for a specific error is to put error *exception type*
.