+ 2

If I provide input using input() it shows syntax error as given below but if I provide this value without input() it works,WHY?

SOURCE CODE: program=input('>') exec(program) > a=5\nb=4\nprint('sum: ',a+b) #input OUTPUT: Syntax error: unexpected character after line continuation character Another method program="a=5\nb=4\nprint('sum: ',a+b)" exec(program) OUTPUT: sum: 9

6th Oct 2020, 5:56 PM
Hemant
Hemant - avatar
1 ответ
+ 5
Using input() function will modify an input like "\n" to "\\n". this causes the problem you have. as far as i know, you can not force to make your input a raw string, but you can create a new string by using the following code below. Your input of: "a=5\nb=4\nprint('sum: ',a+b)" will be stored as: "a=5\\nb=4\\nprint('sum: ',a+b)". program=input(r'>') #program = program.replace("\\n", "\n") exec(program) if you create a varibale like "a=5\nb=4\nprint('sum: ',a+b)", you can run the code without problems.
6th Oct 2020, 7:42 PM
Lothar
Lothar - avatar