Type Casting Type casting Sometimes you need a

  • Slides: 5
Download presentation
Type Casting

Type Casting

Type casting • Sometimes you need a piece of data converted to a different

Type casting • Sometimes you need a piece of data converted to a different type • In Python you do a typecast to cause that to happen • int(3. 599) will give 3 – note that it throws away the fraction, does not round it • float (4349) will give 4349. 0 – it looks the same but remember that it is stored differently in memory • float(“ 23. 4”) will give 23. 4, but float(“abc”) will give a runtime error • x = 5. 3 y = int(x) makes y have the value 5, does NOT change x’s value

Type cast for strings • str will turn a number into a string. This

Type cast for strings • str will turn a number into a string. This is handy when you are using functions which require a string as an argument • str(3. 5) will give “ 3. 5” • str(“abc”) will give “abc” – this one is silly but Python allows it. If the data is already a string, why make it a string again?

Typecasting with input function • Typecasting is used pretty often with the input function

Typecasting with input function • Typecasting is used pretty often with the input function • The input function always returns a string • If you need the data in the string interpreted as a different type, you have to use a typecast to change it to that type • my_num = int(input(“Enter a number “)) • This is the shorthand way of writing two statements my_data = input(“Enter a number “)) my_num = int(my_data)

Strongly typed versus weakly typed • Python allows one variable to hold many different

Strongly typed versus weakly typed • Python allows one variable to hold many different types of values, one after the other • This means the language is weakly typed • Languages like C++ and Java are strongly typed. You have to state what type a variable is and it does not change its type for the whole program • Types are good to help you avoid errors that involve using the wrong type of data or using the data in an illogical way • In Python it is smarter to keep each variable to one type. If you need to use it as a different type, typecast it and put it into a different variable