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)?

3
  • You will need a parser that understands such input. What inputs do you want to accept? Commented May 17, 2016 at 6:54
  • you can get your input as a string, and then split it according to your need Commented May 17, 2016 at 6:55
  • If you only want to accept an expression that is the power of two numbers, you can split input on **. Commented May 17, 2016 at 6:58

2 Answers 2

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) 
Sign up to request clarification or add additional context in comments.

2 Comments

Of course. That's how input works. Probably you thought about raw_input()?
Beware that this changed in Python 3.
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).

2 Comments

how insecure, can you explain a bit?
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: nedbatchelder.com/blog/201206/eval_really_is_dangerous.html Hope this helps, friend.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.