0

So I was doing some really basic programming because I'm very new, and I wanted to do user inputs from the console to define variables. I though the input() function would do it, but I think it's taking what I put in as a string instead.

I stripped down all the code to a really basic program that just multiplies the given number. I've tried putting in raw_input(), but my online compiler doesn't like that. NameError: name 'raw_input' is not defined

n = input("Number:")
print(n*2)

Instead all it does it print the number twice, (5 would be 55, 2 would be 22 etc.)

Zack Tarr
  • 851
  • 1
  • 8
  • 28
  • 4
    `input` in `python3` return `str`. So if you tried to do `'x' * 2` you will get `xx` :). Note: there is not `raw_input` in `python3` – han solo Mar 26 '19 at 13:14

2 Answers2

1

You could do something like this:

n = input("Number:")
if(n.isdigit()):
    n=int(n)
    print(n*2)
else:
    print("N is not a digit")

This will ensure if the input is not a digit, you do not try to convert it to a int.

If you would like to check if n is a float() meaning n.n then you should check out this question on Checking if a string can be converted to float in Python. Then you can replace int(n) with float(n) in the if statement above.

Zack Tarr
  • 851
  • 1
  • 8
  • 28
1

Convert n to an integer first.

n = input("Number:")
m = int(n)
print(m*2)

or just

n = input("Number:")
print(int(n)*2)

Note that this will fail with a ValueError if you type alphabetical characters for your input. A simple way to catch this would be to put the int conversion (you can do a float conversion the same way if you prefer) between a try-except block as follows:

n = input("Number:")
try:
    print(int(n)*2)
except(ValueError):
    print("Please enter digits only.")
mttpgn
  • 327
  • 6
  • 17