------------------------------------------------------------------------------
MC logo
Input And Conversion
[^] Code Examples
------------------------------------------------------------------------------
<<Strings Operations scon.py Lists>>
#!/usr/bin/python3

# Strings can be converted to numbers and vice versa with a functional
# notation.
a = "459"
b = "1891"
c1 = a + b
c2 = int(a) + int(b)
print(a,b,c1,c2)
print()

# The input method reads a line as a string.  Then you can process the
# string.
in1 = input("Please enter a string: ")
print("A string:", in1)
in2 = input("Please enter an integer: ")
in3 = input("Please enter another integer: ")
print("The sum is:", int(in2)+int(in3))
print("The concatination is:", in2+in3)

Python types can be used like function names to perform conversion. For instance, int and float convert to integer or float, respectively, when used as function names. If the conversion of a string to a numeric type fails, Python will throw an exception, much as Java does.

The type str converts to string. This is particularly useful, since Python will not implicitly convert numbers to strings for the concatination operator, as Java does. Python throws a type error exception.

<<Strings Operations Lists>>