Python: Function simplifying the input instead of passing string - python

I need to enter a complex string for handling (UTC time code) and breaking down as part of an assignment. I have started the function like this as required:
def convertWmiDateTime(wmiDateTime):
But when I enter this:
convertWmiDateTime(20061122185433.000000+600)
The variable wmiDateTime stores 2.0061122186e+13
If I use raw_input the value 20061122185433.000000+600 will be stored correctly in wmiDateTime, but not when its called as intended above.
Is there a way to preserve what was typed into the input? A way to stop Pythong calculating and simplifying the number? vb. net would be something like (wmiDateTime As String) is there anything like that for Python?
Thanks for looking.

Your function requires a string as its input parameter. You can't call it with a number (as you're doing).
raw_input() returns a string, so the equivalent would be to call
convertWmiDateTime("20061122185433.000000+600")
Your version treats the time code as a floating point number which a) doesn't have the required precision to preserve all the digits and b) will get the timezone info (+600) added, which leads to wrong results as well.

Related

How to take bytes as input without any manipulation in it in python?

I am taking a byte as input
b'\xe2I4\xdd\r\xe5\xfcy^4\xd5'
but it gets converted into string.
so when i am to trying to convert this string to byte it is again manipulating it and giving me output as:
b"b'\\xe2I4\\xdd\\r\\xe5\\xfcy^4\\xd5'"
My desired output is that when i provide b'\xe2I4\xdd\r\xe5\xfcy^4\xd5' it convert it into byte as it is without manipulating it or adding any character or symbol.
Any resource or reference will be helpful.
Thanks In Advance
The BAD idea
You could pass the value of input() to eval() function. The function eval() directly evaluates a string as if it were directly executed in Python. Although it might feel like a best feature at first but due to the same reason it is pretty much unsafe to use it within any production-level application, since, the user can execute any code using that which might cause a lot of problems.
Better alternative
You can use a safer alternative to eval() which is ast.literal_eval(). This function evaluates a given string as Python literals (like string, numbers, bytes object, etc.). In case if a string does not contain any literal (like function calls, object creation, assignment, etc.), this function throws an error. Enough about that let's see how you could get this working.
import ast
user_input = input()
eval_expr = ast.literal_eval(user_input)
If you want to check if the input is a bytes literal, you could use the isinstance function to check and then perform required action.
# Optional: Handle if `eval_expr` is not a `bytes` literal
if not isinstance(eval_expr, bytes):
...
So, all you need to do is import the module ast first. Then take the user's input. Thereafter pass this input string to ast.literal_eval() function to evaluate the string.

int() vs float() inputs in Python 3 and their utility?

This doesn't refer to a specific code of mine, so I hope this does not defy community standards for asking questions. I'm still learning, so please let me know if this kind of question is inappropriate for future reference!
I am trying to gain a thorough understanding of the utility of certain commands as I embark on learning to use Python 3. I have never coded before, so I do not have background in any other language. I was hoping someone could help me understand this more thoroughly.
Basically, I understand that when prompting for a user input with a numeric value, it is sometimes correct to write float(input()), and sometimes correct to write int(input()). I know in mathematics that an integer is a whole number, and a floating point number is any number defined with a whole portion, a radix, and a mantissa (like 4.32). I don't understand the utility of converting a user input to one or the other.
For example, if I write int(input("Input a decimal. ")) and the user inputs 4.3, the program will return a value error. What is the utility in this? So:
What is the utility in converting an input() to float() or int()?
I understand when I would want an integer (e.g; if I want the user to input how many times to multiply a particular number by itself), but why would I want a floating point input?
In general, when do I need to implement either, and how can I recognize which one a program needs?
Aside from user input, in what other general cases would I want to implement either command?
If anyone has any additional reading on how and when to convert certain defined variables or inputs, please send them my way!
EDIT:
Here is an example of a code that I wrote that I think highlights my confusion about if and when to use int() and float():
price=input("How much did the item cost?: $")
if float(price)<0:
print("The price cannot be negative.")
else:
price=int(float(price)*100)
paid=input("How much did the customer pay?: $")
paid=int(float(paid)*100)
Did I do this correctly? The larger program of which this is a part works fine, but I'm not sure if I added unnecessary command or implemented the commands correctly.
Thank you so much for your help!
Naomi
It has nothing about utility, it has to do with what are the possible range of values you're program should/needs to accept.
If it needs to accept both integers and floats as inputs, then you should convert to float since floats can represent the integers.
But if you're program requires that the input be specifically an integer, then you should be casting to int.
EDIT:
In your example, you should always be using float, since money has a decimal value.
If you were asking "How many bananas did you buy?" You'd want to convert to int since those values are going to be 0, 1, 2, 3, 4, .... And then when you ask "How much did you pay for these bananas?" You'd want to convert to float since those inputs can range from 3.15, .77, 1, 1.00, ... etc.
So that you can work with numbers. You can't very well multiply '3' by '2' in Python.
So that you can work with floating-point numbers. Some things in life can come in bits and pieces, like kilograms, seconds, or grade point averages.
If your program needs to work with the numbers between consecutive integers, you should probably use float.
If you use strings in your program, you may want them to be numbers, regardless of where the strings came from.
You'll need to evaluate this on a case-by-case basis.
You can implement error checking using the try function. The only reason to use an int vs a float, would be if you are trying to save memory, in the case of embedded ROM where you are severly limited.
In my opinion, you should always use float whenever you're not sure because it accepts more values so it will less likely return an error.
Unless your code expects a rounded number (you can round the number if it's a float but can cause confusion if done incorrectly) from a users input.
Bad example:
username_input = float(input("Enter your username: "))
pincode_input = int(input("Enter pincode: "))
pincode = 1234
if pincode == pincode_input:
print("Good")
else:
print("Bad")
In this case, the code expects the user to input a rounded number so I like to use int() so that if the user inputs a decimal number then I know where the problem is and can fix it directly instead of fixing every other code that relies on it.
This is a bad example because the code does run if the user's input doesn't get converted with int() but I hope you get the idea.

How do I make my program acknowledge that a variable contains an integer in Python

I'm new to using Python (and dynamically typed languages in general) and I'm having trouble with the my variables being incorrectly-typed at run time. The program I've written accepts 6 variables (all should be integers) and performs a series of calculations using them. However, the interpreter refuses to perform the first multiplication because it believes the variables are type 'str'. Even when I enter integers for all values it breaks at run-time and claims I've entered strings. Shouldn't Python treat anything that walks and quacks like an int as if it were an int?
Thanks in advance.
PS: I'm running Python 3.4.0, if that helps.
input() always returns a string. If you wanted to have an integer, convert your input.
variable = int(variable)
Python doesn't coerce, you need to convert explicitly. Dynamic typing doesn't mean Python will read your mind. :-)
You can think of it this way: "Duck Typing" applies to the type of a variable, not of the variable's contents. A string variable is something that can for example be indexed with [] or added to other strings with + and even repeated several times with * {some integer}, but you can't add a string to an integer, even if the string happens to be a number.
The number-ness of a string has nothing to do with the type.

how to avoid python numeric literals beginning with "0" being treated as octal?

I am trying to write a small Python 2.x API to support fetching a
job by jobNumber, where jobNumber is provided as an integer.
Sometimes the users provide ajobNumber as an integer literal
beginning with 0, e.g. 037537. (This is because they have been
coddled by R, a language that sanely considers 037537==37537.)
Python, however, considers integer literals starting with "0" to
be OCTAL, thus 037537!=37537, instead 037537==16223. This
strikes me as a blatant affront to the principle of least
surprise, and thankfully it looks like this was fixed in Python
3---see PEP 3127.
But I'm stuck with Python 2.7 at the moment. So my users do this:
>>> fetchJob(037537)
and silently get the wrong job (16223), or this:
>>> fetchJob(038537)
File "<stdin>", line 1
fetchJob(038537)
^
SyntaxError: invalid token
where Python is rejecting the octal-incompatible digit.
There doesn't seem to be anything provided via __future__ to
allow me to get the Py3K behavior---it would have to be built-in
to Python in some manner, since it requires a change to the lexer
at least.
Is anyone aware of how I could protect my users from getting the
wrong job in cases like this? At the moment the best I can think
of is to change that API so it take a string instead of an int.
At the moment the best I can think of is to change that API so it take a string instead of an int.
Yes, and I think this is a reasonable option given the situation.
Another option would be to make sure that all your job numbers contain at least one digit greater than 7 so that adding the leading zero will give an error immediately instead of an incorrect result, but that seems like a bigger hack than using strings.
A final option could be to educate your users. It will only take five minutes or so to explain not to add the leading zero and what can happen if you do. Even if they forget or accidentally add the zero due to old habits, they are more likely to spot the problem if they have heard of it before.
Perhaps you could take the input as a string, strip leading zeros, then convert back to an int?
test = "001234505"
test = int(test.lstrip("0")) # 1234505

Specify input() type in Python?

Is it possible to define input times, like time, date, currency or that should be verified manually? Like for example:
morning = input('Enter morning Time:')
evening = input('Enter evening Time:')
.. I need (only) time here, how do I make sure that user enters input in xx:xx format where xx are integers only.
input (in Python 2.any) will return the type of whatever expression the user types in. Better (in Python 2.any) is to use raw_input, which returns a string, and do the conversion yourself, catching the TypeError if the conversion fails.
Python 3.any's input works like 2.any's raw_input, i.e., it returns a string.
You can't really force the input function to return a certain type. It's best you write some kind of a wrapper that reads some input from the user and then converts it to an appropriate type for your application (or throw an exception in case of an error).
Also, as Alex said, it's better to use raw_input for user input since it will always return the entered value as a string. Much more manageable.

Categories

Resources