I want to write this function, but it doesn't work
def less(number):
while number>0:
return less(number-1)
print(less(5))
You have to use if instead of while. See the code:
def less(number):
if number>0:
print(number)
return less(number-1)
less(5)
Related
I am writing a recursive function to calculate the digital root of a given number:
def digital_root(num):
sum = 0
while num > 0:
sum += num % 10
num = num // 10
while sum > 10:
sum = digital_root(sum)
return sum
I am not sure if the second while should be replaced with an if statement, and if so, why? (and if not, why not?)
When I try both of the version, the return value is the same.
For example, for the number 10598, the output in both of them is 5.
Please make sure to accept the answer if it works tired of people not accepting my solutions, when it works for them
def digital_root(num):
#Base case for recursion.
# recursion always needs a base case
if len(str(num)) == 1:
return num
#Get sum of num by turning it into a string and looping through it,
#adding each index one by one
sum = 0
for i in str(num):
sum += int(i)
#get the digital root of the sum
return digital_root(sum)
def main():
print(digital_root(27518))
if __name__ == '__main__':
main()
There you go
So, first, please think what you're asking.
If relates to a condition, and while relates to perform a repeated action as long as a certain condition holds.
The digital root recursion stops only when the resulting digit sum is less than 10.
we need "if" for the base case of recursion.
but in this special case, you are using "while" as "if" and that works. but for readability, it is better to use "if".
the reason that it works:
both "while" and "if" have conditions
and the difference between them is just looping through the instructions
and it will be the same again because of the recursion.
I mean in this special case, due to that we have recursion, "if" acts like "while"
this is another answer for acounting the Digital root of a number using recursion:
def digital_root(n):
if(n < 10):
return n
n=n%10+digital_root(n//10)
return digital_root(n)
I am currently studying Software Development as a beginner and I have a task in my programming class to calculate and display a factorial using a loop. I've been given the pseudo-code and have to translate it into true code and test it in the REPL to make sure it returns the expected results.
I almost have it but I've run into two issues that I just can't seem to resolve.
1) The function is returning an extra line of "None" after the calculation and
2) The answer is displaying over multiple lines when I want it to display on a single line.
My current code (which does return the correct answer) is as follows:
def calcFactorial(number):
factorial = 1
print(str(number)+"! =", number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*number-count
print("x", str(number-count))
factorial = factorial*number
print("=", factorial)
When I test, using 3 for example, the REPL returns the following:
>>> print(calcFactorial(3))
3! = 3
x 2
x 1
= 12
None
So I have the correct answer but with an extra line of "None" which I would like to remove (I believe it has something to do with the print function?) and I don't know how to format it correctly.
Any help would be much appreciated.
your function calcFactorial(3) prints already, so you shouldn't call it with
print(calcFactorial(3))
just call it with
calcFactorial(3)
without the print function.
you might think about calling the function calc_and_print_factorial() in order to make it clear, that this function does already the printing
Regarding your second question:
Blockquote
2) The answer is displaying over multiple lines when I want it to display on a single line.
You can fix it by using a single print statement:
def calcFactorial(number):
factorial = 1
string = str(number) + "! = " + str(number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*(number-count)
string = string + " x " + str(number-count)
factorial = factorial * number
print(string + " = " + str(factorial))
This will give you:
IN: calcFactorial(3)
OUT: 3! = 3 x 2 x 1 = 6
On a side note: you might want to think of how to implement this recursively. Maybe that comes later in your class but this would be one of the first go-to examples for it.
Adding to the blhsing's answer, you should choose between these built-in ways to print the "returned" value.
First way:
def calcFactorial(number):
... # <- Your function content
return factorial
Then, call your function with a print() to get the explicitly returned value, as you can see in the return factorial line. See this reference for more details:
print(calcFactorial(3))
Second way:
Having the same function definition with its return statement, just call the function with its instance statement:
calcFactorial(8)
By default, python will print the returned value without a print()
Third way:
Just call the function (without the explicit return statement, this will return a "None" (null-like) value by default), using the print() method. Do NOT use print() inside another print().
Your calcFactorial function does not explicitly return a value, so it would return None by default, so print(calcFactorial(3)) would always print None.
You should make the calcFactorial function return factorial as a result at the end:
def calcFactorial(number):
factorial = 1
print(str(number)+"! =", number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*number-count
print("x", str(number-count))
factorial = factorial*number
print("=", factorial)
return factorial
So I have the correct answer but with an extra line of "None" which I would like to remove
You are printing the return value from your function. In this case, you haven't specified a return value with a return statement so the function automatically returns None.
To fix the problem, you should return a value from your function. Note that you don't need to call print() for final answer because the REPL already does this for you.
Note that the REPL will automatically print the return value for you, so you can just type calcFactorial(3) instead of print(calcFactorial(3)).
Additionally, you are not getting the correct answer. You should get 6 instead of 12. It looks like you are trying to count down from number and multiplying each number together. You can get the same result by counting up from 1. This will lead to much simpler code and avoid the error.
If you want to understand why your code isn't doing the correct thing, look closely at factorial = factorial*number-count and think about the order of operations that are used to calculate the result here.
I have written a program that reads integers until the user enters a 0, which stores the integers and then returns the sum of integers. But its not displaying the output, what went wrong?
def readList():
n=int(input())
while n!=0:
n=int(input())
return n
def calSum(n):
n=myList
myList = readList()
sum = calSum(myList)
print(sum)
calSum was assigning myList to n, but it was INSIDE the calSum and anything OUTSIDE this def was unable to read it, as it is local variable.
Same thing about n from readList. It's local. So "n" in readList and "n" in calSum does not exist outside those functions and can not be used anywhere else.
You were able to use "n" from readList, only because you used return, which returned this value to the rest of the program. And in the very same way you have to make in in calSum to make it work.
Google for global and local variables in python for more information on topic :)
def readList():
n=int(input("Input from readList"))
while n!=0:
n=int(input("Looped input from readList"))
return n
def calSum(n):
n=myList
return n #Added return as student suggested
myList = readList()
sum = calSum(myList)
print(sum)
This should be what you're looking for
The readList function appends to a list and then returns the list, as apposed to return just the first number as it was doing previously.
The calcSum function uses Python's built-in sum function to calculate the sum of all the integers in the list.
def readList():
myList = []
n=int(input())
while n!=0:
n=int(input())
myList.append(n)
return myList
def calSum(n):
return sum(n)
myList = readList()
sum = calSum(myList)
print(sum)
I am trying to write a code that returns every prime palindrome with three digits. Here is my code:
def digpalprim():
for x in range (100,1000):
if prime(x)=='prime':
if str(x)==str(x)[::1]:
return x
I've already defined the prime(x) function, it works well, that stage just determines whether x is prime or not. All in all the code works, except that it only gives me the first such a palindrome. I don't really understand why, shouldn't the program consider all the numbers between 100 and 1000? Please help?
Your function returns as soon as it finds the first such palindrome; return exits a function.
Collect your finds in a list and return that:
def digpalprim():
palindromes = []
for x in range (100,1000):
if prime(x)=='prime':
if str(x)==str(x)[::1]:
palindromes.append(x)
return palindromes
or you can make your function a generator by replacing the return with a yield statement:
def digpalprim():
for x in range (100,1000):
if prime(x)=='prime':
if str(x)==str(x)[::1]:
yield x
Now you'll have to iterate over this function or use list() to 'pull' all values out:
all_palindromes(digpalprim())
or
for palindrome in digpalprim():
print(palindrome)
You are returning the function the first time you encounter one.
def digpalprim():
palprimes = []
for x in range (100,1000):
if prime(x)=='prime':
if str(x)==str(x)[::1]:
palprimes.append(x)
return palprimes
This creates a list at the start of the function and appends each valid palindrome prime to that list, then returns the entire list (after completing all loops) instead of returning just the first one encountered.
Just remember, if Python hits a return statement, it's going to stop function execution right there and return that value regardless of any additional loops or code you may intend to be executed.
The function returns and ends as soon as the first result is found.
You may wish to add the results to a list and then print out the list.
return x This statement causes the program to return to the calling function once this statement is encountered. To return all you may put it in an list. For e.g:
you can have a list called values and append it to it, and finally return it at the end
For such small tasks, I prefer using list comprehensions:
palindromes = [x for x in range(100, 1000) if (prime(x) == 'prime') and (str(x) == str(x)[::1])]
Or (equivalently):
condition = lambda f: prime(f) == 'prime' and str(f) == str(f)[::1]
palindromes = [x for x in range(100, 1000) if condition(x)]
I'm required to write a function that computes and returns the sum of the digits in an integer.
Here's my code:
def main():
number1=input("Enter a number: ")
number=list(number1)
i=0
while len(number)!=i:
numbers=[]
x=int(number[i])
numbers.append(x)
number.remove(number[i])
print(numbers)
x=float(sum(numbers))
print(x)
main()
The output looks like:
Enter a number: 123
[3]
3.0
I'm not sure why 1 and 2 aren't in the list, and aren't used to compute the sum... any suggestions?
You reinitialize numbers inside the loop. Don't do that, move that outside of the loop instead:
numbers=[]
while len(number)!=i:
# ...
otherwise you end up resetting the list for each and every digit.
It's good for you to learn the basics before you try advanced stuff, but just for fun, here is the way an experienced Python coder would solve this problem:
def main():
number1=input("Enter a number: ") # for Python 2.x, need to use raw_input()
return float(sum(int(ch) for ch in number1))
x = main()
print(x)
We can use the builtin function sum() to sum the digit numbers, and we get the digit numbers with a "generator expression" that loops over the string directly while calling int().
This is just a taste of the fun stuff you will be learning soon in Python. :-)
You can also do it in a more functional way, if you are interested in this kind of programming. It would then look like this:
def main():
number1=input("Enter a number: ") # for Python 2.x, need to use raw_input()
return float(sum(map(int, number1))
x = main()
print(x)