Value not printing from inputs in UDF - python-3.x

Could I know what's missing in my UDF , my brain is fried atm and couldn't figure out what went wrong.
import math
import numpy as np
CoP = input("Enter the Value 1: ")
Po = input("Enter the Value 2: ")
Rf = input("Enter the Value 3: ")
Ti = input("Enter the Value 4: ")
def Total():
Rf = Rf / 100
Ti = Ti/ 12
Total = CoP - (Po * np.e ** (-(Rf * Ti)))
print(Total)
return Total
~Brittany

You cant use the global vars directly inside the method
Either pass the vars as arguments or declare the vars as global inside the method
Edit~: Converted the str to float
Method 1
import numpy as np
CoP = float(input("Enter the Value 1: "))
Po = float(input("Enter the Value 2: "))
Rf = float(input("Enter the Value 3: "))
Ti = float(input("Enter the Value 4: "))
def Total(CoP, Po, Rf, Ti):
Rf = Rf / 100
Ti = Ti / 12
Total = CoP - (Po * np.e ** (-(Rf * Ti)))
print(Total)
return Total
Total(CoP, Po, Rf, Ti)
Method 2
CoP = float(input("Enter the Value 1: "))
Po = float(input("Enter the Value 2: "))
Rf = float(input("Enter the Value 3: "))
Ti = float(input("Enter the Value 4: "))
def Total():
global CoP, Po, Rf, Ti
Rf = Rf / 100
Ti = Ti / 12
Total = CoP - (Po * np.e ** (-(Rf * Ti)))
print(Total)
return Total
Total()

Related

Is it possible to not have to replicate code for each iteration of the function

def math():
x = str('y')
while x == 'y':
a = float(input("Please enter a number: "))
a = (((4*a)+1)/(a-3))
b = float(input("Please enter a number: "))
b = (((4*b)+1)/(b-3))
c = float(input("Please enter a number: "))
c = (((4*c)+1)/(c-3))
d = float(input("Please enter a number: "))
d = (((4*d)+1)/(d-3))
print(a)
print(b)
print(c)
print(d)
x == str(input("Would you like to continue"))
math()
Hello I'm new to programming and I was just casually doing this to make an easy calculator for my homework assignment and I wanted to know instead of replicating the code for each variable if there was a way to do the math one time and just keep reassigning values to the variable for the math. This might be dumb a question and it's not serious or anything I just was curious if there are better way's to do this.
Comments and suggestions:
def math():
x = str('y')
'y' is a string, so there is no need to convert it to a string using str(). x = 'y' is sufficient.
while x == 'y':
a = float(input("Please enter a number: "))
a = (((4*a)+1)/(a-3))
b = float(input("Please enter a number: "))
b = (((4*b)+1)/(b-3))
c = float(input("Please enter a number: "))
c = (((4*c)+1)/(c-3))
d = float(input("Please enter a number: "))
d = (((4*d)+1)/(d-3))
DRY - don't repeat yourself.
Define a function which takes an input and returns the computed results:
def compute(n_times):
results = [] # initialize results, empty list
for repetition in range(n_times): # repeat n times
inp = float(input("Please enter a number: "))
results.append(((4 * inp) + 1) / (inp - 3)) # append result to list
return results # return filled list
and call this function n times:
result_list = compute(4) # compute() returns a list with results
for result in result_list: # iterate through list
print(result)
ask user if they wish to continue:
x == input("Would you like to continue? ")
run your function:
math()
Conclusion:
def compute(n_times):
results = [] # initialize results, empty list
for repetition in range(n_times): # repeat n times
inp = float(input("Please enter a number: "))
results.append(((4 * inp) + 1) / (inp - 3)) # append result to list
return results # return filled list
def math():
how_often = 4
answer = 'y'
while answer == 'y':
result_list = compute(how_often) # compute() returns a list with results
for result in result_list: # iterate through list
print(result)
answer == input("Would you like to continue? (y/n): ")
math()

Regarding Employee Record in python

I have been working in an employee program in python and I an facing difficulties
The out put should look like below
from array import *
arr = array("i", [])
n= (int(input("Enter the number of employee's: ")))
arr.append(n)
for i in range(1,n+1):
name = input("Enter the name of the employee %s: " %(i))
from array import *
salary = array("f", [])
x = int(input("Enter %s current salary: " %(name)))
arr.append(x)
from array import *
Q1 = array("f", [])
rating1 = int(input("Enter the rating %s received for Q1: " %(name)))
arr.append(rating1)
from array import *
Q2 = array("f", [])
rating2= int(input("Enter the rating %s received for Q2: " %(name)))
arr.append(rating2)
from array import *
Q3 = array("f", [])
rating3 = int(input("Enter the rating %s received for Q3: " %(name)))
arr.append(rating3)
from array import *
Q4 = array("f", [])
rating4 = int(input("Enter the rating %s received for Q4: " %(name)))
arr.append(rating4)
def totalrating():
totalrating = [rating1, rating2, rating3, rating4]
total = sum(totalrating)
return(total)
def overallrating():
overallrating = totalrating()/4
return(overallrating)
def display():
print(name, x, rating1, rating2, rating3, rating4, totalrating(), overallrating())
display()
My programs goes like
The Out put is only returning the second value not the first can you help me what needs to be done
Alright so there is a lot of cleanup to do here. I will point out the changes in code comments and try to further explain as needed.
# The multiple import of array are redundant and the way you are using this is actually
# wrong so it's not needed. So I am commenting out this one and then deleting the rest.
# from array import *
# Here you just need a basic list and not an instance of the array module.
# arr = array("i", []) <- old code for reference.
arr = []
n= (int(input("Enter the number of employee's: ")))
# I commented out this line because you don't ever access this element after you set it
# so you can just not set it at all.
# arr.append(n)
# Because we got rid of the append above we can loop from 0 to n instead of 1 to n+1
for i in range(0, n):
name = input("Enter the name of the employee %s: " %(i))
# These sub arrays is unnecessary and part of the problem
# salary = array("f", [])
salary = int(input("Enter %s current salary: " %(name)))
# So the way you are appending stuff is part of the problem.
# Let's remove all of these appends out and we can do them at the end of the loop
# arr.append(x)
rating1 = int(input("Enter the rating %s received for Q1: " %(name)))
rating2 = int(input("Enter the rating %s received for Q2: " %(name)))
rating3 = int(input("Enter the rating %s received for Q3: " %(name)))
rating4 = int(input("Enter the rating %s received for Q4: " %(name)))
# Here we can append a dictionary to the array with the data laid out how you want it.
arr.append({
'name': name,
'salary': salary,
'rating1': rating1,
'rating2': rating2,
'rating3': rating3,
'rating4': rating4,
})
# Note the display function is now passing in the employee info here.
def totalrating(employee):
# So this function can be modified a few ways
# Also don't name variables the same as functions. It can lead to name clashing issues.
'''
# This is the original code and I am leaving is for posterity.
totalrating = [rating1, rating2, rating3, rating4]
total = sum(totalrating)
return(total)
'''
'''
# Here is the first way it could be modified.
total_rating = [
employee['rating1'], employee['rating2'], employee['rating3'],
employee['rating4']
]
total = sum(total_rating)
return total
# not there is no need to put () around the return in python
'''
# Here is how I would modify it though.
rating_keys = ['rating1', 'rating2', 'rating3', 'rating4']
return sum([employee[rate] for rate in rating_keys])
# This can be rewritten in one line and since it's only used in one place it should be done there
# def overallrating():
# overallrating = totalrating()/4
# return(overallrating)
def display():
# Now that the array has been cleaned up we can go through the array and print it.
for employee in arr:
# Instead of calculating them in the print statement just make variables ahead of time
total = totalrating(employee)
# This whole function is a one liner that should just be done here.
overall_rating = total/4
print(
employee['name'], employee['salary'], employee['rating1'], employee['rating2'],
employee['rating3'], employee['rating4'], total, overall_rating
)
display()
This should output as you asked. Cleaned up without the comments and old code the final product is:
arr = []
n= (int(input("Enter the number of employee's: ")))
for i in range(0, n):
name = input("Enter the name of the employee %s: " %(i))
salary = int(input("Enter %s current salary: " %(name)))
rating1 = int(input("Enter the rating %s received for Q1: " %(name)))
rating2 = int(input("Enter the rating %s received for Q2: " %(name)))
rating3 = int(input("Enter the rating %s received for Q3: " %(name)))
rating4 = int(input("Enter the rating %s received for Q4: " %(name)))
arr.append({
'name': name,
'salary': salary,
'rating1': rating1,
'rating2': rating2,
'rating3': rating3,
'rating4': rating4,
})
def totalrating(employee):
rating_keys = ['rating1', 'rating2', 'rating3', 'rating4']
return sum([employee[rate] for rate in rating_keys])
def display():
for employee in arr:
total = totalrating(employee)
overall_rating = total/4
print(
employee['name'], employee['salary'], employee['rating1'], employee['rating2'],
employee['rating3'], employee['rating4'], total, overall_rating
)
display()

How to fix this

This code is supposed to find all the primes in a given range. But something is very wrong here
import math
def display(num, truth):
if truth:
print(num)
lower = int(input("Enter lower limit :"))
upper = int(input("Enter upper limit :"))
for x in range(lower, upper, 1):
b = 2
c = True
a = math.sqrt(x)
while b < a:
if x%b != 0:
continue
else:
c = False
break
display(x,c)
print("Done")
I expect that it should output, say between 2 and 6:
Enter lower limit :2
Enter upper limit :6
2
3
5
Done
But the output is (for same range)
Enter lower limit :2
Enter upper limit :6
2
3
4
Note that 'Done' does not appear
And when I try to close the shell Python warns that the program is still running.
I am not sure to understand some of the code you have written.
How About something like this:
import math
lower = int(input("Enter lower limit :"))
upper = int(input("Enter upper limit :"))
for x in range(lower,upper + 1):
# prime numbers are greater than 1
if x > 1:
for i in range(2,x):
if (x % i) == 0:
break
else:
print(x)
print("Done")

Python - track inputs

I am having difficulty keeping a track of the total number of inputs. I want my program to keep track of the total number of inputs and print it when my while loop breaks. Any help is appreciated!
r = float(input("enter r:"))
def main(r):
a = 3.14 * (float(r ** 2))
s_v = 0
total = 0
while True:
r = float(input("enter r:"))
if r == sentinal_value:
total += r
print("Total = " , total)
break
else:
print("Area = ", a)
continue
main(r)
I assume that you want your program to re-calculate the area with each iteration. As written, it will only be calculated the first time you run the mymian function. You don't need to pass any arguments to the function.
def mymian():
sentinal_value = 0
total = 0
while True:
r = float(input("enter r:"))
if r == sentinal_value:
print("Total number of r provided to this program" , total)
break
else:
print("Area = ", 3.14 * (float(r ** 2)))
total += 1
continue

How do I create a table function for my program?

I want to make a function which pulls the data from the code and creates a table out of it:
if mode_choice ==1 or 2:
def main():
pv= float(input("Enter the principle amount: "))
interest = float(input("Enter the interest rate (in perecent): "))
term = int(input("Enter the term (in months): "))
interest = interest / 12 / 100
payment = (interest * pv) / (1-(1 + interest)**-term)
main()

Resources