Converting between numbers and strings

Converting between strings and integers is particularly useful if we want to use input() to get a number from the user. Without this step input() assumes what it receives is text rather than a number, so we have to tell Python it is a number before we can do calculations on it.

We can convert from text strings to numbers, and then back again for printing purposes.

Converting a string to an integer

s = input("Type an integer:")
i = int(s)             ## i is an integer you can perform calculations on
print( 2 * i )

Converting a string to a float

s = input("Type a floating point number:")
f = float(s)           ## f is a float you can perform calculations on
print( 2 * f )

Converting a number to a string

a = 4
s = str(a)
print("Your number is " + s)


number_text = input("Type an integer:")
number = int( number_text )
answer = number * 2
answer_text = str( answer )
print("Double your number is: "+answer_text)


Create a program that asks for two numbers, and then prints out: