-4

How can we store the output of 'type' function in a variable ?

next = raw_input('> ')
type = type(next)

if type == 'int':
   val = int(next)
else:
   print "Type a number!"

Syntax Error at line 4....?

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
Shash Aeon
  • 13
  • 4

1 Answers1

2

There are several ways of doing what you want. Note that defining a type variable to mask the type function is not good practice! (and next either BTW :))

n = raw_input('> ')  # (or input in python 3)

try: 
   val = int(n)
except ValueError:
   print("Type a number!")

or

n = raw_input('> ')  # (or input in python 3)

if n.isdigit():
   val = int(n)
else:
   print("Type a number!")

Note: as some comment indicated, that in python 2, it was possible to get what you wanted by just using

n = input("> ")

but very ill adviced since you have to control what n is really, not python 3 portable, and has huge security issues:

Ex: in python 2 on windows, try that:

import os
n = input("> ")

and type os.system("notepad")

you'll get a nice notepad windows !! You see that it is really not recommended to use input (imagine I type os.system("del <root of your system>")) ...

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219