|
User InteractionPage Contents (hide) 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 InputJava version 1.5 introduced the print "What is your name? " name = raw_input() The User PromptsWhen 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 name = raw_input( "What is your name?" ) When executed, the Python interpreter will display the string on a new line and then way for the user to enter the data. Numeric ValuesThe input = raw_input( "What is your gpa?" ) gpa = float( input ) This code segment can be written as a single statement by nesting the two function calls gpa = float( raw_input( "What is your gpa?" ) ) Type ConversionsIn Java, some data types are automatically converted to a different type depending on how it is used. For example, the value of the integer variable int result = 40; System.out.print( "The result = " + result ); While Python can promote and handle conversions between the numeric data types, it does not automatically convert between other data types. Since there are times when you need to convert between the different primitive data types, Python provides several built-in conversion functions. In the following example, the aString = "123.45" value = float( aString ) The following is a list of Python’s built-in type conversion functions for strings and numeric types. Each o function creates a new object of the indicated type.
Standard OutputIn Python, as you have seen in a number of examples, the The avg = grade / 3.0 print avg To display or print multiple values, you can use multiple print "Your average grade =", avg Note: You can not concatenate non-string values with strings as can be done in Java.
Formatted OutputJava version 1.5 introduced the print "The sum of %d and %d is %d\n" % (a, b, sum) Complete details on the use of the formatting operator is provided in a later section. --- 1 |
|
© 2006 - 2008: Rance Necaise - Page last
modified on August 09, 2006, at 10:04 PM
|