PYTHON
  • PYTHON v3
  • Python IDE Setup
  • Python Programming
    • Python for ABS
      • Resources
      • Ch1 - Getting Started
      • Ch2 - Types, Variables and Simple I/O
  • Python For Network Engineers-Kirk Beyers
    • Resources
    • Python Fundamentals
  • Python Inststitute (PCAP)
    • Resources
    • Course Introduction
    • Python Essentials (Part 1)
      • Module 1
        • Fundamentals
        • What is Python
        • Starting your work with Python
      • Module 2
        • The Print Function
          • Section Summary
        • Literals
          • Section Summary
        • Operations- Data Manipulation Tools
          • Section Summary
        • Variables
          • Leaving Comments in Code
          • The input () Function
  • 100 Days Of Code
    • Resources
    • What You Have To Do !!
    • 100 DAY's
      • DAY 1: Working with Variables
      • Day 2: Data Types & String Manipulation
      • Day 3: Control Flow and Operators
      • Day 4: Randomisation and Lists
      • Day 5: For Loops, Range & Code Blocks
      • Day 6: Python Functions and Karel
      • Day 7: Hangman
      • SUMMARY
  • {Pirple}
    • Resources
Powered by GitBook
On this page

Was this helpful?

  1. Python Inststitute (PCAP)
  2. Python Essentials (Part 1)
  3. Module 2
  4. Variables

The input () Function

To get input from the user in Python, you can use the intuitively named input function. For example, a game can ask for the user's name and age as input and use them in the game. The input function prompts the user for input, and returns what they enter as a string (with the contents automatically escaped). Even if the user enters a number as input, it is processed as a string.

print("Tell me anything...") anything = input() print("Hmm...", anything, "... Really?")

The input statement needs to be followed by parentheses. You can provide a string to input() between the parentheses, producing a prompt message. For example 1:

name = input("Enter your name: ") print("Hello, " + name)

Let's assume we want to take the age of the user as input.We know that the input() function returns a string. To convert it to a number, we can use the int or float () function: For example 2:

#Testing TypeError message anything = input("Enter a number: ") something = anything ** 2.0 print(anything, "to the power of 2 is", something) --------------- Traceback (most recent call last): File ".main.py", line 4, in <module> something = anything ** 2.0 TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'float'

The problem here is that we tried to square a string value accompanied by a float - not going to work #Testing TypeError message anything = float(input("Enter a number: ")) something = anything ** 2.0 print(anything, "to the power of 2 is", something) ------------------ Enter a number 4 4.0 to the power of 2 is 16

PreviousLeaving Comments in CodeNextResources

Last updated 4 years ago

Was this helpful?