.ctime()
function to display the current time in human-readable form.
Fri Dec 27 13:10:51 2019
import time print(time.time()) print(time.ctime())
try - except
block on the division, to trap any errors.
$ ./q-try-ratio.py first number? 12 second number? 13 12.000000 / 13.000000 equals 0.923077 $ ./q-try-ratio.py first number? 12 second number? 0 Error: float division by zero $ ./q-try-ratio.py first number? 0 second number? 0 Got exception -->float division by zero<-- $
#!/usr/bin/env python3 x = float(input('first number? ')) y = float(input('second number? ')) try: z = x / y print('{:f} / {:f} = {:f}'.format(x, y, z)) except Exception as e: print('Got exception -->{}<--'.format(e)) #--------
average3()
that accepts three numbers, and returns their average.
Then write a simple program that includes the function, uses it to calculate an average, and displays the result. The program can get three numbers from the user, or just "hardcode" three numbers, whichever you prefer. The point is to demonstrate the use of the function.
answer = average3(17, -3.5, 8) print(answer) 7.166666666666667
#!/usr/bin/env python3 def average3(x, y, z): return (x + y + z) / 3 #-------- a = float(input('first number? ')) b = float(input('second number? ')) c = float(input('third number? ')) avg = average3(a, b, c) print('Average of {}, {}, {} equals {}'.format(a,b,c, avg))
Next string? hello, world Next string? goodbye, earth Next string? stop, I want to get off. Next string? ... and blah blah blah... Next string? ['hello, world', 'goodbye, earth', 'stop, I want to get off.', '... and blah blah blah...']
Then write a simple program that includes the function and uses it. Display the resulting dictionary.
cd = make_char_dict(result) print(cd) {'h': 5, 'e': 4, 'l': 6, 'o': 7, ',': 3, ' ': 11, 'w': 2, 'r': 2, 'd': 3, 'g': 2, 'b': 4, 'y': 1, 'a': 6, 't': 5, 's': 1, 'p': 1, 'I': 1, 'n': 2, 'f': 2, '.': 7} for c, v in cd.items(): print(c, v) h 5 e 4 l 6 o 7 , 3 11 w 2 r 2 d 3 g 2 b 4 y 1 a 6 t 5 s 1 p 1 I 1 n 2 f 2 . 7
#!/usr/bin/env python3 def question1(strings): chars = {} for s in strings: for c in s: if c not in chars: chars[c] = 0 chars[c] += 1 return chars #--------
$ python echo-cmdline.py a bc def ghij klmno pqrst uvwxyz uvwxyz pqrst klmno ghij def bc a echo-cmdline.py
#!/usr/bin/env python3 # Multiple solutions for command-line arguments question import sys # (1) use a loop - naive approach mylist = [] for a in sys.argv: mylist.append(a) for i in range(len(mylist)-1, -1, -1): print(mylist[i]) print('#----') # (2) list comprehension copy, reverse-index printing mylist = [ a for a in sys.argv ] for a in mylist[::-1] : print(a) print('#----') # (3) slicing operation copy, reverse-index printing mylist = sys.argv[:] for a in sys.argv[::-1] : print(a) print('#----') # (4) not a copy, just an "alias" name - not even needed mylist = sys.argv for a in sys.argv[::-1] : print(a) print('#----')