NoneType from API? - python

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

Related

Using regex to filter the timestamp out of message logs?

im new to learning python just so you guys know. Im trying to make a function that uses regex to filter out the timestamp from a message log. Im trying to get my test cases to work but im getting an assertion error.
def get_hr_min(row):
time_match = re.search(r'(\d{2}):(\d{2})', row)
hour = time_match.group(1)
minute = time_match.group(2)
dhour = {}
dhour['hour'] = hour
dmin = {}
dmin['minute'] = minute
return dhour, dmin
here is what I have so far. as far as I can tell the function should return the minutes and hours in dictionary format(but I may have formatted it wrong as my professor did not tell me what a dictionary actually is)
log_open_row = '--- Log opened Tue Sep 20 00:01:49 2016'
join_quit_row = '00:01 -!- Guest40341 [AndChat2541#AN-pl0gl1.8e2d.64f9.r226rd.IP] has quit [Quit: Bye]'
message_row = '00:25 < ice231> anyone good with exploiting cisco asa with extrabacon?'
#assert get_hr_min(log_open_row) == {}
assert get_hr_min(join_quit_row) == {'hour': 0, 'minute': 1}
assert get_hr_min(message_row) == {'hour': 0, 'minute': 25}
here are my test cases. I get an assertion error when I run these test cases. I need to make an if statement to filter out the first assertion but I wanted to get the dictionary to work first(im assuming that is where my mistake is?). Any help or tips are appreciated.
A few problems with your code.
First of all, the functino you have there returns a set of dictionaries, rather than one dictionary. This means the value given is effectively a dictionary of dictionaries rather than a single dictionary. Second problem is that you are trying to compare and integer to a string in your assertion. Despite the fact that regex tells you that '01' is a number, its not. '01' is a string. To fix this, turn it into a number using int().
Here is the code fixed up:
def get_hr_min(row):
time_match = re.search(r'(\d{2}):(\d{2})', row)
hour = time_match.group(1)
minute = time_match.group(2)
rvalue = {} # return value
rvalue['hour'] = int(hour) #give the hour as an integer to the "hour" value of rvalue
rvalue['minute'] = int(minute) #give the minute as an integer to the "minute" value of rvalue
return rvalue # return the dictionary, as one complete dictinary rather than a set.

Why I am receiving a runtime error in Codechef?

I am getting runtime error(NZEC) on Codechef. Can anyone tell me why?
withdrwal = int(input())
balance = float(input())
amt = balance - withdrwal- 0.5
if (withdrwal%5!=0 or withdrwal+0.5>balance):
print('%.2f'%balance)
else:
print('%.2f'%amt)
It's because for the specific sum that you are solving, the inputs are probably given in the same line. ie.
20 50
Your code expects inputs one after the other:
20
50
Try changing the input format in your code something like this:
withdrawal, balance = map(float, input().split())
Most probably you're trying to read input when there is no more input left to read and python raises an exception, the online judge in return gives the (NZEC) error. Try using raw_input() instead of input(). Comment back to let me know if it worked.

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

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

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.

simple python program help!

This program is supposed to calculate the number of degrees below 60 on a given day then create a running sum of degrees. count equals the sum of degrees below 60. However, when I run it I get this error:
cool = 60 - temp
TypeError: unsupported operand type(s) for -: 'int' and 'str'
Any ideas on why it's doing this? Thanks!
def cold_days():
temp = eval(input("What is the temperature? "))
count = 0
if temp < 60:
while temp !="quit":
temp = eval(input("What is the temperature? "))
cool = 60 - temp
count = count + heat
print(count)
else:
print("you have no cold days")
You need to turn temp into an int:
...
try:
temp = int(temp)
except TypeError:
# Handle invalid integer
print("%s is not a valid integer." % temp)
sys.exit(1)
...
In Python 3, the input() function always returns a string (this is different from Python 2, and could be the source of the confusion since the Python tutorial you're using might be unaware of Python 3). Since Python is strongly (but dynamically) typed, you can't perform arithmetic calculations using a string and an integer, as your error message shows. You must first convert the temp string into an integer using int():
temp = int(temp)
If temp does not contain something that can be converted to an integer, you will get a ValueError exception. By default, an exception will terminate your program with an informative error message. To handle the exception and take alternative action, your Python tutorial should have a whole chapter on that.
You can just drop the 'eval' since input does return the correct type. Or typecast the temp to int:
temp = int(temp)
I think you need to rethink how you are reading in data. input() returns eval() of whatever text the user types in, so I would expect an error when the user types "quit".
Instead, I suggest using raw_input() which returns text. Then check if it is equal to "quit" before converting to an int.

Categories

Resources