V

@Videonerd03

Floating-point expression

Python
3 months ago
#Write an assignment statement for the following mathematical equation: #y = (1/3)x + (x/4) + 2x #Keep x as an integer. Use an expression that matches the equation's right side as closely as possible. If the input is -1, the output is -2.58333. #Hints: #Don't rearrange the equation or try to simplify it. #If both operands of division (or other operators) are integers, #integer division is performed, which rounds down;

Total feet and total miles added

Python
3 months ago
#Decompose into feet and inches for the first line feet, inches = divmod(totalInches, INCHES_PER_FOOT) #Totals in other units (as decimals) totalFeet = totalInches / INCHES_PER_FOOT totalYards = totalInches / INCHES_PER_YARD totalMiles = totalInches / INCHES_PER_MILE #Optional: also show miles -> yards -> feet -> inches breakdow

Inches to feet

Python
3 months ago
# Given a total amount of inches, convert the input into a readable output in feet and inches totalInches = int(input("Enter total inches: ")) feet = int(totalInches/12); inches = int(totalInches - feet*12); print(f'{feet}\'{inches}"')

Convert the percentage into decimal

Python
3 months ago
# float() is a built-in function that converts a value into a floating-point number # A floating-point number (or float) is any number that can have a decimal point, such as: 3.14 , 0.75, 12.5 , -9.0 # Floats are used when you need decimal precision, not whole integers #Given an input as a percentage, write a program that converts the percentage into decimal form and outputs the results number = input("Enter a number: ") percent = float(input()) decimal = percent / 100 print = (decimal)

MadLibs practice

Python
3 months ago
# Mad libs are word games which require a person to provide various words to complete a short and fun story. Complete the following program #to make a Mad lib of your own name = input("Enter a name: " ) location = input("Enter a location: ") number = input("Enter a number: ") pluralNoun = input("Enter a plural noun: ") print( f"{name} went to {location} to buy {number} different types of {pluralNoun}. "

Manage Superman Actors

Python
3 months ago
import json # Why the import is nesscary # Without import json, the name json isn't defined, and you'll get a NameError the # moment you call json.dump , etc. #Modular design Python keeps functionality organized in modules from data classes import dataclass, asdict from typing import List, Optional

Exception handling

Python
3 months ago
try: user_age = int(input()) if user_age < 0: raise ValueError('Invalid age') avg_max_heart_rate = 220 - user_age print(f'Avg: {avg_max_heart_rate}') except ValueError as excpt:

Output of multiple exception handlers

Python
3 months ago
user_input = input() while user_input != 'end': try: #Possible ValueError divisor = int(user_input) #Possible ZeroDivisionError print(60 // divisor) #Truncates to an integer except ValueError: print('v') except ZeroDivisionError:

Trajectory of object on Earth

Python
3 months ago
# Common physics equations determine the x and y coordinates of a projectile object at any time # Given the object's initial veocity and angle at time 0 with the initial position of x = 0 and y = 0 # The equation for x is v * t * cos(a). #The equation for y is v * t * sin(a) - 0.5 * g * t * t. # The program's code asks the user for the object's initial veocity, angle, and height(y position), and prints the objects's position for every second #Until the object's y position is no longer gre

Engineering Examples PV = nRT Compute the tempature of a gas

Python
3 months ago
#Gas Equation - An equation used in physics and chemistry that relates pressure, volume, and temperature of a gas is PV = nRT. #P is the pressure #V = Volume #T = Temperature #n = number of moles #R = a constant # The function outputs the tempature of a gas given the other values

Multiple outputs can be returned in a container

Python
3 months ago
student_scores = [75, 84, 66, 99, 51, 65] def get_grade_stats(scores): #calculate the arithmetic mean mean = sum(scores)/len(scores) #calculate the standard deviation tmp = 0 for score in scores: tmp += (score - mean ) **2

Default parameters: Calculate splitting a check between diners

Python
3 months ago
# Write a split_check function that returns the amount that each diner must pay to cover the cost of the meal. #The function has four parameters: # bill: The amount of the bill. # people: The number of diners to split the bill between. # tax_percentage: The extra tax percentage to add to the bill. # tip_percentage: The extra tip percentage to add to the bill. # The tax or tip percentages are optional and may not be given when calling split_check. # Use default parameter values of 0.15 (15%)

Return number of pennies in total

Python
3 months ago
# Given that 1 dollar = 100 pennies, write a function number_of_pennies() that takes two arguments: the number of dollars, and an optional number of pennies. # number_of_pennies() should return the total number of pennies #The code reads three values from input and calls number_of_pennies() twice def number_of_pennies(number_of_dollars, optional_number_of_pennies=0): return number_of_dollars * 100 + optional_number_of_pennies print(number_of_pennies(int(input()), int(input()))) # Bo

Function arguments part 2

Python
3 months ago
# Write a function swap, that swaps the first and last elements of a list parameter def swap(item_list): item_list[0], item_list[-1] = item_list[-1], item_list[0] item = input().split() swap(item_list) print(item_list)

Function arguments

Python
3 months ago
# val_list is read from input. shift_left() has one parameter list_to_modify, and shifts list_to_modify left. #Call shift_left() with a copy of the list val_list as the arguement to avoid modifying val_list def shift_left(list_to_modify): index = 0 temp = list_to_modify[0] while index < len(list_to_modify) - 1: list_to_modify[index] = list_to_modify[index + 1] index += 1

Domestic movie numbers

Python
3 months ago
# Currency helpers CURRENCY_CODE = "USD" # default; will be updated by user input def get_currency_symbol(code): """Return a currency symbol for a given currency code.""" code = code.strip().upper() symbols = { "USD": "$", "INR": "₹", "EUR": "€",

Writing mathematical functions

Python
3 months ago
def find_prymaid_base_area(base_length, base_width): return base_length * base_width def find_pyramid_vol(base_length, base_width, height): base_area = find_pyramid_base_area(base_length, base_width) return base_area * height * (1.0 / 3.0) pyramid_base_length = float(input()) pyramid_base_width = float(input()) pyramid_height = float(input())

Function call in expression

Python
3 months ago
# assign max_sum with the greater of num_a and num_b PLUS the greater of num_y and num_z. Use just one statement. # Hint: Call find_max() twice in an expression def find_max(num_1, num_2): max_val = 0.0 if (num_1 > num_2): # if num1 is greater than num2 max_val = num_1 # then num1 is the maxVal else: max_val = num_2

Functions with parameters and return values

Python
3 months ago
# Define a function calculate_val() that has two parameters and returns the result of subtracting the product of 2 # And the second parameter from the first parameter def calculate_val(x,y): result = x - (2 *y) return result value_read1 = float(input()) value_read2 = float(input())

Hierarchical function calls

Python
3 months ago
# Complete the calc_pizza_calories_per_slice() function to calculate the calories for a single slice of pizza # A calc_pizza_calories() function returns a pizza's total calories given the pizza diameter passed as an arguement # A calc_num_pizza_slices() function returns the number of slices in a pizza given the pizza diameter passed an arguement def calc_pizza_calories_per_slice(pizza_diameter): total_calories = <placeholder_A> calories_per_slice = <placeholder_B>