Having trouble solving a simple Python Payroll program in Python 3.X - 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.

Related

Python 3 + Flask application that uses routes, views and GET parameters

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

python formattng output with input

Just started programming in python 3 and I am trying to pull from an input() where I have placed the input() command in the first line and then further down use the output() to retrieve the input().
Here is an example:
rent = eval(input("How much does rent cost per year? $"))
Now I want to get the input I put in (10,000) and retrieve it from the input automatically using output() or another command.
print output("The family rent is", _______ , "per year."
What code would go in the ________ so I can retrieve what I put in for the input?
Thanks - newbie
the code as is :
# get user input
user_input = input("How much does rent cost per year? $")
# cast to int or whaterver you're expecting
try :
cost = int(user_input)
except :
print ("expecting a number")
# stop here maybe return
# print output
print ("The family rent is", cost , "per year.")
Use string formatting:
print('The family rent is {} per year'.format(rent))
See here for documentation of string formatting:
https://docs.python.org/3/library/string.html#format-string-syntax

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()

Python how do you get a particular part of code to run again

Okay so I'm very new to the programming world and have written a few really basic programs, hence why my code is a bit messy. So the problem i have been given is a teacher needs help with asigning tasks to her students. She randomly gives the students their numbers. Students then enter their number into the program and then the program tells them if they have drawn the short straw or not. The program must be able to be run depending on how many students are in the class and this is where i am stuck, I can't find a way to run the program depending on how many students are in the class. Here is my code
import random
print("Welcome to the Short Straw Game")
print("This first part is for teachers only")
print("")
numstudents = int(input("How many students are in your class: "))
task = input("What is the task: ")
num1 = random.randint(0, numstudents)
count = numstudents
print("The part is for students") #Trying to get this part to run again depending on number of students in the class
studentname = input("What is your name:")
studentnumber = int(input("What is the number your teacher gave to you: "))
if studentnumber == num1:
print("Sorry", studentname, "but you drew the short straw and you have to", task,)
else:
print("Congratulations", studentname, "You didn't draw the short straw")
count -= 1
print("There is {0} starws left to go, good luck next student".format(count))
Read up on for loops.
Simply put, wrap the rest of your code in one:
# ...
print("The part is for students")
for i in range(numstudents):
studentname = input("What is your name:")
#...
Also, welcome to the world of programming! :) Good luck and have fun!

Resources