Fundamentals » User Interaction »


User Interaction

Functions and Methods Table Of Contents Strings

User interaction is very common in Python programs. We typically display information to the user in the terminal and extract data from the user via the keyboard. As in Java, the terminal represents standard output and the keyboard standard input.

Standard Input

Java version 1.5 introduced the Scanner class for extracting data from standard input. It provided a number of methods for extracting different types of data. Consider the following Java code segment for extracting a string from the user

// Java example
Scanner keyboard = new Scanner( );
System.out.println( "What is your name? " );
String name =;

In python, there is a single function for extracting data from the user. The following Python code segment is equivalent to that shown above

print "What is your name? "
name = raw_input()

The raw_input() function waits for the user to enter a line of data at the keyboard, terminated with a carriage return. The data entered by the user is then returned as a string. In this example, if the user enters Smith at the keyboard, name will refer to the string "Smith".

User Prompts

When extracting data from the user, we typically prompt the user with a message indicating what should be entered. Since this is so common, Python allows an argument to be passed to the raw_input() function to be used as a prompt. We can rewrite the previous example as

name = raw_input( "What is your name? " )

When executed, the Python interpreter will display the string on a new line and then wait for the user to enter the data.

Numeric Values

The raw_input() function can only extract strings. But what if we need to extract an integer or real value? In that case, the numeric value will be stored as a string of digits and we must convert it to a numeric value using the appropriate type conversion function. In the following example, we extract a floating-point value from the user by passing the input string to the float constructor which converts the numeric string representation to a real value

userInput = raw_input( "What is your gpa? " )
gpa = float( userInput )

The corresponding Java code would be

// Java sample
System.out.print( "What is your gpa? " );
double gpa = keyboard.nextDouble();

If the user enters 3.92 at the prompt, variable userInput will contain the string value "3.92".

Using the float() constructor, Python will convert that string representation to the numeric value 3.92 which is then stored in variable gpa

The code segment above can be written as a single statement by nesting the two function calls

gpa = float( raw_input( "What is your gpa? " ) )

Standard Output

In Python, as you have seen in a number of examples, the print statement is used to display information to the terminal. Note that print is a statement in Python and not a function which means the use of () around the argument list is optional.

The print statement can be used to display values of any of the primitive types. Internally, Python handles the translation from the primitive type to a string in order for the value to be printed.

avg = grade / 3.0
print avg

To display or print multiple values, you can use multiple print statements or separate each value with a comma. In the latter case, Python will display the values separated with spaces.

print "Your average grade = ", avg

You can not concatenate non-string values with strings as can be done in Java.

The default behavior of the print statement is to produce a linefeed after the value(s) are printed. Thus, two successive print statements will produce two lines of text. For example,

print "Your average grade = ", avg

would produce the following output assuming avg contains a value of 85.2

Your average grade = 85.2

You can suppress the linefeed by ending the print statement with a comma

print "GRADE REPORT!",
print "Your average grade = ", avg

In this case, the results are printed all on one line since the first print statement ends with a comma

GRADE REPORT!Your average grade = 85.2

Example Program

A sample program is provided which illustrates user interaction. Data is extracted from the user and then used to compute an employee’s take home pay. First, consider the Java version of the program

 * Computes the taxes and wages for an employee given the
 * number of hours worked and their pay rate.

import java.util.*;

public class Wages {
   public static void main( String[] args ) {
      // Set tax rates as constants.
      final double STATE_TAX_RATE = 0.035;
      final double FED_TAX_RATE = 0.15;

      double hours, payRate;
      double wages, stateTaxes, fedTaxes, takeHome;
      String employee;
      Scanner keyboard = new Scanner( );
      // Extract data from the user.
      System.out.print( "Employee name: " );
      employee =;
      System.out.print( "Hours worked: " );
      hours = keyboard.nextDouble();
      System.out.print( "Pay rate: " );
      payRate = keyboard.nextDouble();

      // Compute the employee's taxes and wages.
      wages = hours * payRate;
      stateTaxes = wages * STATE_TAX_RATE;
      fedTaxes = wages * FED_TAX_RATE;
      takeHome = wages - stateTaxes - fedTaxes;

      // Print the results.
      System.out.println( "PAY REPORT" );
      System.out.println( "Employee: " + employee );
      System.out.println( "----------------------------------" );
      System.out.println( "Wages:       " + wages );
      System.out.println( "State Taxes: " + stateTaxes );
      System.out.println( "Fed Taxes:   " + fedTaxes );
      System.out.println( "Pay:         " + takeHome );

and compare it to the equivalent Python version

# Computes the taxes and wages for an employee given the
# number of hours worked and their pay rate.

# Set tax rates as constants.

# Extract data from the user.
employee = raw_input( "Employee name: " )
hours = float( raw_input( "Hours worked: " ) )
payRate = float( raw_input( "Pay rate: " ) )

# Compute the employee's taxes and wages.
wages = hours * payRate
stateTaxes = wages * STATE_TAX_RATE
fedTaxes = wages * FED_TAX_RATE
takeHome = wages - stateTaxes - fedTaxes

# Print the results.
print "PAY REPORT"
print "Employee: ", employee
print "----------------------------------"
print "Wages:       ", wages
print "State Taxes: ", stateTaxes
print "Fed Taxes:   ", fedTaxes
print "Pay:         ", takeHome

Formatted Output

Java version 1.5 introduced the printf() method for use with the System.out object to produce formatted output. Python also supports formatted output using the special string formatting operator (%) along with the print statement. Consider the following

print "The sum of %d and %d is %f\n" % (a, b, sum)

Complete details on the use of the formatting operator is provided in the next chapter.

Functions and Methods Table Of Contents Strings

© 2006 - 2008: Rance Necaise - Page last modified on September 08, 2006, at 10:38 AM