0

I have this line in my programme-

num = int(input("Enter a number: "))

Now as the input type is int, I cannot use any exponents. How can I change the data input type from int to something else so that I can input exponents like 2**4 (= 2^4)?

Soham
  • 167
  • 1
  • 2
  • 13
  • You will need a parser that understands such input. What inputs do you want to accept? –  May 17 '16 at 06:54
  • you can get your input as a string, and then split it according to your need – Hassan Mehmood May 17 '16 at 06:55
  • If you only want to accept an expression that is the power of two numbers, you can split input on `**`. –  May 17 '16 at 06:58

2 Answers2

4

Don't use int() :)

>>> x = input("Enter a number:")
Enter a number:2**3
>>> print x
8

It can be explained by the documentation (https://docs.python.org/2/library/functions.html#input):

input([prompt]) 

Equivalent to eval(raw_input(prompt)).

This function does not catch user errors. If the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation.

...

Consider using the raw_input() function for general input from users.

In python3 things a bit changed, so the following alternative will work:

x = eval(input("Enter a value"))
print(x) 
Vadim Key
  • 1,242
  • 6
  • 15
0

You could always accept a string and then split in on a delimiter of your choice, either ^ or **.

If I'm not mistaken, eval is insecure and should not be used (please correct me if I'm wrong).

Maorg
  • 83
  • 8
  • how insecure, can you explain a bit? – Hassan Mehmood May 17 '16 at 07:19
  • consider what will happen on you eval os.system("rm -rf /") . If you'd like to get more information on the matter, please go to: http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html Hope this helps, friend. – Maorg May 17 '16 at 07:45