File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ #!/usr/bin/python3
2+
3+ def num (ip ):
4+ if type (ip ) in (int , float ):
5+ return ip
6+ elif type (ip ) != str :
7+ raise TypeError ('provide only string input' )
8+
9+ try :
10+ return int (ip )
11+ except ValueError :
12+ try :
13+ return float (ip )
14+ except ValueError :
15+ raise ValueError ('could not convert string to int or float' )
16+
17+ assert num (3 ) == 3
18+ assert num (0x1f ) == 31
19+ assert num (0b101 ) == 5
20+ assert num (0o10 ) == 8
21+ assert num (3.32 ) == 3.32
22+ assert num ('123' ) == 123
23+ assert num ('-78' ) == - 78
24+ assert num (" 42 \n " ) == 42
25+ assert num ('3.14' ) == 3.14
26+ assert num ('3.982e5' ) == 398200.0
27+ s = '56'
28+ assert num (s ) + 44 == 100
29+ s = '8' * 10
30+ assert num (s ) == 8888888888
31+
32+ try :
33+ assert num ('foo' )
34+ except ValueError as e :
35+ assert str (e ) == 'could not convert string to int or float'
36+
37+ try :
38+ assert num (['1' , '2.3' ])
39+ except TypeError as e :
40+ assert str (e ) == 'provide only string input'
41+
42+ print ('all tests passed' )
You can’t perform that action at this time.
0 commit comments