Python Input

From OpenCircuits
Jump to navigation Jump to search

Overview

Input is a general term for how programs get at data that is not internal to the program. These methods range from easy to extremely complicated, try to start with the simplest that suits your needs so you do not get lost in the weeds. This page gives an overview of the territory, it does not teach you how to program all the methods.

Hardcode the Data

This is not a method of input but a simple way to avoid it. Suppose you want to get 2 numbers from the user, add them together and then print the result. In hardcoding you can just put the data in 2 variables and then write the rest of the program. Since it is easy to pull up the file, input into the editor and then run the program this may be good enough for you ( or not ). If you paste this code into spyder you should "outdent" the code to the left margin.


   # take two numbers and print the total
   a_number   = 27.5
   b_number   = 33.75
   #
   total     = a_number + a_number
   print total

Use raw_input

In the following program the user ( perhaps you ) can type their responses in the console. I got this code from: [Exercise 12: Prompting People]


   age = raw_input("How old are you? ")
   height = raw_input("How tall are you? ")
   weight = raw_input("How much do you weigh? ")
   print "So, you're %r old, %r tall and %r heavy." % (
                           age, height, weight)


Input from Files

To be written.

Input from the Web

To be written.

Python has a bunch of special methods and even whole libraries supporting this kind of work.

Input from Sensors

This includes temperature measurement, general weather conditions measurements, touch, images..... You might uses your computers camera, or your computer with an add on peice of hardware. The Raspberry Pi is an especially good way to get into this. The Internet of Things (IO ) usually relies heavily on sensor data.