python error need explanations - python

I have this error when running the following program and I don't understand why:
Traceback (most recent call last):
line 18
main() line 13, in main
nombre=condition(nombre)
line 3, in condition
if (nombre % 2) == 1:
TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'
Here is my program:
def condition(nombre):
if (nombre % 2) == 1:
nombre=(nombre*3)+1
else:
nombre=(nombre/2)
def main():
nombre=int(input())
print(nombre)
while nombre!=1:
nombre=condition(nombre)
print(nombre)
main()

This error occurring because you doest returning value from condition function and in second iteration of your while != 1 value of nombre was equal to def. try this to fix your code:
def condition(nombre):
if (nombre % 2) == 1:
nombre=(nombre*3)+1
else:
nombre=(nombre/2)
return nombre
if you want that condition return integer value you should use // instead of / :
def condition(nombre):
if (nombre % 2) == 1:
nombre=(nombre*3)+1
else:
nombre=(nombre//2)
return nombre

You are getting NoneType from condition function since it doesn't return anything.

Related

Python - TypeError not all arguments converted duting string formation

I have a script that will accept a random number from a server and then it will tell me if its even or odd, however when I run it I get an error
TypeError not all arguments converted during string formation
Here is the full error message:
Traceback (most recent call last):
File "client.py", line 18, in
if (RNUM % 2) == 0:
TypeError: not all arguments converted during string formatting
Here is the code:
from socket import *
s=socket(AF_INET, SOCK_STREAM)
s.connect(("localhost",6000))
r=s.recv(1024)
clientname = "Edward"
print("This is " + clientname + "\'s client")
while(True):
a=int(input(r))
if(a >= 1) and (a <=20):
s.send(bytes(str(a), 'utf8'))
rnum=s.recv(1024)
#mat=s.recv(1024)
RNUM=rnum.decode('utf8')
#MAT=mat.decode('utf8')
print("Random Number From Server:",RNUM)
if (RNUM % 2) == 0:
print("{0} is Even number".format(RNUM))
else:
print("{0} is Odd number".format(RNUM))
#print("Random Number + Number given = ", MAT)
else:
print("Invalid Integer, try again")
The variable RNUM is a string. To convert it to an integer, call int(RNUM).

HackerRank Runtime Error in Simple Python 3 if statement

def findNumber(arr, k):
if k in arr:
print( "YES" )
else:
print( "NO" )
if __name__ == '__main__':
arr_count = int(input().strip())
arr = []
for _ in range(arr_count):
arr_item = int(input().strip())
arr.append(arr_item)
k = int(input().strip())
result = findNumber(arr, k)
fptr.write(result + '\n')
fptr.close()
While this runs just fine on Pycharm, on HackerRank i get the error:
Traceback (most recent call last):
File "Solution.py", line 42, in <module>
fptr.write(result + '\n')
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
Would really appreciate if you could point out what the error might be.
Your function def findNumber(arr, k): does not return anything, so it returns None implicitly.
These lines
result = findNumber(arr, k)
fptr.write(result + '\n')
then try to add None and a string together - which does not work.
Instead of printing inside your function, return "Yes" or "No".
findNumber returns Nothing, so it automatically returns None. You have to replace the "print" in your function with return statements.

Why isn't my variable set when I call the other function? [duplicate]

This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
How can I fix a TypeError that says an operator (<, <=, >, >=) is not supported between x and y?
(1 answer)
Closed 25 days ago.
TypeError: '<' not supported between instances of 'NoneType' and 'int'
I have looked for an answer in Stack Overflow and found that I should be taking an int(input(prompt)), but that's what I am doing
def main():
while True:
vPopSize = validinput("Population Size: ")
if vPopSize < 4:
print("Value too small, should be > 3")
continue
else:
break
def validinput(prompt):
while True:
try:
vPopSize = int(input(prompt))
except ValueError:
print("Invalid Entry - try again")
continue
else:
break
This problem also comes up when migrating to Python 3.
In Python 2 comparing an integer to None will "work," such that None is considered less than any integer, even negative ones:
>>> None > 1
False
>>> None < 1
True
In Python 3 such comparisons raise a TypeError:
>>> None > 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'NoneType' and 'int'
>>> None < 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'NoneType' and 'int'
you need to add a return in your function to get the number you input, otherwise it return an implicit None
def validinput(prompt):
while True:
try:
return int(input(prompt))
# there is no need to use another variable here, just return the conversion,
# if it fail it will try again because it is inside this infinite loop
except ValueError:
print("Invalid Entry - try again")
def main():
while True:
vPopSize = validinput("Population Size: ")
if vPopSize < 4:
print("Value too small, should be > 3")
continue
else:
break
or as noted in the comments, make validinput also check if it is an appropriate value
def validinput(prompt):
while True:
try:
value = int(input(prompt))
if value > 3:
return value
else:
print("Value too small, should be > 3")
except ValueError:
print("Invalid Entry - try again")
def main():
vPopSize = validinput("Population Size: ")
# do stuff with vPopSize
Changing None value worked for me np.nan documentation
df_gpa.replace(to_replace=[None], value=np.nan, inplace=True)
code before
def validate(self):
df = self.df['column_name']
print(df)
for i in df:
if i < 0:
raise Exception(f"range is lower than 0.0: {i}")
if i > 150:
raise Exception(f"range is higher than 150: {i}")
code after
def validate(self):
df = self.df['column_name']
df.replace(to_replace=[None], value=np.nan, inplace=True)
print(df)
for i in df:
if i < 0:
raise Exception(f"range is lower than 0.0: {i}")
if i > 150:
raise Exception(f"range is higher than 150: {i}")
Try:
def validinput(prompt):
print(prompt) # this one is new!!
while True:
try:
vPopSize = int(input(prompt))
except ValueError:
print("Invalid Entry - try again")
continue
else:
break
And you will notice when the function is called.
The problem is that validinput() does not return anything. You'd have to return vPopSize
should remove print() from the return of the function, so take the value and print it from outside

Regarding string methods

I'm currently working through Automate the Boring Stuff with Python book and run into curious issue on chapter 7.
When trying to execute the following code:
def isPhoneNumber(text):
if len(text) != 12:
return False
for i in range(0, 3):
if not text[i].isdecimal():
return False
if text[3] != "-":
return False
for i in range(4, 7):
if not text(i).isdecimal():
return False
if text[7] != "-":
return False
for i in range(8, 12):
if not text[i].isdecimal():
return False
return True
print("415-555-4242 is a phone number:")
print(isPhoneNumber("415-555-4242"))
print("Moshi moshi is a phone number:")
print(isPhoneNumber("Moshi moshi"))
I get the following error message:
Traceback (most recent call last):
File "automation.py", line 27, in <module>
print(isPhoneNumber("415-555-4242"))
File "automation.py", line 13, in isPhoneNumber
if not text(i).isdecimal():
TypeError: 'str' object is not callable
Switching the str.isdecimal() method for str.isdigit() method allows me to execute the code properly, but I would like to know why the isdecimal() method will not work?
The error has nothing to do with isdecimal(). You have a typo in how you extract the character from text. The
if not text(i).isdecimal():
should read
if not text[i].isdecimal():
(note the square brackets.)
File "automation.py", line 13, in isPhoneNumber
if not text(i).isdecimal():
TypeError: 'str' object is not callable
The typeError is on line 13, where you are calling a string object. Use [] not ()

Error with calculator type program in python ValueError

this is my script, i am new to python but have come to get this, please be forgiving as such in the answers and keep in mind that i am new to this.
import functools
numbers=[]
def means():
end_mean = functools.reduce(lambda x, y: x + y, numbers) / len(numbers)
print(end_mean)
def sum():
end_sum = functools.reduce(lambda x, y: x + y, numbers)
print(end_sum)
def whatDo():
print('Input Extra Numbers '+str(len(numbers)+1)+' (or nothing to close):')
try:
number= int(input())
numbers.append(number)
except:
print('What do you want to do?')
answer = input()
if answer == "mean":
means()
while True:
print('Input Number '+str(len(numbers)+1)+' (or nothing to close):')
try:
number= int(input())
numbers.append(number)
except:
print('What do you want to do?')
answer = input()
if answer == "mean":
means()
print('Do you want anything else?')
reply=input()
if reply=='no':
break
elif reply--'yes':
whatDo()
else:
break
However i get this:
Traceback (most recent call last):
File "E:/Python/calculator.py", line 26, in <module>
number= int(input())
ValueError: invalid literal for int() with base 10: ''
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "E:/Python/calculator.py", line 37, in <module>
elif reply--'yes':
TypeError: bad operand type for unary -: 'str'
after the 'Do you want anything else' and i enter 'yes'.
elif reply--'yes': should be elif reply == 'yes':
You had a typo
elif reply--'yes'
it should be, of course
elif reply=='yes'

Categories