liveBook · Manning

Input()

As explained in The Quick Python Book, Fourth Edition

input() is Python's built-in function for obtaining a line of text from the user through standard input.

input() prompts for and reads one line from standard input, returning the entered text as a string. The prompt is optional and may be any string, including an f-string. section 4.9 section 13.6

Use input() with these practical rules:

  • Pressing Enter terminates the input line, and input() removes the trailing newline. section 13.6
  • Convert numeric text explicitly with int() or float() before using it as a number. section 4.9
  • Expect an exception when the entered text cannot be converted to the requested numeric type. section 13.6
  • Use sys.stdin for lower-level reading such as read(), readline(), and readlines(), especially when redirecting input. section 13.6

Read text and numbers

name = input("Name? ")\nprint(name)\n\nage = int(input("Age? "))\nprint(age)\n\nA text response remains a string; wrapping input() with int() converts numeric text to an integer. Replace int() with float() when decimal input is required.

name = input("Name? ")
 
Name? Jane
 
print(name)
 
Jane
 
age = int(input("Age? "))   #1
 
Age? 28
 
print(age)
 
28
#1 Converts input from a string to an int

View the prompt, entered values, printed results, and the inline conversion annotation in one compact interaction. section 4.9

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains prompts, line termination, string results, numeric conversion, and standard streams, while deferring lower-level access to sys.
Examples
Demonstrates name and age prompts, integer conversion, decimal conversion, invalid input, and reading through sys.stdin.readline().
What you can do after
Apply it via prompts, convert returned text to numeric types, and choose sys.stdin for lower-level or redirected input.
How it connects
Connects input() with int(), float(), standard input/output, sys.stdin, file objects, and input redirection.

Also explained in

Compare how 7 books explain input() →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.