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()
Related
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
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'm learning to program and I'm using "how to think like an computer scientist" the above question is an exercise
This is the program without a function
fruit = "banana"
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
I want to put that into a function like
def tranversal(fruit):
index = 0
while index < len(fruit):
letter = fruit[index]
return letter
index += 1
print(tranversal("apple"))
However this is only printing the first letter of "apple" and if I use print statement instead of return I will get None.
I'm very confused and need help !!
Seems like you didn't understand the purpose of the return statement inside a function. You might want to read this answer first to make things clear.
Once you understand the difference between print() and return, you should define what your function needs to do. Does it need to return the answer or is printing it on the screen enough?
Assuming the latter, given that strings are iterable, a more pythonic way to do it would be:
def transversal(fruit):
for letter in fruit:
print(letter)
Note that since the function is not explicitly returning a value if you try something like:
foo = transversal("banana")
the variable foo will hold the value None.
If you want your function to return the answer and not print it, you could append each letter to an empty result string, with separators for each new line and after you are done with that, simply return result. It could be a good exercise, so you should give it a try :).
A simple solution:
print(*'banana', sep='\n')
Output:
b
a
n
a
n
a
With help of the star operator * you can split a list or a string into parts and and pass them as multiple arguments to function. So the expression print(*'abc') is equivalent to print('a', 'b', 'c').
If you use print in the function, then you dont need to use print when calling the function.
def tranversal(fruit):
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index += 1
tranversal("apple")
If you use a return statement inside of the while loop, then you will immediately leave the function (and return the first letter), and the while loop will not be executed for higher indices.
You can use this code snippet
def printAllChar(s):
for i in s:
print(i,end='\n')
//calling here...
printAllChar("ProgRank")
//output here...
P
r
o
g
R
a
n
k
For the purpose of understanding i wanted to do that exercise with a function, while loop and get a return value.
I've gotten help and i appreciate everyone, here is my code:
def `tranversal`(fruit):
result = ""
length = int(len(fruit))
index = 0
while index < length:
result += fruit[index]
index += 1
if index == length:
return "\n".join(result)
print(tranversal("string"))
You need to execute the statement using the function outside the function. Just shift return tranversal("apple") outside the function transversal like this:
def transversal(fruit):
index = 0
letters = ''
while index < len(fruit):
letters += fruit[index] + '\n'
index += 1
return letters
print(transversal("apple"))
Thank you #MykolaZotko for pointing out an error in the code that caused it to only print the first letter.
The question is rather academic. I came across the following behaviour in python:
This Code:
def dosth():
print("new")
for n in range(0,10):
return False
dosth()
actually gives me 10 prints instead of one. So does the function recursively call itself after the return statement because there is no break?
If I put in a break before the return statement I still get 2 prints instead of only one.
Can someone explain this behaviour
I only see one new printed.
It also appears that you're a missing a colon : at the end of your loop for n in range(0,10).
def dosth():
print("new")
for n in range(0,10):
return False
dosth()
# prints 'new' once...
I have been attempting to program a calculator using the tkinter module in Python, and I have made 14 functions corresponding to each number and symbol on the calculator. The code below is for the number 1, for example.
The program doesn't return the values as it should, however. I use the values from the previous function in further functions as parameters, but they don't seem to go through and I constantly get result 0.
The variables a and b correspond to two numbers to be used in the calculation and num is a counter for the program to know when to give the number to a and when to give it to b. I have tried inserting a print in this code and a and b was printing correctly but it seems to be a problem with the return.
Any help would be appreciated.
def num1(num,a,b):
if num == 0:
a=a+1
num=num+1
elif num == 1:
b=b+1
return num
return a
return b
Python function only return one value. When you write return a;return b, you only return the first occurrence.
What you need to do , is pack those elements and return them as a tuple:
def num1(num,a,b):
if num == 0:
a=a+1
num=num+1
elif num == 1:
b=b+1
return num, a, b
you need to keep in mind that the first return statement that reaches the work flow causes the end of the current function and returns the value supplied.
the return a; return b lines will never be reached, the execution flow returns to the caller after the first return statement
You can return a list, dictionary,tuple, variable. But a function can't return multiple times. You can try inserting the values in a list and then return the list.