|
I just completed the Rounding Numbers piece of homework, and tried to bug test it a little bit. I found that if you assign 'x' as a fraction (e.g. 9/5) it will incorrectly get rounded down as it assumes an integer, so the code will produce the answer 1, instead of the correct 2. If you input the number as '9./5.' it corrects this, and I know that you can use float() AFTER you've assigned the variable to let the program know it will have decimal points, but I was wondering if there were a way to set the variable to have decimal points when you create the variable, so Python doesn't have to guess what type it is, and the user doesn't have to input the number with a '.'. Thanks for your help. |
|
No I don't think it's possible, though you can ask this over at StackOverflow if you want. Python doesn't bind a variable to any particular type. Here, I think this example will make it more clear. # id(x) returns the memory address of the variable x
Hope this helps Wow, that's exactly the answer I was looking for, and more. Thanks for clearing that up! Would you see that as a flaw of Python or is it more of a non-issue? P.S. I just noticed there are nested comment threads and the delete button doesn't seem to be working on my other reply. I would call it a feature. |
|
You can set the var as x = 0.0 and then update it somewhere in the code... Would this have the effect you want? Not sure what you want to do... |
|
I want to be able to set x to have decimal places immediately. I don't want to have the input the number with a decimal point. For example, if in the Rounding Numbers homework I had the user input a number, and he chose "9/5". If the code used that exact entry, it assumes the division of 9/5 is an integer, and so with the code I produced it would output 1 as the rounded number. I have very little coding knowledge, but I believe in C# and other languages you can set variables to be types straight away, as with int, float, var, etc.. I want to be able to do that without having to set x first, then convert it using float(x). I hope that makes more sense. |