0
Pls help mee
def factorial(x): if x == 1: return 1 else : return x * factorial(x - 1) op =input("Enter a number: ") print (op) print (("The factorial of ") + (op) + " is ") print (factorial(op)) It errors in line 10 . I need your help
8 Respuestas
+ 3
I see your problem: the result of "input" is ALWAYS a str, so the problem comes when you try to do x-1. It doesn't mean anything with str. Try casting op as an int
+ 2
try removing the brackets other things are not looking like error
print("the factorial of"+op+"is");
+ 1
I am not quite sure about it, but I think your second print() throws the error because it has problems on concatenation because of the (). Remove them and try again.
@Chris I am sorry but you are completely wrong. The concept you are de scribing is called recursion. It is far away of beeing illegal.
+ 1
@AKC Not sure that second print() is error
I need the program to be like this :
Enter a number: 5
The factorial of 5 is 120
or
Enter a number: 6
The factorial of 6 is 720
but the print(factorial(op)) errors , which its say TypeError and refer to the "return x * factorial(x - 1)"
Thanks for the feedback , I appreciate it 😊
+ 1
Write a "" + before your factorial() inside the print
+ 1
@Amaras How ? 😂
Srsly , im not quite understand bout dis int and string thingy , but only the last string wasnt printed
+ 1
simple: you can't use - to manipulate a string in Python. It makes absolutely no sense. It just throws a TypeError: unsupported operands... (I don't remember exactly what it prints)
The problem with your code is that it tries to use factorial with a string: op looks like '3' (for instance) so let's follow the execution.
input: '3'
factorial('3')
'3'!=1
returns '3'*('3'-1)
It is at this point that there is an error: '3'-1 is not a legal operation.
If you can analyse the stack trace, you should see where exactly in your code there is a problem. In that case, line 5 just crashes...
0
@Amaras Thanks for the big help 😁
I forget op is a string , then adding a str and an int is illegal
So I guess I made the op as an int 😂
Check it out 😂