''' Purpose: introduce casting -- constructing a value of one type from a value of another type int( s ): returns the integer constructed from integer numeric string s int( d ): returns the integer part of decimal d float( s ): returns the decimal constructed from numeric string s. there maybe loss of precision float( i ): returns the decimal constructed using integer i. there maybe loss of precision str( x ) : returns a string version of x ''' # Casting - converting from one type to another # Types we've seen so far: # int (ex. 3) # float (ex. 3.0) # string (ex. '3') # define values for int and float casting integer_string = '7' decimal_string = '3.2' decimal_number = 1327934872398572398.5235987239482930480239840293842039 integer_number = 427349871239859274129759821751982798127508923759823175891273598172398572398 # get integer conversions i1 = int( integer_string ) # int('7') -> 7 # Convert string of number to an integer i2 = int( decimal_number ) # int(13.5) -> 13 # Convert float (decimal) to an integer # get decimal conversions f1 = float( integer_number ) # float(4) -> 4.0 # Convert integer to a float f2 = float( decimal_string ) # float('3.2') -> 3.2 # Convert string of decimal to a float # print conversion statements print() print( 'integer_string = \'' + integer_string + '\'' ) print( 'decimal_string = \'' + decimal_string + '\'' ) print( 'decimal_number =', decimal_number ) print( 'integer_number =', integer_number ) print() print( 'i1 = int( integer_string )' ) print( 'i2 = int( decimal_number )' ) print() print( 'f1 = float( integer_number )' ) print( 'f2 = float( decimal_string )' ) print() reply = input( 'Enter when ready. ' ) print() # use conversions in arithmetic total1 = i1 + i2 total2 = f1 + f2 print( i1, '+', i2, '=', total1 ) print( f1, '+', f2, '=', total2 ) print() reply = input( 'Enter when ready. ' ) print() # define and print some numbers for string cast nbr1 = 37 # integer nbr2 = 12.15 # decimal print( 'nbr1 =', nbr1 ) print( 'nbr2 =', nbr2 ) print() # get and print string conversions s1 = str( nbr1 ) # str(37) -> '37' # Convert int to a string s2 = str( nbr2 ) # str(12.15) -> '12.15' # Convert float to a string # '37' + '12.15' (String concatenation - glue strings together!) -> '3712.15' # print conversion statements print( 's1 = str( nbr1 )' ) print( 's2 = str( nbr2 )' ) print() reply = input( 'Enter when ready. ' ) print() # use them s3 = s1 + s2 print( '\'' + s1 + '\' +', '\'' + s2 + '\' =', '\'' + s3 + '\'' ) # print('\'') is just printing ' (like the apostophe itself) # If you want to have a quote inside a quote, these are called special/escape characters # \' is the character ' (the single quote) # For s1 = '2' and s2 = '3.0' # So this would print out # '2' + '3.0' = '23.0' based on this print statement ^