What's the problem in this short user-defined function? - python

It says that "salary" is not defined or that i can't multiply this.
I want to have it with the def command so please just let it in this form just correct the mistakes, im completely new to it so just let it as easy as it is. Thank you very much :)
def computepay(Hours,RatePerHour):
if float(Hours)-40<0:
salary=float(Hours)*float(RatePerHour)
else:
salary=40.0*float(RatePerHour)+(float(Hours)-40.0)*float(RatePerHour*1.5)
Hours=input("Hours:\n")
RatePerHour=input("RatePerHour:\n")
computepay(Hours,RatePerHour)
print("Salary:")
print(salary)
I expect that someone could help me how this little program works correct

You need to return salary and then assign this to a variable. Here's an improved version of your code:
def compute_pay(hours: float, rate_per_hour: float) -> float:
if hours - 40 < 0:
salary = hours * rate_per_hour
else:
salary = 40 * rate_per_hour + (hours - 40.0)* rate_per_hour * 1.5
return salary # This is the line you are missing!
hours = input("Hours:\n")
rate_per_hour=input("RatePerHour:\n")
computer_salary = computepay(float(hours), float(rate_per_hour)) # You also need to assign the output of a function to a variable, I've given it a different name from salary just to show you that this is a different variable from the one inside your function. Also, cast to float here so you don't have to do it all over your function.
print(f"Salary: {computer_salary}")
The concept you need to learn here is called scope.

You needed to return the calculated salary.
Also, simpler if you performed the float conversion on input.
def computepay(Hours,RatePerHour):
if float(Hours)-40<0:
salary=Hours*RatePerHour
else:
salary=40.0*RatePerHour+ (Hours-40.0)*(RatePerHour*1.5)
return salary # return value
Hours = float(input("Hours:\n")) # float conversion
RatePerHour = float(input("RatePerHour:\n")) # float conversion
salary = computepay(Hours,RatePerHour)
print("Salary:")
print(salary)

Here is the correction, and some explications follow.
def computepay(Hours,RatePerHour):
salary = 0
if float(Hours)-40<0:
salary=float(Hours)*float(RatePerHour)
else:
salary=40.0*float(RatePerHour)+(float(Hours)-40.0)*float(RatePerHour) *1.5) #<=== here you multiply with out turning rateperhour as float
return salary
Hours=input("Hours:\n") RatePerHour=input("RatePerHour:\n")
salary = computepay(Hours,RatePerHour)
print("Salary:")
print(salary)
First, salary is a variable enclosed inside your function, it's not a avaliable outside of it.
Second, you get an error because you multiply a string by an integer. Convert it to float before.
float(RatePerHour*1.5) #wrong
float(RatePerHour) *1.5 # correct

Related

Python - Take an int variable and times it by a float?

As a learning project, I'm attempting to write a small game to simply get familiar with the Python language as well as build my programming skills. Being somewhat of a gamer, I always seem to want to add additional code to the game to make it more playable and therefore enjoyable. Right now I'm stuck on stupid and hope this is fairly easy to solve by the more familiar:
Python 3.8.8
I have an int that has been randomly selected and added it to a variable:
if act_trl_cls == trl_cls[0]:
trl_atk_pwr = random.randint(7.0, 10.0)
What I'm looking to do is create a float (for percentage purposes) add it to a variable:
if act_trl_cls == trl_cls[0]:
trl_cls_wpn_ran = random.uniform(0.01, 0.05)
trl_cls_wpn_dmg = "{:.2f}".format(trl_cls_wpn_ran) # converts to two decimal points
... and then multiply them to get a percentage, much like we do with tipping.
Example:
Bill Total: $53.56
$53.56 * .20 = $10.71
$53.56 + $10.71 = $64.27
Total: $64.27
My question is how do we represent this in Python? Everytime I attempt:
if fight_confirmation == "Y" or fight_confirmation == "y":
total = trl_atk_pwr * trl_cls_wpn_dmg
... I end up with:
0.030.030.030.030.030.030.030.03
... or some other variation depending on the random int and float chosen by the random function and respective method rather than the return value of the multiplied values assigned to each variable. Obviously this is not the correct way to do this.
You have to convert it to float before multiplication like below .
if fight_confirmation == "Y" or fight_confirmation == "y":
total = float(trl_atk_pwr) * float(trl_cls_wpn_dmg)
You are getting this because now you are getting trl_cls_wpn_dmg as a string and it will do concatenation when you are multiplying it by a number.

NoneType from API?

Probably a very noobish problem but I just can't figure this out.
I'm calling a price info from server with .get command, then printing it out and then multiplying that price with the balance of my account.
Here is the code:
def ticker_sell(currency):
ticker_sell = client.get_ticker(symbol=currency)
ask_price = ticker_ask['askPrice']
print (ask_price)
balance = 1
ltcusdt = ticker_sell('LTCUSDT')
sold_to_usdt = float(ltcusdt) * float(balance)
When running the code, it prints out the price as float, as it should. However, when this float should be multiplied by balance (=1) I am getting error code:
TypeError: float() argument must be a string or a number, not 'NoneType'.
Is it possible that as I am calling value for key 'LTCUSDT', the key is somehow messing things up?
Change ticker_sell to this:
def ticker_sell(currency):
ticker_sell = client.get_ticker(symbol=currency)
ask_price = ticker_ask['askPrice']
return ask_price
You need to have a return statement for ticker_sell to provide a value to ltcusdt

Transforming an input variable into an interger

I'm completely new to python, and I wanted to create a program that "loads" a number that the user would have entered.
To do this, I made a function with an input variable,
percentage
that I then tried to transform to an interfer,
percentage_int
To then put in a while loop.
However, I get an error message, why?
def loader():
percentage = input("what percentage do you want?")
percentage_int =int(percentage)
x = 0
print("Goal:{} %".format(percentage_int))
while x < percentage_int:
x+=1
print(x)
loader()
You need to do the type conversion, that is in this case from string to integer.
If you dont do so python will consider percentage_int as the input string itself.
percentage = input("what percentage do you want?")
percentage_int = int(percentage)
Go through this tutorial which will help you learn more about type conversions with python.

Replacing Iteration with Recursion Python [duplicate]

This question already has answers here:
Is this function recursive even though it doesn't call itself?
(3 answers)
Closed 5 years ago.
I'm just starting to learn about recursion for an EdX course, and I've written an iterative function to calculate the remaining balance after paying the minimum required payment for 12 months.
I was able to easily do it with iteration, but I can't seem to wrap my head around the recursive way.
Please point me in the right direction.
Here is my iterative function
def remaining_balance_iter(balance,annualInterestRate, monthlyPaymentRate ):
'''
This code will take any balance and annual interest rate and calculate the
balance after one year of making the minimum payments
'''
month = 1
monthly_interest_rate = annualInterestRate/12.0
while month <= 12:
minimum_monthly_payment = monthlyPaymentRate * balance
monthly_unpaid_balance = balance - minimum_monthly_payment
balance = monthly_unpaid_balance + monthly_interest_rate*monthly_unpaid_balance
print( "Month {} Remaining balance: ".format(month) + str(round(balance,2)))
month += 1
print ("Remaining balance " + str(round(balance,2)))
I've made an attempt at a recursive function, but it needs work, and I need tutoring haha
def remaining_balance_recur(balance,annualInterestRate, monthlyPaymentRate, month ):
'''
This code will take any balance and annual interest rate and calculate the
balance after one year of making the minimum payments
'''
month = 1
monthly_interest_rate = annualInterestRate/12.0
while month <= 12:
minimum_monthly_payment = monthlyPaymentRate * balance
monthly_unpaid_balance = balance - minimum_monthly_payment
interest = monthly_interest_rate*monthly_unpaid_balance
balance = remaining_balance_recur(monthly_unpaid_balance, annualInterestRate, monthlyPaymentRate, month + 1) + interest
print ("Remaining balance " + str(round(balance,2)))
The best way I've found to deal with recursion is to start by specifying a base case. What is the condition that tells you when you've finished your method? In your code, it looks like you run your method until `month > 12', so your base case would be:
if month > 12:
return 1 # 1 for the purpose of explanation
Your return value for your base case is some base value of your function. What would your script return if your month was 12? That's the value you would return.
Next is the hard part. You have to figure out what variable is being modified by subsequent calls to your method. I'm not exactly sure what your code is intended to do, but it looks like you have a few calculations on some variables. When you use recursion, it's almost as if you're saving the state of the current method call you are executing while you go and retrieve the value you need for your statement. (e.g. a_num = 1 + recurse(n - 1) - you need the value of recurse(n - 1) before you can continue with this statement. This is only an example, though). Look for the variable that is affected by your previous iterations and try to make that recursive. In your situation, it looks like balance is that variable:
balance = balance + remaining_balance_recur(annualInterestRate, monthlyPaymentRate, month + 1)
return balance
When you write a recursive method, you always need to return some value at the end of the method, so the statement that called the method actually gets a value. Here's a short, useless example:
def recurse(n)
if n == 0 # BASE CASE
return 1
some_sum = 0
some_sum += recurse(n - 1) # I need the value from recurse(n - 1)
return some_sum # This method was called somewhere, so it needs to return
Try to figure out a recursive solution for your code from these hints. I'm sorry, recursion is very hard to explain especially over SO. Youtube vids and Google would also be a big help to understand recursion in general. Hope this gave you some ideas.
By putting "month = 1" before the while statement, you are resetting it so that while month <= 12 will run forever. This creates a "RecursionError: maximum recursion depth exceeded in comparison."
The output of your function is currently "NoneType" because its output is a print statement rather than returning an int or a float. This produces a "TypeError" because you have tried to add a float (the interest rate) to a NoneType (the printed statement) in your recursion.

How to do the correct casting using a loop in python?

The objective is to write a program that will increase the population every 7 and 35 seconds and decrease every 13 seconds. I am trying to use a loop for this program and I am having some problems with getting the right casting for each variable. Here's the code:
#(1)There is a birth every 7 seconds (2)There is a death every 13 seconds (3)There is a new
immigrant every 35 seconds.
#CURRENT POP: 307,357,870
populationCurrent = input("What is the current population")
x=0
while x!=100:
if (x%7==0):
populationCurrent=populationCurrent+1
x=x+1
elif (x%13==0):
populationCurrent=populationCurrent-1
x=x+1
elif (x%35==0):
populationCurrent+=1
x=x+1
else:
x=x+1
print("The population will be "+int(populationCurrent)+".")
Thank you for your time.
I think you are confused in python2 and python3, there's a difference in input() function of python 2.x and python 3.x, where input() function gives an integer value in python 2 and str in python 3
input() is str by default so, this should be converted to int
populationCurrent = str(input("What is the current population"))
You cannot concatenate string and int
print("The population will be "+str(populationCurrent)+".")
Its easier to do this than iterate through 100 times
populationCurrent += 100//7 + 100//35 - 100//13
You need to convert populationCurrent to an integer immediately after you read the string.
populationCurrent = int(input("What is the current population"))
Note that if you don't enter a string that is a valid integer representation, this will raise a ValueError. You might want to consider how to handle that (catch it and use a default value? catch it and try to read another value? Let the exception propagate?)
With this change, you'll have to convert the integer value back to a string for the output:
print("The population will be "+str(populationCurrent)+".")
or using any of the various string formatting tools available. It's better to have populationCurrent as an integer, since there are more places in your code that assume it to be an integer than assume it to be a string.
The only thing you need to do is convert populationCurrent from string to int:
populationCurrent = int(input("What is the current population?"))
The more concerning stuff is that your code doesn't do what it's supposed to: when x is 35 you will only have one birth, since 35 % 7 is 0, but no immigrant will arrive. Do something like this, removing the elif statements which do not make the code that more efficient anyway:
while x!=100:
if (x%7==0):
populationCurrent=populationCurrent+1
if (x%13==0):
populationCurrent=populationCurrent-1
if (x%35==0):
populationCurrent+=1
x=x+1
print("The population will be ", populationCurrent, ".")
Though still note that the loop will stop after x gets to 100. You could reset it but I don't know for how long you want it to run.
def intInput(prompt):
while 1:
try: return int(input(prompt))
except ValueError: print("Invalid Input!")
def YearToModifier(x):
if x%35 ==0 or x%7 ==0: return 1
if x%13 == 0: return -1
return 0
populationCurrent = intInput("What is the current population?") #ensure you get an int
n_years = intInput("How Many Years?") #ensure you get an int
#in this case populationChange is independent of initial population (this is rarely the case in reality)
populationChange = sum(YearToModifier(x) for x in range(n_years))
#the population in the future is the initialPopulation + population Change ... duh...
populationFuture = populationCurrent + populationChange
print("The Population will be %d!"%populationFuture)
there you go
WRT #martjinpeters comment on OP you could change YearToModifier to
def YearToModifier(x):
return sum([x%35 ==0,x%7 ==0,-1*int(x%13 == 0)])
of coarse as #AshokaLella points out you can calculate the total births/immigrations/deaths for a given number of years without actually visiting each year
births = n_years//7
immigrations = n_years//35
deaths = n_years//13
populationChange = births + immigrations - deaths

Categories

Resources