Nov-22-2022, 08:20 PM
do we convert the data type ?
where in the program is the conversion occurs ?
where in the program is the conversion occurs ?
first function
|
Nov-22-2022, 08:20 PM
do we convert the data type ?
where in the program is the conversion occurs ?
There is no conversion, calling the built-in function
int by passing it a string, the string remains a string, a integer object is returned from the function.input_str = "10" print(type(input_str)) returned_int = int(input_str) print(type(input_str)) print(type(returned_int))
number = get_int(input("Number: ")) passes a str object (which is what is returned from the input() function) to our get_int() function. Then, try: n = int(n) , tries to type convert the srt object (which in n in this function) to an int object.def get_int(n): try: print(f"Type converting {type(n)}") n = int(n) print(f"Type conversion to {type(n)} done.") return n except ValueError: print(f"Type conversion of {n} failed.") return False while True: number = get_int(input("Number: ")) if number: # do whatever print(number, type(number)) else: print("Error in number input")With a input of 12:
Sig:
>>> import this The UNIX philosophy: "Do one thing, and do it well." "The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse "Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Nov-22-2022, 10:51 PM
(This post was last modified: Nov-23-2022, 05:32 AM by deanhystad.)
int(arg) raises a ValueError if the string cannot be interpreted as an integer. The arg is the correct type for this operation (it is a str), but the Value of the string is wrong.
arg = "Hi mom!" number = int(arg) A TypeError is raised when you pass an argument that is incompatible with the operation being performed.arg = [1, 2, 3] number = int(arg) Here args cannot be converted to an int because str() doesn't know how to convert a list into an int. The Type of arg is wrong.
Nov-23-2022, 06:43 PM
okay,
so from what i understood, is even if the the value is a str initially, it will be converted only if it's comprised of digits....otherwise it's a ValueError, and if it's another kind of data type not compatible with being converted into an int - it's a TypeError. understood correctly ? what does the 'base 10' means ? (invalid literal for int() with base 10) thank you
Nov-24-2022, 04:04 AM
It means base 10. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10... base 2 is 0, 1, 10, 11, 100, 101, 110, 111...base 16 is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f
Nov-24-2022, 04:22 PM
alright, cool !
so it would be simply called decimal, base 2 is binary, 8 is octal, and 16 is hexadecimal, just got to know the correlation |
|