Python issue with implicit data types
|
08-01-2024, 08:13 PM
(This post was last modified: 08-01-2024 08:25 PM by nbc12.)
Post: #2
|
|||
|
|||
RE: Python issue with implicit data types
I can't comment on the behavior of pixon, but I do know that Python isn't designed to be strongly typed. I don't have much experience with Micropython or Python on the Prime, but I have been using Python for over 10 years, and currently write Python for work.
I don't know your programming background or level of experience with Python, but you can mitigate unintended behavior of weak typing with a few tools: To convert between types, you can simply wrap the type in the "constructor" of the desired type. str(5) returns '5', int(5.5) returns 5, etc. Usually the only type conversions I need for numeric programs (mandelbrot etc) are:
Also, if at least one operand of a math operation is a float, the output will always be a float even if the value can be represented by an integer, excluding % and // for obvious reasons. For this reason, some of your variables will probably be a float even if they are representing an int. This can be frustrating for low level folks, myself included, but it's just an attribute of Python I've had to get used to. It doesn't usually impact anything anyway. I usually don't need to worry about making a distinction between floats and ints. I just floor/ceil/round/truncate everything as needed for program logic. Just make sure to convert everything at the end of your calculations if you are passing it to an external library function that takes an int, obviously. You can also use isinstance() combined with an if statement to change the program flow depending on a type at runtime. Code: x = isinstance(y, int) where x is a bool that is true if y is an int. Note: This does not see 4.0 as an integer. A numeric type is only a float if it has a decimal. Otherwise, it's an int. You can use int(x) == x if you want to check if the fractional part is zero. For debugging types, you can use Code: print(type(x)) Hope this helps! |
|||
« Next Oldest | Next Newest »
|
Messages In This Thread |
Python issue with implicit data types - 34C - 08-01-2024, 11:08 AM
RE: Python issue with implicit data types - nbc12 - 08-01-2024 08:13 PM
RE: Python issue with implicit data types - bxparks - 08-01-2024, 09:33 PM
RE: Python issue with implicit data types - toml_12953 - 08-01-2024, 09:23 PM
RE: Python issue with implicit data types - Albert Chan - 08-02-2024, 04:13 PM
RE: Python issue with implicit data types - 34C - 08-03-2024, 09:25 AM
|
User(s) browsing this thread: 2 Guest(s)