Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Project: MTA 98-381
Views: 51
Kernel: Python 3 (Ubuntu Linux)

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

type('lacey')
str
type(55)
int
type(5.5)
float
type(True)
bool

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.

age = 5 age = str(age) print("I am going to be " + age + " years old tomorrow.")
I am going to be 5 years old tomorrow.
age = "50" age = int(age) print(10, 20, 30, 40, age)
10 20 30 40 50
price = float(4.25) cost = int(price) print(5, cost, 3)
5 4 3

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.

lacey = [] lacey = ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) lacey[0:15:3]
sam = [] sam = ([28, 17, 4, 32, 65, 2]) sam[2:]
harry = "We all scream for ice cream!" harry[::-1]
jenna = [] jenna = (['JENNA', 'jenna', 'Jenna', 'JeNnA', 'JennA']) jenna[-2:0:-1]

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.

len("Run Forest, Run!")
16
aa = "I love to eat pizza with my friends." print(aa[4])
v
bb = "Honey, where is my super suit?" print(bb[-7])
r
cc = "What is your favorite type of food?" cc.count('o')
5

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 left

  • The += operator: assigns the value on the right plus the value of the previous variable to the variable on left

  • The /= operator: takes the previous value of the variable divided by the value on the right and assigns this to the variable on the left

x = 7 print(x)
7
x = 29 x += 7 print(x)
36
x = 16 x /= 4 print(x)
4.0

Comparison: There are six different kinds of comparison operators

  • The == operator: If the values of two operands are equal, then the condition becomes true

  • The != operator: If the values of two operands aren't equal, then the condition becomes true

  • The < operator: If the value of operand on the left is less than the operand on the right, then the condition becomes true

  • The > operator: If the value of operand on the left is greater than the operand on the right, then the condition becomes true

  • The <= operator: If the value of operand on the left is less than OR EQUAL TO the operand on the right, then the condition becomes true

  • The >= 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

x = 5 y = 8 if x < y: print(True)
True
x = 2 y = 9 if x > y: print(True) else: print(False)
False
x = 7 y = 7 if x >= y: print(True) else: print(False)
True
x = 0 y = 21 if x != y: print(True) else: print(False)
True

Logical: There are three different kinds of logical operators

  • The and operator: True if both of the operands are true

  • The or operator: True if one of the operands are true

  • The not operator: True if the operand is false

if 1>2 and 6<5: print("condition met") else: print("failure")
failure
if 4==4 or 5!=5: print("condition met") else: print("failure")
condition met
x = False if not x: print("condition met") else: print("failure")
condition met

Arithmetic: Used to perform mathmatical operations

  • The + operator: add two operands together

  • The - operator: subtract the right operand from the left

  • The * operator: multiplies two operands together

  • The / operator: divides the left operand by the right one

  • The % operator: (called modulus) gives the remainder of the left operand by the right

  • The // operator: (called floor division) division that results in the whole number answer taking away any decimal

  • The ** operator: (called exponent) left exponent raised to the power of the right

x = 6 % 4 y = x * 4 print(y)
8
x = 7 // 2 y = x ** 4 print(y)
81

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 otherwise

  • The is not operator: evaluates to false if the variables on either side of the operator point to the same object and true otherwise

x1 = 5 y1 = 5 print(x1 is not y1)
False
x2 = 'Hello' y2 = 'Hello' print(x2 is y2)
True
x3 = [3, 4, 5] y3 = [3, 4, 5] print(x3 is y3)
False

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't

  • The not in operator: evaluates to true if it doesn't find a variable in the specified sequence and false if it does

x = "hello world" print('h' in x)
True
x = "hello world" print('Hello' in x)
False
y = {1:'a',2:'b'} print(1 in y)
True
y = {1:'a',2:'b'} print('a' in y)
False

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:

n_string = input('Enter any interger:') n = int(n_string) if n > 5: print('n is greater than 5') elif n == 5: print('n is equal to 5') elif n < 5: print('n is less than 5')
Enter any interger:

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.

phone = input('What is the phone that Apple makes?') if phone == 'iPhone': print('Correct! Apple makes iPhones.') else: print('Sorry, Apple does not make ' + phone + 's.')

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.

x = 10 while x > 5: print("This is a test.") x -= 1

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.

words = ["sleepy", "shaken", "snaked", "shocked", "snoring"] for word in words: print("sister " + word)

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.

nums = [1, 2, 3, 7, 8, 17, 87] for n in nums: print(n ** 2)

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.

time = 0 while 4 < 5: print('this loop will never end') time += 1 if time > 5: break

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.

numbers = [1, 4, 24, 33, 59, 391] for n in nums: print("this is a number") if n % 2 == 0: print("this is an even number") else: continue

pass is a null operation -- when it is executed, nothing happens. It is useful as a placeholder.

number = input("Enter a Number: ") if number == "9": print("This number is nine.") else: pass print("What a nice number!")

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 """

count = 0 numbers = [4, 7, 2, 18, 0] for count in numbers: count += 2 # Always indent the body of for loops or else the code will result in an error print(count)
6 9 4 20 2
speed = 3 if speed < 5: print("You are not fast") #the body of the if and elif statements are indented elif speed == 5: print("You are average") elif 5 < speed <= 10: print("You are super fast")
You are not fast
def num_even_digits(n): # The information between the two pairs of """ is considered the docstring """ >>> num_even_digits(123456) 3 >>> num_even_digits(2468) 4 >>> num_even_digits(1357) 0 >>> num_even_digits(2) 1 >>> num_even_digits(20) 2 """ digits_nr = 0 while n > 0: i = n % 10 if i % 2 == 0: digits_nr += 1 n //= 10 print(n) import doctest doctest.testmod()

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

def function1(): # This is always what the notation looks like, except sometimes in the parenthesis there are parameters print("I am learning how to make functions in Python! YAY!") # The body of the def statement is always indented (indentation must be at the same level) function1()
I am learning how to make functions in Python! YAY!
def square(x): return x*x # Here we used the return function to return the value of the function which is 4*4 or 16 square(4)
16
def multiply(dollars_per_gallon, gallons, days): # These are the declaring arguments or parameters print((dollars_per_gallon * gallons) // days) multiply(2.5, 38, 24) # These are the passing arguments that are plugged into the definition and ultimately give you an output
3.0
def divide(x, y = 5): # default value of the argument is y = 5, so when calling the divide function you only have to type in the x parameter bc the y parameter is already given return x // y divide(90)
18
def divide(x, y = 1): return x // y divide(100, y = 4) # default value of the argument can be changed in the passing argument if specified like in this example
25

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.

whille 2 != 1: print("Yes or Yes")
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.

sum = 1 + 2 * 5 #We're expecting it to add to 15, but it doesn't if sum == 15: print("We got the expected response.") else: print("This isn't what we expected.")
This isn't what we expected.

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.

sum = (1 + 2) * 5 if sum == 15: print("We got the expected response.") else: print("This isn't what we expected.")
We got the expected response.

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.

print(Hello)
Hello

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.

print("Hello") #Here we're printing the string "Hello"
Hello
Hello = 288 #Here we're setting Hello as 288 and we're going to print a variable print(Hello)
288

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.

print(29/0)
--------------------------------------------------------------------------- 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:

  • ImportErrors occur when a module doesn't import properly

  • An IndexError would occur when a number that is not present in a list is called

  • A NameError could happen when a variable that hasn't been defined yet is called (like in example 4)

  • SyntaxError (discussed above)

  • TypeErrors happen when a item is acted with in a way that isn't suitable for the type

  • A 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.

num_s = input("Divide 11 by any number: ") num = int(num_s) try: awns = 11 // num print(anws) except ZeroDivisionError: print("You can't divide 11 by 0, try again!")
Divide 11 by any number: 0 You can't divide 11 by 0, try again!

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.

whille 2 != 1: print("Yes or Yes")
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.

sum = 1 + 2 * 5 #We're expecting it to add to 15, but it doesn't if sum == 15: print("We got the expected response.") else: print("This isn't what we expected.")
This isn't what we expected.

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.

sum = (1 + 2) * 5 if sum == 15: print("We got the expected response.") else: print("This isn't what we expected.")
We got the expected response.

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.

print(Hello)
Hello

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.

print("Hello") #Here we're printing the string "Hello"
Hello
Hello = 288 #Here we're setting Hello as 288 and we're going to print a variable print(Hello)
288

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.

print(29/0)
--------------------------------------------------------------------------- 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:

  • ImportErrors occur when a module doesn't import properly

  • An IndexError would occur when a number that is not present in a list is called

  • A NameError could happen when a variable that hasn't been defined yet is called (like in example 4)

  • SyntaxError (discussed above)

  • TypeErrors happen when a item is acted with in a way that isn't suitable for the type

  • A 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.

num_s = input("Divide 11 by any number: ") num = int(num_s) try: awns = 11 // num print(anws) except ZeroDivisionError: print("You can't divide 11 by 0, try again!")
Divide 11 by any number: 0 You can't divide 11 by 0, try again!

Notice that the way to use the except command, when you're only checking for a specific error is to put error *exception type*.