Receiving return None value - python

I am doing exercise from the book where I am supposed to write program that can take a positive integer greater than 2 and write out the number of times one must repeatedly divide this number by 2 before getting a value less than 2.
def inStr():
n = -1
while n<2:
try:
n = int(input('Enter a positive integer greater than 2: '))
except:
pass
print(positive(n)) # prints None
def positive(n, step=0):
if n < 2:
# print(step) #it prints correct answer
return step #but why it returns None?
positive(n//2, step+1)
inStr()
I don't understand why def positive(n, step=0) returns None?

It seems that you forgot to add return right before positive(n//2, step+1). So your function positive sometimes returns nothing (i.e. None).
Try this:
def inStr():
n = -1
while n<2:
try:
n = int(input('Enter a positive integer greater than 2: '))
except:
pass
print(positive(n)) # prints None
def positive(n, step=0):
if n < 2:
# print(step) #it prints correct answer
return step #but why it returns None?
return positive(n//2, step+1)
inStr()

Because you don't tell it to return anything else. You need to put return in there:
def positive(n, step=0):
if n < 2:
# print(step) #it prints correct answer
return step #but why it returns None?
return positive(n//2, step+1)
There may be times when a function calls itself, but doesn' want to return the results. You need to tell Python that this time you want to. Since you didn't tell Python what to return, it returns None by default.

Related

Python Program to Find Factorial of Number Using Recursion

The factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 is 12345*6 = 720. Factorial is not defined for negative numbers and the factorial of zero is one, 0! = 1.
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
I would like help just to know how to read the entries and call the functions
For that purpose you can add the following code below your functions:
# main program
method = {
"IV": add_node,
"IA": add_edge,
"RV": delete_node,
"RA": delete_edge
}
numinputlines = int(input())
for _ in range(numinputlines):
instruction, *rest = input().split()
if len(rest) == 3: # There is a cost:
rest[-1] = int(rest[-1])
method[instruction](*rest)
The method dictionary helps to translate a 2-letter code to a method that needs to be called. As the arguments to those methods are all in the same order, you can just capture those in a list rest, and "unpack" that list when passing the arguments. There is just one special thing to take care of. Two methods get a cost argument, and it must be of number type. Since input is read as string, you need to convert that cost string to a number. The if statement takes care of this case.
This should answer your question, but it does not finish the exercise. You will still have to debug your code. For instance, currently your code will raise an exception on the example input you have given -- vertex "B" is referenced in IA B A 1 before it is added with IV B.
Also, you'll need to add the code to produce the output.
But since your question was about capturing the input and calling the functions, I have left the rest for you to tackle.
How do I calculate a factorial of an integer in Python? Note that the factorial function is defined only for positive integers; therefore, you should also check that n >= 0 and that isinstance(n, int). Otherwise, raise a ValueError or a TypeError respectively.
def factorial(n):
if(not isinstance(n, int) or n < 0):
raise ValueError("Invalid argument")
if (n==1 or n==0):
return 1
else:
return (n * factorial(n - 1))
# Driver Code
num = int(input("Please enter a number"))
print("Factorial : ",factorial(num))

This recursive program in python giving me an error

def fact(number=input("Enter a value:")):
if number==1:
return 1
else:
return number*fact(number-1)
res=fact()
print(res)
It is generally bad to initialize parameter variables with functions that don't return constants (like input). In addition, input returns a string, not an integer so it needs to be converted. I recommend you change it like this:
def fact(number):
if number <= 1:
return 1
else:
return number*fact(number-1)
number = int(input("Enter a value:"))
res = fact(number)
print(res)
Try converting input to integer. By default, it is taking as string.
def fact(number=int(input("Enter a value:"))):
if number==1:
return 1
else:
return number*fact(number-1)
res=fact()
print(res)

Can't figure out how to make my funtion not return None in Python

I have a program I am trying to make which will either show all the factors of a number or say it is prime. It's a simple program but I have one main issue. Once it prints all of the factors of an inputted number, it always returns none. I have tried multiple ways to get rid of it but nothing works without screwing something else up. The code is below.
def mys(x):
x = input("Enter a number: ")
for i in range(2,x):
r = x % i
if r == 0:
print(i)
print(mys(x))
That code is just for printing the factors but that is where the problem lies. The results I get after entering a number, in this case 20, are as follows:
2
4
5
10
None
No matter what I do, I can't get the None to not print.
So if you don't want the return value of mys (None) not printed, then don't print it:
mys(x)
In python, a function that has no return statement always returns None.
I guess what you are trying to do is calling the mys function, and not printing it.
Note that you should remove x parameter, because it is asked inside of the function.
def mys():
x = input("Enter a number: ")
for i in range(2,x):
r = x % i
if r == 0:
print(i)
mys()
It would be better not to include user input and printing in your function. It would make it easier to test and to reuse:
def mys(x):
result = []
for i in range(2,x):
r = x % i
if r == 0:
result.append(i)
return result
x = input("Enter a number: ")
print(mys(x))

Python can't print the word from the given condition

I have this program:
def validateNumber(number):
if (count > 10) :
print('Invalid number')
return -1
elif (count < 10):
print('Invalid number')
return -1
while True:
count = 0
num = int(input('Number:'))
while num > 0:
num = num//10
count = count+1
if (count == 10) :
break
But I can't print the print('Invalid number') and it turn out to be like this:
Number:122344
Number:123442
Number:1234567890
>>>
I want it to print the print('Invalid number') when the number is less or more than 10.
Number:122344
Invalid number
Number:123442088080989098
Invalid number
Number:1234567890
>>>
Help please. Thanks
The return -1 is for if the number is missing or invalid
Firstly, you could condense your if check to one statement. Note that the easiest way to count the number of digits is to convert it to a string and check its length.
def validateNumber(number):
if len(str(number)) != 10:
return -1
Unfortunately, you do not return a legitimate value if the number is valid. Why not return a boolean value instead?
def validateNumber(number):
if len(str(number)):
return True
return False
You can further reduce this to:
def validateNumber(number):
return len(str(number)) == 10
Note that all the validation logic has now been moved to the function. You'll see how this simplifies the loop code.
Next, you have defined two loops. When you break from the inner, the outer will continue, so you come back to the inner, thus restarting the process.
As a fix, I'd recommend doing this with one loop only, like this:
while True:
x = int(input('...'))
if validateNumber(x):
break
else:
print('Invalid Number')
Since validateNumber returns a bool result, simply have the if query the return value, and break if the number is valid, otherwise the loop repeats.
The good thing about having all your validation code inside the function is that you don't have to modify your loop code if your validation logic changes.

calling the function, checking for palindromes in a range

I'm trying to make a function, which recursively checks for palindromes in a given range. The range is sent to "is_palindrome_multi", which then calls "is_palindrome".
However, it doesn't work with numbers higher then 10, so the limiting step seems to be:
elif data[0]==data[-1]:
statement. Why it doesn't return true for the numbers like 11, 22 and so on? I will be grateful for explanation.
def is_palindorme_multi(beg, end):
for i in range(beg, end):
i = str(i)
if is_palindrome(i) == True:
print "Palindrome"
else:
print "Not palindrome"
def is_palindrome(data):
print data,
if len(data)==1 or len(data)==0:
return True
elif data[0]==data[-1]:
is_palindrome(data[1:-1])
else:
return False
You are not returning the result of the recursive call.
Change your elif:
elif data[0]==data[-1]:
is_palindrome(data[1:-1])
to:
elif data[0]==data[-1]:
return is_palindrome(data[1:-1])
However, I would simply change your is_palindrome method to:
def is_palindrome(data):
return data == data[::-1]
Really, no need to use recursion here.

Categories