This question already has answers here:
Safe way to parse user-supplied mathematical formula in Python
(3 answers)
Closed 1 year ago.
So I wanna make a code that solves simple problems (For example 3+4=? or 2/4+5=?) that are typed in by the user with input() but it treats the returned value as a string and it doesn't wanna work.
Basicly I wanna do this correctly:
print('Enter a problem:')
equals = input()
print('The answer is {}.'.format(equals))
Thanks in advance and have a nice day!
Well input() always returns a string. There is no way around that. However, you can't just "cast" it to be an equation. However, if you know the operations that will be inputted you can do some parsing. For example, this is how you might handle addition.
print('Enter a problem:')
equation = input() # user inputs 3+4=?
equalsIndex = equation.index('=')
# Reads the equation up to the equals symbol and splits the equation into the two numbers being added.
nums = equation[:equalsIndex].split('+')
nums[0] = int(nums[0])
nums[1] = int(nums[0])
print('The answer is {}.'.format(nums[0] + nums[1]))
In general, you would have to parse for the different operations.
You can't transform this from "string" to "code". I think that exist a lot of libraries that can help you (example).
Other option is that you write your own code to do that.
Main idea of that is to get numbers and operators from string to variables. You can use "if" to choosing operations.
Example.
You have a input string in format "a+b" or "a-b", where a,b - integers from 1 to 9. You can take first and last symbol of that string. Convert it into integer and save into variables. Next step is check if second symbol of the string is "+" than you can add this two variables. Otherwise you can sub this variables. That's it.
Obviously if you want some powerful application you need more work, but it only an idea.
To my experience, I have no idea on how to solve problem directly inside the input(). The only way to solve your issue (I think) is overide the input() method. You can Google 'overriding method python' and you'll find the syntax.
Hope you'll figure out this problem. Have a nice day :)
Use exec as follows.
equation = input("Input your equation")
exec("output = {}".format(equation))
print(output)
Here is an example (Note. "=" should not be included in the equation)
Input your equation: 2+4
6
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 12 months ago.
Improve this question
I need to generate a string of the numbers from 1 to 50 with a for-loop.
my suggestion:
solution = range(1,50)
for i in solution
print(i++, end ="")
it shows me invalid syntax and I don't really get behind the reason. The output should be a string with the number from 1 to 50 added like this (12345....).
How do I do that?
variable++ is not Python syntax at all. You might know it from C, C++, Java, JavaScript, or any of the dozens of languages that use it.
You're missing a colon after the for loop line.
The Python interpreter should have pointed out at least the latter to you. The former is easily found by Googling.
The following should give the output you need, but know that there are easier ways to do this in Python.
solution = range(1,50)
string_variable = "" # the i from below will be of type integer, not string.
for i in solution:
string_variable += str(i) # += performs appending (or addition depending on the data type), but you'll need to convert i to a string
print(string_variable)
Explanation (method 1)
Breaking down the problem
Let's think about what you want.
You want to consider numbers from 1 to 50.
You then want to think about them one at a time.
While doing step 2, you want to maintain a "joined" record somewhere, and "join" each number at the end of the record as you consider it.
Finally, you want to output that "joined" record.
Converting ideas to code
Let's go through each step one at a time, this time in code.
Consider numbers from 1 to 50.
You got this! You saved a range() generator to a variable with 1 and 50 as its endpoints.
solution = range(1, 50)
Think about them one at a time.
You got this too! By using a for loop to iterate over your generator, you are doing this.
for i in solution:
Join the numbers
This step gotcha :(
To understand this, you need to know about something called data types.
The range() generator gives you integer values. Think of this as a proper value: a number that you can manipulate (add, subtract, multiply etc).
However, when you want to join stuff together (called concatenating), you need to use strings.
To you and me, a number on a piece of paper is same as the number on a calculator. To a computer, it's not. If it's a string, it's treated equivalently to an alphabet: you cannot do math with it, you can only do stuff like displaying it.
To concatenate, you must convert to a string. That's why I start with a blank string variable.
string_variable = ""
We do this with the following syntax:
str(i)
The str stands for string.
The joining part happens with the += operator:
string_variable += str(i)
Output the string
I think you know how to do this. Just print it out:
print(string_variable)
Putting it all together:
solution = range(1,50)
string_variable = ""
for i in solution:
string_variable += str(i)
print(string_variable)
Explanation (method 2)
I think your logic was right.
solution = range(1,50)
for i in solution
print(i++, end ="")
We're removing the ++ because it isn't valid Python syntax. This is the increment operator from languages like C++. In practice, if you were using something like a while loop, you would use this to increase the value of i by 1 in each pass of the loop. However, for loops sort of have this idea built into them, so we don't need it.
Addition of : and indentation by 4 spaces are done because that's way we communicate to Python that the line print(i, end ="") is to be executed inside the loop for i in solution.
Corrected code:
solution = range(1,50)
for i in solution:
print(i, end ="")
This question already has answers here:
How to get the size of a string in Python?
(6 answers)
Closed 1 year ago.
we have just begun our unit on recursion, and I had a question regarding non-recursive functions and strings
I understand that strings are inherently recursive, as each character within a string has its own positive or negative index value, but I am a little unclear on how to create this function.
EDIT: Please disregard above text
What I meant to say:
I understand that a sequence is recursive in nature, that a string is a character followed by another string, just as a list is an element followed by another list.
Imagine we had a function called:
def flipside(s)
And when we input a string into our s parameter of the function, for example, the string:
'homework'
It takes the first half of the string (s) and moves it to the back while taking the second half of the string moving it the front, effectively generating the output:
'workhome'
I guess what I am having an issue with, is regarding string operations. If I do not know the length of s because it can take on any value due to it being a parameter, how do I create a non-recursive program to take 1//2 of s and move that half of the string to the back while simultaneously pushing the second half forward.
I have only gone so far as to set my base case:
def flipside(s):
if s == (''):
return 0
else:
fliprest =
return fliprest
Thank you, I would appreciate any information on the thought process behind your logic, or any feedback regarding any bad habits that I may be developing with how I have started off my code.
You can use slicing
def flipside(s):
return s[len(s)//2:] + s[:len(s)//2]
>>> flipside('homework')
'workhome'
This question already has answers here:
How to calculate an equation in a string, python
(2 answers)
Closed 2 years ago.
I'm using Python 3.7.4. I was wondering about how to keep track of symbols like: +, /, -, * in a string. But I mean with out the '' and "" in front and behind of it. I'm creating a calculator as my project. This is what it looks like:
When ever you click on one of the buttons it adds that number to a string like user_text = ''. So like a blank string. So say you have in 9 + 9 the string when ever you added it together you get 18. But the problem lies with: +, /, -, *. Cause I know how to turn a string into a number and then add them together or any other way. But, how would you keep track of the symbols in the string and add the numbers in the string to each other with the symbol with it. So, with the correct operation.
I've tried to do: if '+' in len(user_text): print("Yes") but then I realize that it can't iterate a string for int. Anything with range is out of the question I realized too. I was thinking about having like a back up line, but as a list then append what ever was entered onto the list. Then keep track of it. Like say user_list = [] then you added 4 + 4 onto the list user_list = ['4', '+', '4']. But then again how would I keep track of the symbols I said, but then add the 2 strings numbers together as an int to get 8. I just can't think of a way to do something like this. I might be overthinking this but I just can't think of it.
If I can provide anymore information on my issue or anything, let me know. I appreciate the advice and help. Thank you.
Have you considered using python's eval()? Since your calculator probably doesn't use the same operator symbols as python you might have to tweak the resulting string from your calculator to make it work, but it sounds like eval() should do the job for you.
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reverse a string in Python
Its been stumping me despite my initial thoughts that it would be simple.
Originally, I thought I would have have it print the elements of the string backwards by using slicing to have it go from the last letter to the first.
But nothing I've tried works. The code is only a couple lines so I don't think I will post it. Its extraordinarily frustrating to do.
I can only use the " for ", "while", "If" functions. And I can use tuples. And indexing and slicing. But thats it. Can somebody help?
(I tried to get every letter in the string to be turned into a tuple, but it gave me an error. I was doing this to print the tuple backwards which just gives me the same problem as the first)
I do not know what the last letter of the word could be, so I have no way of giving an endpoint for it to count back from. Nor can I seem to specify that the first letter be last and all others go before it.
You can do:
>>> 'Hello'[::-1]
'olleH'
Sample
As Mike Christensen above wrote, you could easily do 'Hello'[::-1].
However, that's a Python-specific thing. What you could do in general if you're working in other languages, including languages that don't allow for negative list slicing, would be something more like:
def getbackwards(input_string):
output = ''
for x in range(0,len(input_string),-1):
output += input_string[x]
return output
You of course would not actually do this in Python, but just wanted to give you an example.