[ LiB ] | ![]() ![]() |
There are two simple functions in Python for getting keyboard input from the user: raw_input and input. The raw_input function is the easier to use of the two. It takes one argument and waits at a normal keyboard prompt for a user to type something. Whatever is typed is then returned as a string:
X = raw_input( "Enter your name: " ) print X
input works just like raw_input except that it is preferable to use with numbers because Python interprets the variables as whatever is typed in, instead of converting any numbers into strings.
X=input("Enter a Number: ") print X
input will think that everything that has been entered is some sort of number, so if you enter in a string by using input, Python will conclude that the string represents a number.
Let's try input with something a bit more complexa bit of code that calculates the area of a rectangle. To do so, you simply need two input lines and then a print statement that displays the results:
# This program calculates the area of a rectangle print "Rectangle_Program_1" length = input("Please put in the length of the rectangle:") width = input("Please put in the width of the rectangle:") print "Area",length*width
You can find this program, called Rectangle_Program_1, in the Chapter 3 folder on the CD. When you run it, it spits out output similar to you can see in Figure 3.2.
Here is a while loop in action with input:
# This program adds until the user quits a = 1 sum = 0 print "Enter numbers to add:" print "Enter Q to quit." while a != 0: print 'Current Sum:',sum a = input('Number? ') sum = sum + a print 'Total Sum =',sum
This loop takes in numbers from a user and keeps adding them until the user quits with a Q entry. You'll see there is nothing new here; you're just mixing two functions from the chapter together. You can also find this code sample on the CD as Addition_1.py.
[ LiB ] | ![]() ![]() |