DFN40323 - PROGRAMMING ESSENTIALS IN PYTHON CODING School Search . . . 1.4 Construct Python literals
CODING School Search . . . LEARNING OUTCOMES 01 0 2 1.4 .2 Ma n ip u la t e P yt h o n lit e ra ls u sin g co n ve rt in g op e rat ion a) strings into numbers b) numbers to strings
CODING School Search . . . Convert a string to number using int() # String to be converted myStr = "200" # Display the string and it's type print("String = ", myStr) print("Type= ", type(myStr)) # Convert the string to integer using int() and display the type myInt = int(myStr) print("\nInteger = ", myInt) print("Type = ", type(myInt))
num = '10' # check and print type num variable print(type(num)) # convert the num into string converted_num = int(num) # print type of converted_num print(type(converted_num)) # We can check by doing some mathematical operations print(converted_num + 20)
CODING School Search . . . Convert a string to number using float() # String to be converted myStr = "500" # Display the string and it's type print("String = ",myStr) print("Type= ", type(myStr)) # Convert the string to float myFloat = float(myStr) print("\nFloat = ", myFloat) print("Type = ", type(myFloat)) # Convert the float to int myInt = int(myFloat) print("\nInteger = ", myInt) print("Type = ", type(myInt))
num = '10.5' # check and print type num variable print(type(num)) # convert the num into string converted_num = float(num) # print type of converted_num print(type(converted_num)) # We can check by doing some mathematical operations print(converted_num + 20.5) a = '2' b = '3' # print the data type of a and b print(type(a)) print(type(b)) # convert a using float a = float(a) # convert b using int b = int(b) # sum both integers sum = a + b # as strings and integers can't be added # try testing the sum print(sum)
CODING School Search . . . Example : Calculate Age If you want to then perform mathematical operations on that input, such as subtracting that input from another number, you will get an error because you can't carry out mathematical operations on strings.
CODING School Exercise 1. Fix the error occurred in the Example : Calculate Age Search . . .
CODING School Convert a number to string using str() Search . . . • We can convert numbers to strings through using the str() method. • We’ll pass either a number or a variable into the parentheses of the method and then that numeric value will be converted into a string value. • Eg: str(12) Output '12'
Search . . . CODING School Example user = "Sammy" lines = 50 print("Congratulations, " + user + "! You just wrote " + lines + " lines of code.") user = "Sammy" lines = 50 print("Congratulations, " + user + "! You just wrote " + str(lines) + " lines of code.") print(str(421.034)) f = 5524.53 print(str(f)) f = 5524.53 print("Sammy has " + str(f) + " points.")
CODING School EXERCISE Search . . . https://holypython.com/beginner-python-exercises/exercise4-python-type-conversions/