Problem with the multiplication table of a number - python

I am trying to write a function that shows me the multiplication table of a number:
def tabellina(n):
for i in range (1,11):
print(n*i)
If I write the function in this way, it works fine.
If I put 4 instead of n, it prints:
4,8,12,16,20,24,28...40
But if I use return instead of print, it does not work anymore, and it just returns me the n value.
I have to use the return and I can’t use the print
What should I do? (I MUST use return NOT print)

The reason it returns the n value if you use return is because the loop doesn't run fully. When you use return, it returns the value, which exits the function. The rest of the loop never executes.
What you want instead is to return an array. The easiest way is probably a list comprehension:
def tabellina(n):
return [n*i for i in range(11)]

you could save the output in a string and then return that. for example:
def tabellina(n):
table = ''
for i in range (1,11):
table += ((n*i) + ' ')
return table
you could replace ' ' with any devider (like ',') as you want.

Try the following script:
def tabellina(n):
joint = ""
for i in range (1,11):
joint = joint + (" %s" % n*i)
return joint

Related

How to recursively append to an empty list?

I'm new to recursion and finding it pretty difficult to grasp. I can't figure out how to append an empty array if I can't directly "touch" it. If its a string I would add the value each time. If it was a number that involved multiplication, I could multiply it each time, but with an array, I don't know what to do.
I dont know how to append to an empty array without being able to directly "touch" it.
This is what I've done so far:
def laugh(num):
if num == 0:
return []
# This doesnt work since we can't append a function call. I'm unsure what to do.
return laugh(num - 1).append("ha ")
print(laugh(3)) -> ["ha, ha, ha"]
If could do this easily if i could just return a string of "Ha"'s instead. I could return an empty string and just add a "Ha" for each step.
You can modify it like:
def laugh(num):
if num == 0:
return []
haha = laugh(num-1)
haha.append("ha")
return haha
Since append does not return the modified list, you have to do it in two steps. Using concatenation and the ternary operator, you can shrink this to:
def laugh(num):
return laugh(num-1) + ["ha"] if num else []
In this case you are mutating the list by calling append on it. What you want to do is return a new list:
def laugh(num):
# base case
if num == 0:
return []
# recursive case
return ["ha"] + laugh(num-1)

Issues with multiplication table output

I'm trying to print out the multiplication table and my function prints out one row at a time.
It works fine alone, but when I run multitable(n) through a for loop, it prints out "None" at the end of each row.
Why is this happening and how do I get rid of it?
def multitable(n):
for num in range (1,12+1):
print(num*n,end = " ")
#multitable(1)
#multitable(2)
for n in range (1,12+1):
print(multitable(n))
Replace this:
print(multitable(n))
with this:
multitable(n)
Your program is printing None because that's the value that multitable() is returning. If you don't want to see it, all you have to do is to avoid printing it.
mutlitable(n) does not return anything and thus returns None, which you then print. Seperate the statements.
def multitable(n):
for num in range (1,12+1):
print(num*n,end = " ")
#multitable(1)
#multitable(2)
for n in range (1,12+1):
multitable(n)
print()
It's the return value of the function, which you print out. If there is no return statement
https://docs.python.org/3/reference/simple_stmts.html#return
Like the accepted answer multitable(n) will do the needful, otherwise return the function
for n in range (1,4):
multitable(n)
print()

Calculating a factorial using loops in Python3

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.

writing a function that return the reversed number

I am trying to write a Python function that get a number as input and returns its reversed number as output. for example: 1234 returns 4321.
this is what I try, but it return only ''
def reverse(num):
L=[]
x=str(num)
L1=list(x)
for i in L1:
L.insert(0,i)
print 'the reversed num is:'
x=''
for i in L:
x.join(i)
return x
any ideas?
def reverse(num):
return str(num)[::-1]
or one line:
lambda x: str(x)[::-1]
Well, the easy solution is this one:
>>> int(str(1234)[::-1])
4321
Your code can be fixed by changing the part
for i in L:
x.join(i)
return x
to
for i in L:
x += i
return x
Alternatively, just replace that section by
return ''.join(L)
What was wrong with your code? Because of wrong indentation, you returned in the first iteration of the for loop. You never assigned a name to x.join(i) so the return value was lost. What you expected join to do I do not know.
First, there is an easier way by converting to string, slicing the string and converting it back to a number.
def reverse(num):
return int(str(num)[::-1])
Second, there are multiple errors in your code:
1) your return statement is in the loop, so it will return after the first iteration;
2) x does not change because x.join() creates a new string and does not modify the string x (which is immutable by the way)
3) no need to convert the string into a list since you can directly iterate over the string (for i in x: ...)
4) join() takes an iterator as an argument. No need for the second loop: return ''.join(L)
thank you all for the helpful ideas.
here is my solution:
def reverse(n):
reverse=0
while(n>0):
dig=n%10
reverse=reverse*10
reverse=reverse+dig
n=n/10
return reverse
def reverse(num)
return str(num)[::-1]
Reverse a string in Python
Other users already gave good answers. Here is a different one, for study purposes.
num = 1234
print "".join(reversed(str(num)))
# 4321
You can convert to int afterwards.

returning a list in a single line in python

I'm just curious if there is a simpler way to do this. If I want to print a list of items on one line I simply write
for i in things:
print i,
but if I substitute print for return I'm obviously only going to get the first item of the list. I needed the list to comma and space separated as well so I ended up with a function that looks like this
def returner(things):
thing = ""
n = 1
for i in things:
thing += i
if n < len(things):
thing += ", "
n += 1
return thing
Was there a better way to do this?
Use join
return ", ".join([str(x) for x in things])
You can use the string join function -
",".join(things)
I think you are confusing identity with representation
def returner(things): #misnomer since this is actually a generator
for itm in things:
yield itm
print ", ".join(map(str,returner(a_list)))

Categories

Resources