How can I input the maths functions (exp,log,sin) in python - python

When I run the following code :
import math
x=float(input('enter : '))
print(x)
and then I input : math.sin or cos or pi or log .... of a number like : sin(2) ,I get this error :
Traceback (most recent call last):
File "C:\Users\user\Desktop\hh.py", line 10, in <module>
x=float(input('enter : '))
ValueError: could not convert string to float: 'sin(x)'

You can get an answer by combining comments from #Walter Tross and #wwii. How to fix the problem if you want users to be able to enter code that will be evaluated with the result stored in x, you should use:
from ast import literal_eval
x = literal_eval(input('enter:'))
P.S. You will need to put quotation marks around the user input.
P.P.S. Your user can put in basically any code to be executed using this input.
To get to the why, you are giving python commands and expecting it to evaluate what you said and store it in x. You are giving words to python and not giving it a way to convert them to numbers. It'd be the same as typing into your terminal 2 plus 2. The words don't mean anything unless you have some kind of compiler.

It is difficult for you to write a program to understand and evaluate expressions, especially ones that include functions like sin or sqrt. However, if you are sure that the user of your program is safe (and that is usually a bad assumption), you can get Python to do the evaluation using the built-in eval function. You could try this:
import math
strexpr = input('enter: ')
print(eval(strexpr))
Then, if you run this program and the user types math.sin(2), the program prints
0.9092974268256817
which is the correct value of the sine of two radians.
NOTE: This little program will allow the user to type any valid Python expression then evaluate it. If the user knows how, he could use this to format the hard drive and wipe out all your data or do all kinds of mischief. Use this only if you are totally sure of the user. But how can you ever be sure about anyone else?

Related

Why do I get a ValueError: could not convert string to float in Python? [duplicate]

This question already has answers here:
Evaluating a mathematical expression in a string
(14 answers)
Closed 2 years ago.
I do not understand why I get a ValueError when I want to transform a calcul string into float. I would like an issue because I am stuck up.
(The aim of my code is to create random equations with increasing level depending on question number.)(I am still a beginner, sorry if my code is unmethodical (and in french too).)
:)
There is my code:
(input)
from random import *
def Numéro_Question():
global NuméroQuestion
NuméroQuestion+=1
print("\t~ Question {} ~\t\n".format(NuméroQuestion))
def Calcul2():
PremierChiffre=randint(0, NuméroQuestion*5+5)
Question=str(PremierChiffre)
for i in range(1,NuméroQuestion+1):
SigneDeCalcul=["+","*","-"]
SigneChoisi=str(choice(SigneDeCalcul))
x=str(randint(0, NuméroQuestion*5+5))
Question=Question+SigneChoisi+x
print(type(Question))
QuestionNumérique=float(QuestionNumérique)
QuestionEcrite=Question+" = "
Question=float
Réponse=input(QuestionEcrite)
NuméroQuestion=0
Raté=0
while Raté<3:
Numéro_Question()
Calcul2()
print("\n\n")
(output)
(The output changes each time you execute the program because it gives random number)
~ Question 1 ~
<class 'str'>
Traceback (most recent call last):
File "main.py", ligne 26, in <module>
Calcul2()
File "mai,.py", ligne 17, in Calcul2
QuestionNumérique=float(QuestionNumérique)
ValueError: could not convert string to float: '3*6'
It's because when you use float(my_string) it will only work if my_string can be cast as an actual float. It cannot do the multiplication for you.
Luckily, there is a very useful python function that accepts strings and runs them as code. It is called eval.
For example, eval("12 + 3") will return 15.
Just use eval instead of float, like this:
QuestionNumérique=eval(QuestionNumérique)
In summary, you want to "evaluate" (eval) the Numeric Question, not to "cast" (float) it.
A caveat: As others point out, eval is "unsafe". In general, evaluating arbitrary strings as code is unsafe.
UPDATE: I was thinking about this while eating chips earlier and I had a crazy idea.
OK, so, in Python you can execute shell commands in a subprocess and pipe the results. (os.popen - see here) . Assuming the machine running python has Bash as its shell, we can use Bash's arithmetic expression which (I think) might be easier to safeguard against arbitrary input.
Here is what it would look like:
import os
QuestionNumérique = "117 * 3 + 23 * 3"
shell_command = f"echo $(({QuestionNumérique}))"
piped_shell_result = os.popen(shell_command).read()
stripped_result = piped_shell_result.strip()
result_as_number = float(stripped_result)
This code is still dangerous! You would have to make sure the QuestionNumérique string contains "globally closed" ( and ) brackets, since someone could easily provide evil input like this:
QuestionNumérique = "117 * 3)); mkdir 'YOU HAVE BEEN H&CK3D'; echo $(("
If you can definitely make sure the input string has properly closed brackets then this should be safer than eval, since bash arithmetic expression will only do arithmetic.

Python raw_input, input and other multi-line methods fail to read std input

I"m trying to store 2 multi line inputs in 2 variables. However, std input methods keep getting hung up. I cannot change input format, but I can always expect 2 strings will be provided together. There is a new line character at the end of the first block and a new line character at the end of the second block.
I have tried several solutions from previous posts on how to accept multi line input, but none work for this case:
Store multi-line input into a String (Python)
When I try to use this code:
y input is accepted but x input is never accepted. I think the compiler is misinterpreting a line break somehow.
Any suggestions would be really appreciated.
y = input().strip()
x = input().strip()
TGGGAGGAGCAGTGATAATGCTACCTTGCTCGTGCCCCTTTAATGCCGGTGTCATCGCCTTAATGGGGTTCACAAGCAGTTACGGGGGGTCAAGTAATCATCGCGTTCGTCTTAGACGTGTCAGAGAACTAGTTTTGGAATCATTAACGACCTGCAATACTAGGTGCCAGCATAGGGTCTTTCGGAAGCACAACGTTGGAAGGCATCGCTTAGTGTAACCTAGTTACGGGAAGGCTACAGGTGCGGATGGTGGGGCCCAGCTGGGACTCAATCCAGGGACATCGGACTTTCGTTGGGGTTGAGCGGTCGCGAGGATTCGCAAGAGGGCGCCTTACAATGTTACCGTTTAGATTTACGGCCATTCCGACTTTGCAATTATTACCTTGAGCGATGCCGGCCATGCCGCGACATTATCAGTGATGTGTTCTCTCTCGGCTTGGTCGTTCAAACACGGGGCGTCATAGCTGAGTAGCCAAGGCAAACCAATTACCTACGTTCTGACCTGGCTGAATCTTGTGGAGCACCGGATCCAAGCAGTCGTGCCGGAGATTGTAGGCCAGCTTGTCATTCTGGATTGCGTTCCGCCCGATGTGAGCTTGTTCATACACCGAGTACGGGCTGCATTGGATCGTTCTATACGACAACGCTTCAGATCTCGAGTGCGTGGATCGAAGAAAGCGGAAGTCCGTTCGCGGACGCTCACAGCTGGTTGCTGCCGGCACCAACATGAACCGATCACCTAGCGCTTATAGTAAGCGGATATATCTTAGTATTAACCTTTCATTCCGGGCGGCACCTGAATGGGCAGTCTCGATTGATTAAGATCCCTTACTCTTCGAACTCGCGCGGACACGTCGTGCGCATCAATGGCAGTTATCTCGTATTAATACATACGCGTGATCAGCGCTATAGGGTATTTTTAGTTTTGGTCAACTCCGCAGTCACTGTGGATTGAATTGAGCATGCGGGCGAAGATCTGCTTTTCATCGCCTCTAACCAA
TATGGAGGACCAATGGTAGATGATACCGTTGCTCGGGGCGCTTTAAAGCCGGAGTAATGCGCCTATGAATGTGGGTTCACAGAGGAGTTCCCGGGGGGTCAACATCATCATGCGAGTGTCGTCTTAAAAGTGGCAGAATAACTGGTTTCTATGTATATCATTGAGCACCATCAATACGAGGTGTCAGCATGAGGCTCGTTCGGATGCCCGGCCTTGGAAGGCATCTGAGTTAGTATAACACTAGTTACGCGAAGGCTACAGGTGCGTGATCGTGCGGCCCAGTTGGGACTCAATTGAGGGACACGCGGACTTTCGTCGGGCTGTCAGAGGCCGGTCGGGGGAATGCGCAGGTTGTGCGGCACATACAATGTTATCGTTTCAGAATTTTATCGGCCATATCCGACTTTGCAATTATATTCCTTGCAGCGATGCCGGGGGAGCCGCGTACATGCATCAGTGTATGTATGCTCACTCGGCTATGTCGGTTCATAACCTGGCGCATATTAGCTGAGTAGACAAGGACTAAACCAATTAAACTACGTTCTGACCTCGCTATAGTATGTGAGTGAGTCACCGGATCCGAGCAGTTCGGGCCGCAGATTGGAGGCCAGCTTGTCATACTGGGTTGACCGTTTCGCCCGATGGGAGCTTGGTATCATACATCGAGTTACGTGGCTGCATTGTGTATCGTTCTGTTACGTACAACGCCTTCAAGGTCCCGAGTGCGAGGGTTCCCAGAAAAGCTGGAAGCGCAGTTCGTGAACTGCTCACAGCTGGTGGCTGCCGGCACCAACATGCACTTCGACTCACCTACCCAGCTAAATGTAAGCGCATATCTCTTAGTATATAACCTTTACATATCCGGGCGACGTACAGTAAAGAAGCAGGCTCGATGTCGTAGAGTTACCCTTACTACACTCGCAAATCGCGCGGACACGGTATGTACGCATTGAATCGACAGTTCTCTCGTATTTAGTACATACGCGTGATCAGCTGCTATAGAGTAATTCTAGCTTTGAGTGAACACCTCAGTGATGGCTGGATTGTAACTGAGCAACGCGGTCTGAGCGAACGGTTTTTGCATCGCGCTCTAACCAGG
I figured out that the problem was IDE specific. VS Code cannot accept large string input from console. No problems when using PyCharm.

Running my python code in Gitbash

I am a total newbie in programming so I was hoping anyone could help me. I am trying to write program in python that, given an integer n, returns me the corresponding term in the sylvester sequence. My code is the following:
x= input("Enter the dimension: ")
def sylvester_term(n):
""" Returns the maximum number of we will consider in a wps of dimension n
>>> sylvester_term(2)
7
>>> sylvester_term(3)
43
"""
if n == 0:
return 2
return sylvester_term(n-1)*(sylvester_term(n-1)-1)+1
Now, my questions are the following, when trying to run this in GitBash, I am asked to input the n but then the answer is not showing up, do you know what I could do to receive the answer back? I plan to continue the code a bit more, for calculating some other data I need, however, I am not sure if it is possible for me to, after coding a certain piece, to test the code and if so, how could I do it?
You will need to add:
print(sylvester_term((int(x)))
to the end of your program to print the answer.
You will need to cast to int because the Python Input() function stores a string in the variable. So if you input 5 it will return "5"
This does not handle exceptions, e.g if the user inputs a letter, so you should put it in a try and except statement.
Here's an example of how I'd handle it. You can use sys.argv to get the arguments passed via the command line. The first argument is always the path to the python interpreter, so you're interested in the second argument, you can get it like so:
sys.argv[1]
Once that is done, you can simply invoke your function like so
print(sylvester_term(int(sys.argv[1]))

Python 2.7: Handling wrong input which is not a string

I am writing a program which is supposed to contain a way of informing the user that the input for one of the variables is not a string, if entered as a name by user.
E.g. program expects a user input of any string, and if it is a string which is contained within dictionary, it will print out its value, if not, it will print out an error message.
ageofdeath.getage('JesusChrist')
33
ageofdeath.getage('John McCena')
This is not a bible character. Please enter a name of a character from the bible.
but, the program should at least throw an error message when confronted with wrong user input such as
ageofdeat.getage(JesusChrist)
ideally popping up a message along the lines of "This is not a string please input a string". Instead, no matter whether i try to use if = or isinstance, it always shows typical python name is not defined error. Is there a way of going round this or not really, as it is a default way of python shell handling the input?
Your program isn't even getting to the part where it executes your getage() method. It is failing far earlier.
You're using input() instead of raw_input(). Thus JesusChrist is taken as the name of a variable because input() evaluates what the user types as a Python expression. JesusChrist is a legal Python variable name, it just hasn't been defined, so Python tells you that. And because it knows you can't do anything with a value that doesn't exist, it stops.
Now you could catch that error by wrapping your input() in a try/except block, but that's just trying to compensate for making the wrong decision in the first place. The right answer is to use raw_input() to get input from your user and it will always be a string.

Reading user input in python 2.4, putting it into a queue

So I'm writing a differential calculator program in python 2.4 (I know it's out of date, it's a school assignment and our sysadmin doesn't believe in updating anything) that accepts a user input in prefix notation (i.e. input = [+ - * x^2 2x 3x^2 x], equivalent to x^2 + 2x - 3x^2 * x) and calculates the differential.
I'm trying to find a way to read the command line user input and put the mathematical operators into a queue, but I can't figure it out! apparently, the X=input() and x=raw_input() commands aren't working, and I can find literally 0 documentation on how to read user input in python 2.4. My question is: How do I read in user input in python 2.4, and how do I put that input into a queue? Here is what I am trying:
1 formula = input("Enter Formula:")
2
3 operatorQueue=[]
4
5 int i = len(formula)
6
7 for x in formula:
8 if formula[x] == '*', '+', '-', '/':
9 operatorQueue.append(formula[x])
0
11 print "operator A:", operatorQueue.pop(0)
12
Which is not working (I keep getting errors like "print: command not found" and "formula:command not found")
Any help would be appreciated
#miku already answered with this being your initial problem, but I thought I would add some more.
The "sh-bang" line is required by command line scripts so that the proper process is used to interpret the language, whether it be bash, perl, python,etc. So in your case you would need: /usr/bin/env python
That being said, once you get it running you are going to hit a few other issues. raw_input should be used instead of input, because it will give you back a raw string. input is going to try and eval your string which will mostly likely give you problems.
You may need to review python syntax a bit more. Assignments in python don't require that you declare the variable type: int a = 1. It is dynamic and the compiler will handle it for you.
Also, you will need to review how to do your if elif else tests to properly handle the cases of your formula. That too wont work doing it all on one line with multiple params.
If you're on a unix-ish platform, put a
#!/usr/bin/env python
on top of your program. The shell does not seem to recognize that you are running a python script.

Categories