Creating a calculator
Pierre-Alain Dorange
pdorange at pas-de-pub-merci.mac.com
Fri Jul 1 05:34:40 EDT 2016
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...
--
Pierre-Alain Dorange Moof <http://clarus.chez-alice.fr/>
Ce message est sous licence Creative Commons "by-nc-sa-2.0"
<http://creativecommons.org/licenses/by-nc-sa/2.0/fr/>
More information about the Python-list
mailing list