Python: Capturing and Formatting User Input

Glenn Norman
  1. Introduction to Python
  2. Python: Choosing a Text Editor or IDE
  3. Python: Hello World
  4. Python: Variables, Strings and Numbers
  5. Python: Variable Naming
  6. Python: Math, Familiar
  7. Python: Math, Less Familiar
  8. Python: Mathematical Order of Operations
  9. Python: Introducing PEP 8
  10. Python: Text Concatenation
  11. Python: if Statements and Comparison Operators
  12. Python: else and elif statements
  13. Python: Testing Multiple Conditions
  14. Python: Testing Sets of Conditions
  15. Python: Nested if Statements
  16. Python: Lists
  17. Python: Adding To and Changing Lists
  18. Python: Lists: Take a Slice, Delete Elements, Popping Elements
  19. Python: Tuples
  20. Python: for Loops
  21. Python: Nested for Loops
  22. Python: Capturing and Formatting User Input
  23. Python: Dictionaries
  24. Python: Functions
  25. Python: While Loops
  26. Python: Creating and Using Classes
  27. Python: Data Files
  28. Python: Modules
  29. Python: CSV Files
  30. Python: JSON Files
  31. Python: Errors and Exception Handling
  32. Python: Using Pexpect
  33. Python : Using Pexpect : ftpTestOffload.sh
  34. Python : Using Pexpect: ftpTest.py
  35. Python: DCL Conversion to Python

Go to Chapter 23 in A Smarter Way.

You can ask for user input and put it into a variable in one line:

user_age = input("Enter your age: ")
print(user_age)

Anything the user enters will be treated as a string. Sometimes that’s a problem, since you may need to do math with their input.

age_integer = int(user_age)

To convert the string to a decimal value (a float):

age_float = float(user_age)

If you  need to convert a number back into a string:

age_float = str(age_float)

Exercises

See http://www.asmarterwaytolearn.com/python/23.html

See http://introtopython.org/while_input.html#Accepting-user-input

  1. Create a new code block in your examples.py file.
  2. Request the user’s name and age (in other words make two requests).
  3. Format the inputs properly to print them in a line that contains the user’s name followed by their age.