Question:
Write a program which can compute the factorial of a given numbers.
The results should be printed in a comma-separated sequence on a single line.
my code:
numb = input("Please add a number: ")
def numb_f(x):
i = 1
suma = 1
while i < int(numb):
suma = suma * (i+1)
i = i + 1
print(numb_f(numb))
the output is always "None". Don't know why, please advise.
If you don't specify a return value in your function, it will return None by default.
First you should store the calculated values, and then you can print it.
The only way for a python function to return a value different from None is to use a return statement.
numb = input("Please add a number: ")
def numb_f(x):
i = 1
suma = 1
while i < int(numb):
suma = suma * (i+1)
i = i + 1
return suma
print(numb_f(numb))
Now it works fine.
I also decided to add condition that checks whether input is a number:
numb = input("Please add a number: ")
if type(numb) == int:
def numb_f(x):
i = 1
suma = 1
while i < int(numb):
suma = suma * (i+1)
i = i + 1
return suma
print(numb_f(numb))
else:
print("Please add number!")
but this time it prints else statemenet all the time. What did I do wrong?
I made a modification, placed a function out of if/else statemenet but still receive the same outcome.
numb = input("Please add a number: ")
def numb_f(x):
i = 1
suma = 1
while i < int(numb):
suma = suma * (i+1)
i = i + 1
return suma
if type(numb) == int:
print(numb_f(numb))
else:
print("Please add number!")
You haven't defined numb as an integer yet. Which begs the question why are you asking for a string instead of an integer to begin with?
numb = int(input("Please add a number: "))
Thank you. It didn't come to my mind that it's possible to define input as integer.
It's not a definition, it's a type conversion. Input is always a string. Using the function int, tries to convert the string into a integer. If the content of the string is not a valid integer, you'll get a ValueError.