Foundations of Python

You are currently auditing this course.
67 / 134

Input from User

If you want to take the value for a variable from the user via their keyboard, Python provides a built-in function called input that gets input from the keyboard. When this function is called, the program stops and waits for the user to type something. When the user presses Return or Enter, the program resumes and input returns what the user typed as a string.

inp = input()

It is a good thing to display to the user to enter what you want before taking the input.

 name = input('What is Cloudxlab?\n')

The sequence \n at the end of the prompt represents a newline, which is a special character that causes a line break. That's why the user's input appears below the prompt.

If you expect the user to type an integer, you can try to convert the return value to int using the int() function:

question = 'What is 2 multiplied by 3?\n'
answer = input(question)
print(int(answer))

It takes the answer from the user and prints it after converting it into int. Try it in the notebook.

Input something other than a string of digits and observe the error that you get. (We will learn how to handle this kind of error later.)

INSTRUCTIONS
  • Define a function with name input_name that displays a prompt, "What am I studying?"
  • Then, within the function take an input from the user and return it.
  • In a new cell, call the function, input Python after the prompt.
  • Store the returned value in the variable subject.
  • Print subject.

Loading comments...