Considering Data Types in IronPython
❘
35
The
raw_input()
function is also new. If you’re working in Visual Studio, the console screen appears
and disappears so quickly in many cases that you can’t see the output of your code. Using the
raw_
input()
function as shown simply adds a pause to your code. The string included with the function
call provides a prompt. You’ll discover more about input and output functionality as the book pro-
gresses. For right now, all you really need to know is that you can obtain a value from the console using
raw_input()
.
Don’t get the idea that you won’t have any access to native data types. It’s possible to tell IronPython
to react in a certain way to your data. For example, you can use the
str()
and
repr()
functions to
interpret a string in multiple ways. In addition, you can specifically convert numbers to a specific type,
as shown in Listing 2-2.
lISTINg 2-2:
Specifying data types
# Create a string variable.
String = ‘Hello and Goodbye’
# Display using str() and repr()
print ‘A string and its representation.’
print ‘str()‘, str(String)
print ‘repr()‘, repr(String)
# Create the numeric variable.
Number = 5.1
# Display the numeric types.
print ‘\nThe numeric data types.’
print ‘int’, int(Number)
print ‘long’, long(Number)
print ‘float’, float(Number)
print ‘complex’, complex(Number, 3.5)
# Pause the display
raw_input(‘Press any key...’)
This example begins by showing you a comment. Yes, IronPython, like most computer languages,
supports comments and you should use them often.
The first part of the code works with a string. When you use the
str()
function, you tell IronPython
to take any data within the function, the expression, and convert it to a string. IronPython performs
this task for you automatically, but you can use the
str()
function for explicit conversion. The output
of the
str()
function is always in human-readable form. The
repr()
function returns a representa-
tion of the object you pass to it. In most cases, you use the
repr()
function to create output that the
interpreter understands. Figure 2-17 shows the difference in output between the two functions. Notice
that
repr()
outputs single quotes so you could pass this information directly to the interpreter.
The second part of the code works with a number. In this case, the number contains floating point
data. However, you can convert it directly to an
int
or
long
using the
int()
or
long()
functions.
The
float()
function will convert any numeric data into a floating point number and you can
even create complex numbers using the
complex()
function. Figure 2-17 shows the output from the
numeric conversions as well. IronPython also supports base conversions using the
oct()
and
hex()
548592c02.indd 35
2/24/10 12:47:22 PM
www.finebook.ir
Do'stlaringiz bilan baham: |