Python Codes for Final

¡Supera tus tareas y exámenes ahora con Quizwiz!

Expressions

Missing "=' 5 + ham 2 + 2 2

% Operator

Modulus

!=

Not equal to

Variables vs. Strings

Strings - 'spam' Variables - spam

Print the numbers from 0 to 10 Specifications: You must use a for loop When the loop has completed display the string, "The loop has completed" Run the cell and show the output

for i in range(11): print(i) if i == 10: print("The loop has completed.")

Create a program that prints "Go Buffs, beat UCLA!" 3 times. Specifications: You must utilize a loop for this program. The first line printed should be: "Go Buffs, beat UCLA!" On a new line tabbed over one time, print a note that will output the loop iteration at all iterations. Use Python's f-strings formatting when printing out your loop iteration note. In your iteration note, the iteration number must be printed using the current iteration value based on the loop variable. (i.e., you cannot manually enter the iteration numbers and receive full credit)

for i in range(3): print("Go Buffs, beat UCLA!") print(f'\tNote: This is loop iteration, i ={i}')

Correct the control flow given in the next cell so that correct responses will be printed for printing grades based on percentage For example, as currently written if grade = 90 the code would currently print 'You got a D' which is certainly not what you want if you earn a 90 in a course. Note: don't change any of the values given for grades (e.g., 93,65,75,85) just the control flow this isn't meant to be the actual grades for the course just an example After you correct the control flow run the cell and show the output when grade = 90 grade = 90 if grade >93: print('You got an A') elif grade >65: print('You got a D') elif grade >75: print('You got a C') elif grade > 85: print('You got a B') else: print('You got an F')

grade = int(input('What is your ending grade?')) if grade <=65: print("You got an F") elif grade >65 and grade <75: print("You got a D") elif grade >= 75 and grade <85: print("You got a B") elif grade <93: print("You got an A")

>

greater than

>=

greater than or equal to

Print the numbers from 75 to 12 (inclusive) counting down from 3 Specifications: You must use a loop to answer this question Print the output horizontally

i = 78 while i > 12: i = i-3 print(i,end = ' ')

In the next cell, make a copy of the dwarfs list named, dwarfs2, and print its value.

import copy dwarfs2 = copy.copy(dwarfs) print(dwarfs2)

Check your working directory

ls

Show the number columns for each year of BLS data? Show the number of records for each year of BLS data? Use one cell per year below

rows08 = bls08.shape[0] columns08 = bls08.shape[1] tot08 = rows08 * columns08 print(f'There are {columns08} columns') print(f'There are {rows08} rows') print(f'There are {tot08} total records')

Show all rows for the 2nd to the 4th columns (birthday-Quiz1)

student.iloc[:,2:5]

Show all the information for students that scored an 80 or above on Quiz1 and Quiz2 whose first name starts with an 'A'.

student.loc[(student["firstName"].str.startswith('A') == True) & (student.Quiz2 >=80) & (student.Quiz1 >=80)]

Show all the information for students that scored an 80 or above on Quiz1 or Quiz2 whose first name starts with an 'A'

student.loc[(student["firstName"].str.startswith('A') == True) |(student.Quiz2 >=80) | (student.Quiz1 >=80)]

how the Quiz2 score of the student with the ID 1046

student.loc[1046, 'Quiz2']

Show all data for studentID's from 1071-1076

student.loc[1071:1076]

Show the Quiz1 and Quiz2 scores for student ID of: 1002, 1006, 1010, 1030

student.loc[[1002,1006,1010,1030], ['Quiz1', 'Quiz2']]

Show the number of records/rows in the dataset Just the number of rows, nothing else Assign a variable to this called, totRecords

totRecords = student.shape[0]

What does the expression, 23 // 7 , evaluate to?

3

Given the following Python code: spam = 40 spam + 1 What will be the value of spam when the code runs?

40

Given the following Python code: spam = 40 spam = spam + 1 What will be the value of spam when the code runs?

41

Values

5 'hello' -88.8

<

less than

<=

less than or equal to

What does Python return when the following function is executed? int('245')

245

What does the expression, 9 % 3, evaluate to?

9 % 3 = 0

We wish for Python to return the following: 'I have eaten 225 cans of spam' The following code will give us an error: 'I have eaten ' + 225 + 'cans of spam' Write the three correct values to return our desired string:

' I have eaten ' + str(225) + ' cans of spam. '

What does Python return when the following function is executed? str(245)

'245'

What does the following expression evaluate to: 'spam' * 3

'spamspamspam'

What does the following expression evaluate to: 'spam' + 'spamspam'

'spamspamspam'

What does Python return when the following function is executed? float('245')

245.0

Operators

* - / +

Create a function to calculate an employees total weekly pay Specifications: your program should: Create a function named, pay It should prompt the user to input how many regular hours and overtime hours they work An employees total weekly pay equals the hourly wage multiplied by the total number of regular hours plus any overtime payOvertime pay equals the total overtime hours multiplied by 1.5 times the hourly wageThe hourly wage is $12 a hour The function should return the total pay for the employee as a float data type

12*1.5 def pay(): regular = float(input('How many regular hours do you work?')) overtime = float(input('How much overtime do you work?')) wage = regular*12 + overtime*18 print(wage) pay()

How many possible values does the Boolean data type have?

2

Definition of an Expression

An expression in Python consists of values and operators and can always evaluate down to one value

Assignments

Anything with '=' eggs = 2 ham = 5 + 8

==

Equal to

10 == 9 and 8==8

False

2 == 1 + 1 and not 10==2*5 or 5==2*(2+1)

False

False and True

False

In Python, what value would be returned by the following code? 99 == '99'

False

True and True and True and False evaluates to:

False

not not not True

False

What is the // operator in Python?

Integer Division/Floored Quotient

'10' == 9 or 8==8

True

In Python, what value would be returned by the following code? x = 10 y = 15 z= 5 x <= y and y > z

True

True and True

True

True and True and True or False

True

True and True and True or False evaluates to:

True

True or False or True and True

True

True or False or True and True and not False

True

Working with lists The next subset of questions refer to the list defined below: aList = ['one','two','three',4,5] Don't forget to define this list in the next cell (Quiz5)

aList = ['one','two','three',4,5] aList[2] aList[1:5] aList[1][0:2] print(aList) aList.append('Python') print(aList) print(aList) aList[3] = aList[3] + 1000 print(aList) print(aList) aList[0] = 1 print(aList)

In the next cell define a function, listform that meets the following specifications: Specifications: The function must display text that tells the user "This is a program to create a list" You must use a while loop in your code Store the values in a list variable called, aList Prompt the user to enter values for their list and tell them how to exit the program when they are doneExit the program if the user hits enter without typing any characters Print the users final list formatted as indicted below:When printed to the screen the user should see their list items formatted like the following:Red, Orange, YellowNote the items should print with the first letter capitalized even if the user enters all lower case Define your function in the next cell but do not call it yet

aList = [] def listform(): print('This is a program to create a list.') while True: item=input('Enter a value for your list. Click enter when you are done.') if item == "": break aList.append(item) for i in aList: aListJoin = ', '.join(aList) print(aListJoin.title()) CALLED: listform()

Assign a variable, age, the integer value that a user inputs when given the prompt, "What is your age? " Check to see if the user inputted value for age is less than or equal to 25If the age entered is 25 or less, print to the screen the text: "You are pretty young!"If the age entered is not 25 or less, print to the screen: "You are getting old!"

age = int(input("What is your age?")) if age < 25: print("You are pretty young!") else: print("You are getting old!")

Data Preparation - Convert the fields that should be numeric to float Make the changes in the existing data frames (i.e., don't create new DataFrames)

bls08 = bls08.astype({"year": int, "occ_code": object, "occ_title": object, "group": object, "tot_emp": float, "emp_prse": float, "h_mean": float, "a_mean": float, "mean_prse": float, "h_pct10": float, "h_pct25": float, 'h_median': float, "h_pct75": float, "h_pct90": float, "a_pct10": float, "a_pct25": float, "a_median": float, "a_pct75": float, "a_pct90": float, "annual": object, "hourly": object})

Data Preparation - Correctly Filling pandas Null Values Replace the characters you found to be causing pandas to read the data in as objects with null valuesMake the change in place for each DataFrame (i.e., don't create new data frames for this)Use default null value for pandas, 'NaN', as your replacement value

bls08 = bls08.replace(['*','#','**','~'],'NaN') bls09 = bls09.replace(['*','#','**','~'],'NaN') bls10 = bls10.replace(['*','#','**','~'],'NaN') bls11 = bls11.replace(['*','#','**','~'],'NaN')

Replace group column null values with 'detail' The BLS Source data only includes labels under the group column for total and major groups. All other job descriptions are considered 'detail' job descriptions so fill in values for this in case a report or analysis request asks for breakout by group type. Do this for every year of data Make sure your changes are done in place

bls08.group.fillna('detail', inplace = True) bls09.group.fillna('detail', inplace = True) bls10.group.fillna('detail', inplace = True) bls11.group.fillna('detail', inplace = True)

Add a year column to all DataFrames This is important to easily distinguish data across years when we combine data Name the column, 'year' Insert the appropriate year value for each dataset as the first column

bls08.insert(0,'year',2008) bls09.insert(0,'year', 2009) bls10.insert(0,'year',2010) bls11.insert(0,'year',2011)

Data Preparation - Set the index Set the index on all annual data frames to the year, occ_code and occ_title Make the change in the current DataFrames (i.e., in place)

bls08.set_index(['year','occ_code','occ_title'], inplace = True)

Explore the data for potential problems Why are fields that should be numeric being read in as objects?For example, a_median represents the annual median wage which we would expect to be a numeric data type but did it get read into your DataFrame as a numeric value? Explore the data using various methods and tools in pandas to find the source of this problem For points on this question complete the following: Show what code you wrote to help examine the data type issue in the first cell In the blank markdown cell show what character's are causing pandas to read much of the data in as object data types.

bls08['h_pct90'].nunique

Data Preparation: Consistent Column Naming Look closely at how the field/column names are entered for all years Are all the fields entered identically across years?If not, convert all years to match how the column names are entered for 2008

bls10.columns = map(str.lower, bls10.columns) bls10

Reset the index for bls4yr Show the last 5 records in the output for this question

bls4yr = bls4yr.reset_index(drop=False) bls4yr.tail()

Combine the Data and name the new DataFrame, bls4yr Show the rows and columns of the combined dataframe as output for this question

bls4yr = pd.concat([bls08,bls09,bls10,bls11]) bls4yr.shape

In the next cell, show the method you used to determine if you had more cleaning to do on occ_title Only examine the major categories for this question

bls4yr.loc[(bls4yr['group']=='major'),['occ_code','occ_title']] bls4yr.occ_title.value_counts()

Data should be getting cleaner! Do you have more data cleaning to do on the major occ_title's? Re-examine the major occ_titles If there is anything else you should clean up do that in the next cells In the next cell, show the method you used to determine if you had more cleaning to do on occ_title

bls4yr.loc[(bls4yr['group']=='major'),['occ_code','occ_title']].nunique()

n the next cell, write any code you used to make the occ_title's more consistent

bls4yr['occ_title'] = bls4yr.occ_title.str.lower()

Write a while loop that will return the following output using the variable, count. Specifications: You must use a while loop for this question Your output should look like what is shown in the next code cell.

count = 0 while count < 10: print(f"The count is: {count}") count += 1 print("Good Bye!")

Task: write a while loop that will return the following output: The count is 1The count is 2The count is 3The count is 4The count is 5The count is 6The count is 7The count is 8The count is 9Good bye!

count = 0 while count <9: count = count +1 print(f'The count is {count}') print('Goodbye!')

Working with Dictionaries The next subset of questions refer to the dictionary defined below: d = {'k1':[{'nest_key':['this is deep',['hello']]}]} Don't forget to define this dictionary in the next cell

d['k1']

Working with Dictionaries¶ The next subset of questions refer to the dictionary defined below: d = {'k1':[{'nest_key':['this is deep',['hello']]}]} Don't forget to define this dictionary in the next cell 6b. In the next cell, grab the string, 'this is deep' (quiz5)

d['k1'][0]['nest_key'][0]

Working with Dictionaries¶ The next subset of questions refer to the dictionary defined below: d = {'k1':[{'nest_key':['this is deep',['hello']]}]} Don't forget to define this dictionary in the next cell 6c. In the next cell, grab the string, 'hello' (3 points

d['k1'][0]['nest_key'][1][0]

Working with Dictionaries The next subset of questions refer to the dictionary defined below: d = {'k1':[{'nest_key':['this is deep',['hello']]}]} Don't forget to define this dictionary in the next cell 6d. In the next cell, grab the first three letters of 'hello' (3 points)

d['k1'][0]['nest_key'][1][0][0:3]

Task: Create a function to return customer level Create a function for returning a customer level based on revenue. The customer levels are: Bronze (<250,000 in revenue) Silver (>=250,000 but < 500,000 in revenue) Gold (>=500,000 but < 750,000 in revenue) Platinum (>=750,000 in revenue) Call your function 4 times and pass these values to it to check that your function returns the correct output: 200,000 300,000 600,000 1,000,000

def custLevel(rev): if rev <250000: print('Bronze') elif rev >=250000 and rev <500000: print('Silver') elif rev >=500000 and rev <750000: print('Gold') elif rev >=750000: print('Platinum') custLevel(200000) custLevel(300000) custLevel(600000) custLevel(1000000)

Write Python code to define a function called, divide, that will divide two numbers. Specifications: Use two parameters in your function named: a and b will be the numerator will be the denominator Include code that will handle the possibility that a user will pass a value of 0 to the denominator. In your exception handling code, tell the user "Cannot divide by 0, please enter non-zero denominator for second value"

def divide(num,denom): try: return (num / denom) except ZeroDivisionError: print('Cannot divide by 0, please enter non-zero denominator for second value') divide(10,2)

Factorial of a number In the next cell define a function, fact, to calculate and print the factorial of a number If you don't remember what a factorial is, look it up Specifications: Your function should have only one parameter You must use a for loop For example, if passed 7 as the parameter, your function should print a statement: "The factorial of 7 is 5040"

def fact(num): fact = 1 for i in range(1,num+1): fact = fact*i print(f'The factorial of {num} is {fact}') fact(7)

In the next cell define a function, numCheck, that will check whether a number is in a given range Specifications: Your function should take three parametersA number to be checkedA low for the rangeA high number for the range Print two statements to the user based on if the number is within the range or notIf in the range print: '{num} is in the range between {low} and {high}If not in the range print: '{num} is outside the range between {low} and {high}'Where {num}, {low}, and {high} are the actual numbers passed to your function

def numCheck(num,low,high): if num in range(low,high): print(f'{num} is in the range between {low} and {high}') else: print(f'{num} is outside the range between {low} and {high}') numCheck(5,3,100)

List Append Square Function Write a function named, square, that when passed a list of numbers as the parameter will return a list of squares of the integers stored in the original list. For example, your function when passed the list [1,2,3,4] would return the list [1,4,9,16].

def square(list1): list2 = [] for i in list1: list2.append(i**2) print(list2) square([1,2,3,4])

Create a function named, summation Prompt the user to enter the lower bound and upper bound of a range of numbers to sum Calculate and return the sum of all numbers between the lower and upper bound Note: The upper and lower bounds are inclusive

def summation(): lower = int(input('Enter a lower bound number.')) upper = int(input('Enter an upper bound number')) for i in range(lower,upper+1): print(sum(range(lower,upper+1))) break summation()

Unique item list Write a function, unique_list that takes a list as a parameter and returns a new list with unique elements of the first list. For example, your function could take the list, [1,1,1,1,2,2,3,3,3,3,4,5] and return the list, [1,2,3,4,5]

def unique_list(list1): list = [] for x in list1: if x not in list: list.append(x) return list print(unique_list([1,1,1,1,2,2,3,3,3,3,4,5]))

Select the correct Python function to convert a value to a floating-point number

float()

Q1 (3 Points): Import Pandas and give it an alias as pd

import pandas as pd

Select the correct Python function to convert a value to an integer

int()

how the number of columns/fields in the dataset Just the number of columns, nothing else

len(student.columns) student.shape[1]

Create a while loop that checks for a user name and password and never stops asking until the correct password is entered. Specifications: Ask a user for their name and store the value in a variable labeled, name. Print a statement that says: "Hi, {userName}, what is the password?"Note: the print statement should use the value inputted by a user not the literal {userName} given above Prompt a user to input a password variable named, password. If the password matches the value, 'codingrulz', print 'Access Granted!' and exit the loop If the password does not match, 'codingrulz', print 'Access Denied' and restart the code. Finally, on the last line of output, print. "Have a good rest of your week, {userName}, see you Monday!"

name = ' ' password = ' ' while password != "codingrulz": name = input("What is your name?") password = input(f'Hi, {name}, what is the password?') if password == 'codingrulz': print("Access Granted") break print('Access Denied') print(f'Have a good rest of your week, {name}, see you Monday!')

Task: create a for loop that will store the squares of all numbers in a list variable provided. Specifications: The numbers variable is defined as: numbers = [1,2,4,5,12,25] You must use a for loop in this question to iterate through the numbers list to produce the values stored in the sq list. Store the squares of all the numbers in, numbers, in a new list variable named, sq. Print what is currently stored in the sq variable at each iteration of the loop. #The following should start your code: numbers = [1, 2, 4, 5, 12, 25]

numbers = [1,2,4,5,12,25] list = [] for i in numbers: sq = i**2 list.append(sq) list

In the next cell define a function, cirArea, to calculate and print the area of a circle Specifications: Assume pi=3.14 Your function should only have one parameter, diameter, passed to it If you forgot how to calculate the area of a circle, look it up (Google it). Print a statement describing the area of the circleFor example, if passed 100 as the parameter, your function should print a statement: "The area of your circle is: 7850 units squared"

pi = 3.14 def cirArea(diameter): area = pi*((diameter/2)**2) print(f'The area of your circle is: {area} units squared.') cirArea(20)

The seven dwarfs lists Use the following list to answer questions Q2a-Q2e [24]: dwarfs = ['Happy', 'Sleepy', 'Doc', 'Bashful', 'Sneezy', 'Grumpy', 'Dopey'] In the next cell, change 'Dopey' to 'Scrappy' and print the list before and after the change

print(dwarfs) dwarfs[-1]='Scrappy' print(dwarfs)

In the next cell, add a new dwarf, 'Hungry', to dwarfs2 and print the list before and after the change.

print(dwarfs2) dwarfs2.append('Hungry') print(dwarfs2)

Insert a new dwarf, 'Booboo', as the second item in the list dwarfs2 and print the list before and after the insert

print(dwarfs2) dwarfs2.insert(1,'Booboo') print(dwarfs2)

In the next cell, sort the dwarfs2 list in descending order and print the list before and after the sort.

print(dwarfs2) dwarfs2.sort(reverse=True) print(dwarfs2)

Select the correct Python function to convert a value to a string

str()

Show the Quiz1 and Quiz2 scores for students that scored an 80 or above on Quiz1

stu = student.loc[student.Quiz1 >=80] stu.iloc[:,3:5]

Show the lastName and Quiz2 scores for students that scored a 90 or above on Quiz2

stu1 = student.loc[student.Quiz2 >=90] stu1.iloc[:,[1,4]]

show the lastName, Quiz1, and Quiz2 scores for students that scored an 80 or above on Quiz2 and a 95 or above on Quiz1

stu2 = student.loc[(student.Quiz2 >=80) & (student.Quiz1 >=95)] stu2.iloc[:,[1,3,4]]

(1) Assign the student100.xlsx data to a DataFrame object named, student (1) Read the students100.xlsx (1) Set the index for the student DataFrame to the 'studentID' column

student = pd.read_excel('students100.xlsx', index_col = 0) student

Show what datatypes are in the dataframe

student.dtypes

Show the first 7 rows of the student dataframe

student.head(7)

Show the third through the 10th records Show all the fields/columns related to these records

student.iloc[2:10]


Conjuntos de estudio relacionados

Safety and infection control - Client needs

View Set

Financial Management Of The Firm Chapter 9

View Set