Fairly new to python, know some basics but want to dive straight in and create economic models, play with the math and interpret the ouputs. However, everytime i place a letter in the equation there will be an error. For example;
MoneyDemand = -100+2K
Money Supply = 5000*10K
File "experiment.py", line 20
MD = -100+2K
^
SyntaxError: invalid syntax
This is probably a small issue for most but i need assistance in how to overcome it. Thanks!
You've got three SyntaxErrors here. A SyntaxError means that you've written something that isn't valid python. I'd really suggest you look through some python tutorials to get a grip on how to program python. Even something like learn x in y minutes would probably be helpful.
But in your cases, the fixes are:
Ending a number with k is not valid python. If by that you mean 1000, you should just write 2000 or 10000. (Or, if you want, multiply it by 1000. See how the error points you at the letter k on the line.
You can't have spaces in the names of variables. Money Supply is not a valid name. Python conventions would probably suggest naming it money_supply.
python does not accept K as an indication of 1000.
You can however using scientific notation.
MoneyDemand = -100 + 2e3
MoneySupply = 5000 * 10e3
The e can be either lower or upper case.
Also note that I removed a space from your variable name Money Supply -> MoneySupply otherwise you would have a syntax error on the next line.
Related
I am encountering a weird situation in Python and would like some advice. For some business reasons, we need to keep this python code module to shortest number of lines. Long story --- but it gets into a requirement that this code module is printed out and archived on paper. I didnt make the rules -- just need to pay the mortgage.
We are reading a lot of data from a mainframe web service and applying some business rules to the data. For example and "plain English" business rule would be
If the non resident state value for field XXXXXX is blank or shorter than two character [treat as same], the value for XXXXXX must be set to "NR". Evaluation must treat the value as non resident unless the residence has been explicitly asserted.
I would like to use ternary operators for some of these rules as they will help condense the over lines of code. I have not use ternary's in python3 for this type of work and I am missing something or formatting the line wrong
mtvartaxresXXX = "NR" if len(mtvartaxresXXX)< 2
does not work.
This block (classic python) does work
if len(mtvartaxresXXX) < 2:
mtvartaxresXXX = "NR"
What is the most "pythonish" way to perform this evaluation on a single line if statement.
Thanks
You can simply write the if statement on a single line:
if len(mtvartaxresXXX) < 2: mtvartaxresXXX = "NR"
This is the same number of lines as the ternary, and doesn't require an explicit else value, so it's fewer characters.
I'm new to coding and I'm using Python. And I was making a simple calculator, just to mess around with the IDLE, and I keep getting this error:
"ValueError: could not convert string to float: 'bread'"
Here is the code I have written.
total = float("bread") + float("coffee") + float("milk")
I was hoping someone could point me to what is wrong here.
You have to input the actual variable, not the string of the variable. If you put anything between "", it automatically becomes a string.
Try this:
total = float(bread) + float(coffee) + float(milk)
It will work.
The reason why your program didn't work is, that you can't calculate the float value of a string. Imagine sitting in a maths class and your teacher tells you to calculate what bread plus coffee is.
Because you put the words between "", the compiler interpreted them as strings and not as your variables.
it my first time using Stack Overflow so please excuse any mistakes i have made. Im creating a program and i want ask mathematical questions for the user. But my program will generate two random numbers, and a random arithmetic operator will occur. They are plus, minus and times. So i put them into an array and this is the code.
Code:
The Error i gained:
It said the Error is in Line 10.
Ive tried doing this 'What is'+str(Ran) +,+str(op) +,+str(dom) +'?')
However i gained an invalid syntax on the comma.
Ive tried searching for this particular program, but all of them seem to have something called classes and def in. If it is possible, can i please not use the def and class in my program because i am new to python and i still need to learn what they are.
I am using Python 3.4.2, on a Windows 8 operating system if you wanted to know.
Thanks for reading, i am looking forward to have any assistance in my problem.
+ + is invalid syntax. You should be doing str(something) + ' ' + string(something_else) if you want to add two strings with a space in between. You also need quotes around add, minus and times in the list in order to make them strings.
I am teaching some neighborhood kids to program in Python. Our first project is to convert a string given as a Roman numeral to the Arabic value.
So we developed an function to evaluate a string that is a Roman numeral the function takes a string and creates a list that has the Arabic equivalents and the operations that would be done to evaluate to the Arabic equivalent.
For example suppose you fed in XI the function will return [1,'+',10]
If you fed in IX the function will return [10,'-',1]
Since we need to handle the cases where adjacent values are equal separately let us ignore the case where the supplied value is XII as that would return [1,'=',1,'+',10] and the case where the Roman is IIX as that would return [10,'-',1,'=',1]
Here is the function
def conversion(some_roman):
roman_dict = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M',1000}
arabic_list = []
for letter in some_roman.upper():
if len(roman_list) == 0:
arabic_list.append(roman_dict[letter]
continue
previous = roman_list[-1]
current_arabic = roman_dict[letter]
if current_arabic > previous:
arabic_list.extend(['+',current_arabic])
continue
if current_arabic == previous:
arabic_list.extend(['=',current_arabic])
continue
if current_arabic < previous:
arabic_list.extend(['-',current_arabic])
arabic_list.reverse()
return arabic_list
the only way I can think to evaluate the result is to use eval()
something like
def evaluate(some_list):
list_of_strings = [str(item) for item in some_list]
converted_to_string = ''.join([list_of_strings])
arabic_value = eval(converted_to_string)
return arabic_value
I am a little bit nervous about this code because at some point I read that eval is dangerous to use in most circumstances as it allows someone to introduce mischief into your system. But I can't figure out another way to evaluate the list returned from the first function. So without having to write a more complex function.
The kids get the conversion function so even if it looks complicated they understand the process of roman numeral conversion and it makes sense. When we have talked about evaluation though I can see they get lost. Thus I am really hoping for some way to evaluate the results of the conversion function that doesn't require too much convoluted code.
Sorry if this is warped, I am so . . .
Is there a way to accomplish what eval does without using eval
Yes, definitely. One option would be to convert the whole thing into an ast tree and parse it yourself (see here for an example).
I am a little bit nervous about this code because at some point I read that eval is dangerous to use in most circumstances as it allows someone to introduce mischief into your system.
This is definitely true. Any time you consider using eval, you need to do some thinking about your particular use-case. The real question is how much do you trust the user and what damage can they do? If you're distributing this as a script and users are only using it on their own computer, then it's really not a problem -- After all, they don't need to inject malicious code into your script to remove their home directory. If you're planning on hosting this on your server, that's a different story entirely ... Then you need to figure out where the string comes from and if there is any way for the user to modify the string in a way that could make it untrusted to run. Hackers are pretty clever1,2 and so hosting something like this on your server is generally not a good idea. (I always assume that the hackers know python WAY better than I do).
1http://blog.delroth.net/2013/03/escaping-a-python-sandbox-ndh-2013-quals-writeup/
2http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
The only implementation of a safe expression evalulator that I've come across is:
https://pypi.org/project/simpleeval/
It supports a lot of basic Python-ish expressions and is quite restricted in what it allows you to do (so you don't blow up the interpreter or do something evil). It uses the python ast module for parsing, and evaluates the result itself.
Example:
from simpleeval import simple_eval
simple_eval("21 + 21")
Then you can extend it and give it access to the parts of your program that you want to:
simple_eval("x + y", names={"x": 22, "y": 48})
or
simple_eval("do_thing(11)", functions={"do_thing": my_callback})
and so on.
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