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

29th Dec 2016, 6:25 AM
Abraham Wong
Abraham Wong - avatar
8 Antworten
+ 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
30th Dec 2016, 5:51 AM
Amaras A
Amaras A - avatar
+ 2
try removing the brackets other things are not looking like error print("the factorial of"+op+"is");
29th Dec 2016, 11:42 AM
Sandeep Chatterjee
+ 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.
29th Dec 2016, 8:02 AM
Andreas K
Andreas K - avatar
+ 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 😊
29th Dec 2016, 10:00 AM
Abraham Wong
Abraham Wong - avatar
+ 1
Write a "" + before your factorial() inside the print
29th Dec 2016, 10:15 AM
Andreas K
Andreas K - avatar
+ 1
@Amaras How ? 😂 Srsly , im not quite understand bout dis int and string thingy , but only the last string wasnt printed
31st Dec 2016, 2:14 PM
Abraham Wong
Abraham Wong - avatar
+ 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...
2nd Jan 2017, 3:48 AM
Amaras A
Amaras A - avatar
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 😂
3rd Jan 2017, 10:47 AM
Abraham Wong
Abraham Wong - avatar