How to Input a Command for a Number in Python

Python is a free, object-oriented programming language you can use to create dynamic applications. When programming in Python, you may need to ask users for their input to a question, such as their age for example. In Python, you prompt a user for a numeric value using the raw_input function.

Instructions

    • 1

      Open your Python editor.

    • 2

      Set a variable to prompt the user for a number. For example, type:

      var = raw_input ("Please enter a number: ")

      The "raw_input" function saves the value as a string.

    • 3

      Change the string variable to a numeric value. To convert the string to an integer, type:

      int(var)

      To convert the string to a floating point decimal, type:

      float(var)

    • 4

      Print the user's response by typing:

      print "You entered ", var

    • 5

      Save your program.

      In the example above, Python first prompts the user "Please enter a number: ". The program waits for the user to enter data. Then, Python converts the number from a string into either an integer or a floating point decimal. Finally, Python prints "You entered " and prints the number to the screen.

Tips & Warnings

  • For user-inputted data, always use the raw_input function instead of "input". "Raw_input" saves the user's data as a string. "Input" allows the user to enter any type of data and even call an executable file or perform a database query. For security purposes, use "raw_input" to limit access to your system.

Related Searches:

References

Comments

Related Ads

Featured