1. INPUT through functions - Rakhmanov
[Pages:8]1. INPUT through functions
In [1]: C = input('C=?') C = float(C) F = (9./5)*C + 32 print (F)
C=?24 75.2
What is the difference between upper and lower program?
In [3]: C = float(input('C=?')) F = (9./5)*C + 32 print (F)
C=?24 75.2
EVAL function
In [6]: r = eval('1+2') r
Out[6]: 3
In [7]: a='1' b='2' c=eval(a+b) c
Out[7]: 12
In [8]: from math import sqrt r = eval('sqrt(2)') r
Out[8]: 1.4142135623730951
In [10]:
# Perimeter of Square def calculatePerimeter(l):
return 4*l
# Area of Square def calculateArea(l):
return l*l
expression = input("Type a function: ")
for l in range(1, 5): if (expression == 'calculatePerimeter(l)'): print("If length is ", l, ", Perimeter = ", eval(expression)) elif (expression == 'calculateArea(l)'): print("If length is ", l, ", Area = ", eval(expression)) else: print('Wrong Function') break
Type a function: calculateArea(l) If length is 1 , Area = 1 If length is 2 , Area = 4 If length is 3 , Area = 9 If length is 4 , Area = 16
EXEC
In [11]: program = 'a = 5\nb=10\nprint("Sum =", a+b)' exec(program)
Sum = 15
In [12]:
a = 5 b=10 print("Sum =", a+b)
Sum = 15
In [ ]:
program = input('Enter a program:') exec(program)
# [print(item) for item in [1, 2, 3]]
From String to code We need to install Scitools with: pip install scitools3
In [13]: from math import *
def f2(x): return exp(x)*sin(x)
In [14]: f2(2) Out[14]: 6.71884969742825
In [15]:
from scitools.StringFunction import StringFunction formula = 'exp(x)*sin(x)' f = StringFunction(formula)
# turn formula into function f(x)
In [16]: f(2) Out[16]: 6.71884969742825
2. Command line input
Cretae following programs and test through prompt
In [ ]:
# one input import sys C = float(sys.argv[1]) F = 9.0*C/5 + 32 print (F)
In [ ]:
import sys t = float(sys.argv[1]) v0 = float(sys.argv[2]) g = 9.81 y = v0*t - 0.5*g*t**2 print (y)
Error handling
In [18]:
C = float(input('Enter degree Celsium:')) F = 9.0*C/5 + 32 print (F)
Enter degree Celsium:5 41.0
In [19]:
try: C = float(input('Enter degree Celsium:'))
except: print ('You failed to provide Celsius degrees as input on the command line!') sys.exit(1) # abort
F = 9.0*C/5 + 32 print ('%gC is %.1fF' % (C, F))
Enter degree Celsium:we You failed to provide Celsius degrees as input on the command line!
---------------------------------------------------------------------------
ValueError
Traceback (most recent call last)
in
1 try:
----> 2
C = float(input('Enter degree Celsium:'))
3 except:
ValueError: could not convert string to float: 'we'
During handling of the above exception, another exception occurred:
NameError
Traceback (most recent call last)
in
3 except:
4
print ('You failed to provide Celsius degrees as input on the co
mmand line!')
----> 5
sys.exit(1) # abort
6
7 F = 9.0*C/5 + 32
NameError: name 'sys' is not defined
In [ ]:
try: C = float(input('Enter degree Celsium:'))
except IndexError: print ('Celsius degrees must be supplied on the command line') sys.exit(1) # abort execution
except ValueError: print ('Celsius degrees must be a pure number, not "%s"' % C) sys.exit(1)
F = 9.0*C/5 + 32 print ('%gC is %.1fF' % (C, F))
examples of Errors in python
In [23]:
data = [1.0/i for i in range(1,10)] data[we]
---------------------------------------------------------------------------
NameError
Traceback (most recent call last)
in
1 data = [1.0/i for i in range(1,10)]
----> 2 data[we]
NameError: name 'we' is not defined
In [24]: C = float('21 C')
---------------------------------------------------------------------------
ValueError
Traceback (most recent call last)
in
----> 1 C = float('21 C')
ValueError: could not convert string to float: '21 C'
In [25]:
forr d in data: return data
File "", line 1 forr d in data: ^
SyntaxError: invalid syntax
3. Interface
In [26]: import tkinter tkinter._test()
In [27]:
from tkinter import * root = Tk() C_entry = Entry(root, width=4) C_entry.pack(side='left') Cunit_label = Label(root, text='Celsius') Cunit_label.pack(side='left')
def compute(): C = float(C_entry.get()) F = (9./5)*C + 32 F_label.configure(text='%g' % F)
compute = Button(root, text=' is ', command=compute) compute.pack(side='left', padx=4)
F_label = Label(root, width=4) F_label.pack(side='left') Funit_label = Label(root, text='Fahrenheit') Funit_label.pack(side='left')
root.mainloop()
Modules
Assume I am depositing money to bank. Following are the fowmulas used to calculate annual interest.
= (1 + ) Amount to return:
0
360100
Following formulas can be derived from upper formula:
= (1 + ) 0 Initial ammount needed: = Number of days needed:
= 360 100 (( ) - 1) Rate needed:
-
ln(1l+n03600110306)0100
You can answer question like what should be initial ammount to get back so so amount? How many days it should be deposited? What should be annual rate?
In [28]: from math import log as ln def present_amount(A0, p, n):
return A0*(1 + p/(360.0*100))**n def initial_amount(A, p, n):
return A*(1 + p/(360.0*100))**(-n) def days(A0, A, p):
return ln(A/A0)/ln(1 + p/(360.0*100)) def annual_rate(A0, A, n):
return 360*100*((A/A0)**(1.0/n) - 1)
In [29]: x=initial_amount(12000,5,1000) x Out[29]: 10443.997433188539
Now assume that you have many formulas like this, and everyone in the bank need to use them. Moreover, you need to update them frequently. What is the solution?
Form a file named interest.py
In [30]: import interest
In [31]: interest.days(10450,12000,5) Out[31]: 995.8627846505938
In [33]: A0 = 10450; A = 12000; p = 5 n = interest.days(A0, A, p) years = n/365.0 print ('Money should reach your desired level after %.1f years' % years)
Money should reach your desired level after 2.7 years
In [34]: from interest import annual_rate
In [35]:
annual_rate(10450,12000,2.7*365)
Out[35]:
5.0525799686598205
Now try interest.py on command line. It won't give you anything.
We need to convert it to executable program
In [ ]:
if __name__ == '__main__': A = 2.2133983053266699 A0 = 2.0 p = 5 n = 730 print ('A=%g (%g)\nA0=%g (%.1f)\nn=%d (%d)\np=%g (%.1f)' % \ (present_amount(A0, p, n), A, initial_amount(A, p, n), A0, days(A0, A, p), n, annual_rate(A0, A, n), p))
Now it can work both as module and executable program.
Checking the module
In [36]:
from interest import * dir()
Out[36]:
['A', 'A0', 'ACTIVE', 'ALL', 'ANCHOR', 'ARC', 'BASELINE', 'BEVEL', 'BOTH', 'BOTTOM', 'BROWSE', 'BUTT', 'BaseWidget', 'BitmapImage', 'BooleanVar', 'Button', 'C', 'CASCADE',
Chapter 3.6 Review , Chapter 3.7 Exercises
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- программирования Урок 10 python основы
- chapter 1 meet tkinter
- programiranje 2 tkinter
- python for practice nprg067 cz
- an introduction to python programming and gui design using
- journeyman reference v3d 082918a wikipython
- the irobot create 2 raspberry pi camera web
- an introduction to tkinter
- python for practice nprg067
- 1 input through functions rakhmanov
Related searches
- personality types 1 through 9
- personality test 1 through 9
- number generator 1 through 20
- biblical numbers 1 through 1000
- roman numerals 1 through 10
- 1 through 12 multiplication worksheets
- random number 1 through 5
- the amendments 1 through 27
- pick a number 1 through 7
- 2 1 relations and functions worksheet
- random number 1 through 3
- pick a number 1 through 11