Creating a calculator

Chris Warrick kwpolska at gmail.com
Fri Jul 1 07:39:39 EDT 2016


On 1 July 2016 at 11:34, Pierre-Alain Dorange
<pdorange at pas-de-pub-merci.mac.com> wrote:
> DFS <nospam at dfs.com> wrote:
>
>> Here's a related program that doesn't require you to tell it what type
>> of operation to perform.  Just enter 'num1 operator num2' and hit Enter,
>> and it will parse the entry and do the math.
>>
>> -----------------------------------------------
>> ui=raw_input('Enter calculation to perform: ')
>> n1=float(ui.split(' ')[0])
>> op=ui.split(' ')[1]
>> n2=float(ui.split(' ')[2])
>> if op=='+':c=n1+n2
>> if op=='-':c=n1-n2
>> if op=='*':c=n1*n2
>> if op=='/':c=n1/n2
>> print(ui+' = '+str(c))
>> -----------------------------------------------
>
> More reduced :
> ----------------------------------
> u=raw_input('Enter calculation:")
> print eval(u)
> ----------------------------------
> works and compute :
> 1+2+3+4-1+4*2
> 2+3.0/2-0.5
>
> Perform better and shorter, but less educationnal of course...

No, this is awful. It’s a great way to compromise your system’s
security. Never use eval() for any reason, especially with user input
— if you were to type in __import__('os').system('…') with some
particularly dangerous command (rm, format, …), you would kill your
system.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16



More information about the Python-list mailing list