Python 3 + Flask application that uses routes, views and GET parameters - python-3.x

I have the following problem for part of my python class homework:
Using the functions you created earlier, make a flask application that takes arguments and displays the results of the calculations using routes/views.
For example, you will have three routes and they can be called square, triangle, and cost. You will pass GET query string parameters to these routes and the view will display the appropriate results.
I did some research and could not figure out what to do with Flask. My teacher gave a very short overview in class on Flask, and I'm a beginner with Python, so hoping someone can help me.
I just have no idea what to do. Any help I can get would be appreciated. Thanks!
Here is the code for the functions (this code works)
functions.py file:
# Using the input function ask the user for the base of a triangle and store in a variable
print()
b = int(input(str(user_name)+ ", please enter the base length of your triangle: "))
print()
#Using the input function ask the user for the height of a triangle and store the value in a variable
#Where b = length of base and h = length of height
h = int(input("Now please enter the height length of your triangle: "))
print()
#Call your function passing the two variables that contain the values for base and height
print("The area of your triangle", user_name, "is", str(area_tr(b,h)) +".")
print()
#Part 3: Total Cost
#Assume you work for an outdoor clothing company. Your job is to find out the total cost of buying raw materials for a winter jacket.
#Create a function that takes two arguments and returns the total cost using the formula:
#Total cost = Number of units X price per unit
def tc_wjacket(u,p):
"""
total cost of buying raw materials for a winter jacket.
Total cost = Number of units X price per unit.
"""
return u * p
#Using the input function ask the user for the numbers of units and store it in a variable.
print()
u = int(input(str(user_name)+ ", please enter the number of winter jackets you want for your store: "))
print()
#Using the input function ask the user for the price per unit
p = int(input("Now please enter the cost of the raw materials per jacket: "))
print()
#Call your function passing the two variables that contain the values for number of units and price per unit
print(str(user_name)+ ", according to my calculations, the cost to buy the raw materials for", b ,"jackets with at", p ,"dollars per jacket is", tc_wjacket(u,p) ,"dollars.")
print()
print("I hope this information was helpful " + str(user_name)+ ".")
print()

#importing Flask
from flask import Flask
#creating an app instance in the current namespace
app = Flask(__name__)
#decorator
#app.route("/")
#app.route("/square/<int:side1>/<int:side2>/<int:side3>/<int:side4>")
def add(side1,side2,side3,side4):
"""
perimeter of a square
"""
perim = (side1 + side2 + side3 + side4)
return "<h2>Your square's parimeter is {}</h2>".format(perim)
#app.route("/triangle/<int:b>/<int:h>")
def area_tr(b,h):
"""
Function calculates the area of a triangle
formula = (base * height)/2
"""
area_tr = b * h / 2
return "<h2>Your triangle's area is {}</h2>".format(area_tr)
#app.route("/cost/<int:u>/<int:p>")
def tc_wjacket(u,p):
"""
total cost of buying raw materials for a winter jacket.
Total cost = Number of units X price per unit.
"""
total_cost = u * p
return "<h2>Your triangle's area is {}</h2>".format(total_cost)
#debug=True allows us to make changes to our code and see them in the browser without having to re-run our app
app.run(debug=True, port=8000, host='0.0.0.0')

Related

How to return the mean minus each of the integer in a list with Python?

I have a list of sample stock prices for two stocks, IBM and MSFT. After finding the average stock prices of the two stocks, I want to find the mean adjusted stock prices for the two stocks. This is done by subtracting the respective stock prices by their average stock price.
Then, to find the best fit line, I need to find a way to compute (to find m):
mean_adjusted stock price IBM = m * mean_adjusted stock price MSFT
However, I am also stuck in returning a list of mean adjusted stock prices for the two stocks.
import statistics
def get_best_fit_line(price_IBM, price_MSFT, averagePrice_IBM, averagePrice_MSFT):
mean_adjusted_IBM = []
mean_adjusted_MSFT = []
for number in price_IBM:
mean_adjusted_IBM.append(number - averagePrice_IBM)
return mean_adjusted_IBM
for number2 in price_MSFT:
mean_adjusted_MSFT.append(number2 - averagePrice_MSFT)
return mean_adjusted_MSFT
price_IBM = [132.45, 130.85, 130.00, 129.55, 130.85, 129.48, 130.51, 130.23, 132.31, 131.78]
averagePrice_IBM = statistics.mean(price_IBM)
price_MSFT = [30.95, 30.96, 30.77, 30.45, 30.66, 30.27, 30.07, 30.35, 30.96, 30.86]
averagePrice_MSFT = statistics.mean(price_MSFT)
IBM, MSFT = get_best_fit_line(price_IBM, price_MSFT, averagePrice_IBM, averagePrice_MSFT)
print('The mean adjusted stock price for IBM is ', IBM)
print('The mean adjusted stock price for MSFT is ', MSFT)
Please help!
First, create a function to average the list of number
def average(lst):
return sum(lst) / len(lst)
Function, to minus the average to each number in the list
def get_append_avg(price_list, average_val):
mean_adjusted=[]
for number in price_IBM:
mean_adjusted.append(number - average_val)
return mean_adjusted
Call each def as below
IBM=get_append_avg(average(price_IBM))
MSFT=get_append_avg(average(averagePrice_MSFT ))

Need help calculating average from text file

I've kind of run into a brick wall with one of my latest assignments where I have to calculate the class average from a text file that is created after a certain amount of inputs from a user.
Code:
f=open('class.txt','w')
title=['name','english','math','science']
f.write(str(title)+""+"\n")
name=input("enter student name:")
m=int(input("enter math score:"))
e=int(input("enter english score:"))
s=int(input("enter science score:"))
o=input("do you wish to continue?: y/n:")
f.write(name + " " +str(m)+ " "+str(e)+" "+str(s)+" "+"\n")
name =[]
while o !='n':
name=input("enter a student name:")
m=int(input("enter math score:"))
e=int(input("enter english score:"))
s=int(input("enter science score:"))
o=input("do you wish to continue?: y/n:")
f.write(name + " " +str(m)+ " "+str(e)+" "+str(s)+" "+"\n")
f.close()
Basically, the text file needs a header, hence the line with "title" in it, and after the user hits 'n' the text file gets saved.
Now I'm having trouble figuring out how to write the code that reads the text file, calculates the total score of each, calculates the average score of each student and then prints it all into three columns. If I could get any pointers as to how I should go about doing this it would be much appreciated! Thanks!
(I am not a phython programmer so the syntax may not be exactly right)
I am assuming that you are to write the code that produces the text file and calculates the average at the same time. If so then no need write file then re-read it, just keep running total and calculate average when you're done.
numberOfStudents = 0
int totalMathScore = 0
# Only showing math score add lines to do same with english / science
# see below about how loop should be structured
while continue != 'n':
numberOfStudents += 1
m=int(input("enter math score:"))
totalMathScore += m
# Now calculate average math score
averageMathScore = totalMathScore / numberOfStudents
Look for bits of repeated code and refactor. e.g. where you're getting the scores both outside and inside the loop. Thats poor style and should be either
a) Put that in a function
b) Or more likely for this simple example change loop to something like
continue = 'y'
while (continue != 'n'):
name=input("enter a student name:")
m=int(input("enter math score:"))
e=int(input("enter english score:"))
...
Other bonuses
Use descriptive variable names - e.g. mathScore rather than m
Error handling - what happens if someone types in "BANANA" for a score?

python TypeError: '<' not supported between instances of '_Printer' and 'int'

I am working on this code
A certain university classifies students according to credits earned. A student with less than 30 hours is a Freshman. At least 30 credits are required to be a Sophomore, 60 to be a Junior, and 90 to be a Senior. Write a program that calculates class standing from the number of credits earned with the following specifications:
Write a function named determineStatus() that prompts the user for how many credits they have earned and uses a decision structure (if, else, etc.) to determine the class standing of the student. The function should display the standing to the student (85 points).
If the user tries to enter a negative value, the program should alert the user that negative numbers are not allowed (5 points).
Write a main() function that calls the determineStatus() function (5 points).
def determineStatus():
credits= -1;
while(credits<0 ):
credits=int(input("enter number of credits earned: "))
if(credits<0):
print("ALERT: you entered negative credit. Pls try again")
if(credits<30):
print("A Freshman!")
elif(credits>30 and credits<60):
print("A Sophomore!")
elif(credits>60 and credits<90):
print("A Junior")
else:
print("A Senior")
def main():
determineStatus()
main()

Setting user input parameters and accounting for varying answers

I've managed to save input into a variable then called it in the function below it. I wanted to account for .upper() and .lower() choices such as if someone inputs "C", "c", "Circle", or "circle". Not sure how to do that though...
"""
a calculator that can compute the area of a chosen shape, as selected by the user. The calculator will be able to determine the area of a circle or a triangle
"""
from math import pi
from time import sleep
from datetime import datetime
#opening comments and thinking computer thinks for 1 second
now = datetime.now()
print("Calculator is booting up! Beep Boop...")
print(("%s/%s/%s " + "%s:%s \n") % (now.month, now.day, now.year, now.hour, now.minute))
sleep(1)
#nagging teacher comment if needed
hint = str("Don\'t forget to include the correct units! \nExiting...")
#user input choose Circle or Triangle
option = input("Enter C for Circle or T for Triangle: ")
#Circle computing
if (option.upper() == input(str(C))) or (option.lower() == input(str(c))):
radius = input(float("What is the radius?: "))
area = (pi * radius ** 2)
print("The pie is baking...")
sleep(1)
print(str(area + hint))
It's from a code academy project and tried to search for an answer but couldn't find one here
Just lower the input you get from the user and only test against lowercase:
if option.lower() == expected_lowercase_input:
That way you don't have to worry about case at all as 'FOO', 'Foo', 'fOO', etc., will all be lowered to 'foo'.
To account for variations like 'c' or 'circle', you could do something like:
expected = ('c', 'circle')
if option.lower() in expected:
...
Which will execute the if block if the lowercase version of option is 'c' or 'circle'.
Stick with the Codecademy stuff. It is a great resource in my opinion!

Having trouble solving a simple Python Payroll program in Python 3.X

This is the problem.
Write a program to solve a simple payroll calculation. Find the amount of pay given, hours worked, and hourly rate. (The formula to calculate payroll is pay = hourly rate * hours worked.)
What i have so far
def hours():
hours = input("how many hours did you work?: ")
return hours
def rate():
rate= input("How much is your hourly rate?: ")
def grossPay():
grossPay = hours() * rate()
return grossPay
def main():
print("your gross pay is"), + (grossPay)
return grossPay
def main():
print('Payroll Information')
print hours()
print rate()
main()
There are a few issues with the code...
You have no indentation in your code, which is required for Python (though you may have just pasted it into SO incorrectly)
You call the hours function, but one doesn't exist in your code blurb
Opinion: Seems needlessly complex for a simple operation
There are many ways to do this, but putting it all into one function is most natural to me. I'd do something like this...
def calc_and_show_pay():
rate = input("How much is your hourly rate?: ") #collect the hourly rate
hours = input("How many hours did you work?: ") #collect number of hours worked
gross_pay = float(rate) * float(hours) #Convert string input to floats so we can do math on it
print("Payroll Information:") #print out results, per your format in the example
print("Your pay is %f"%(gross_pay)) #could also do print("your pay is:", gross_pay)
return gross_pay #you don't need to return this unless you want to use this number elsewhere (i.e., you have a bigger program where you'll use this as an input somewhere else).
Then of course you can call "calc_and_show_pay()" as you please.

Resources