CoCalc Public Fileslab 8.ipynb
Views : 80
Compute Environment: Ubuntu 18.04 (Deprecated)
In [19]:
def wordcount(fname):
try:
fobj = open(fname, 'r')
text = ''
words = []
words = text.split()
length = 0
length = len(words)
except FileNotFoundError:
length = -1
return(length)

wordcount('lab.txt')


7
In [ ]:

try:
x = int(input("Enter a number"))
z = 2/x
print("Good job, no errors")
except ValueError:
print("Input was not an integer, setting z to -1")
z = -1
except ZeroDivisionError:
print("Can't divide by 0, setting z to -2")
z = -2
print(z)

In [53]:
import random

def make_data(fname):
fobj = open(fname, 'w')
for i in range(0,1000):
num1= str(i)
num2= str(random.randint(-1000, 1000))
num3= num1 + "," + num2 + "\n"
fobj.write(num3)

make_data('dog.txt')


In [57]:
def read_data(fname):
min_num = 0
max_num = 0
try:
fobj = open(fname, 'r')
except FileNotFoundError:
for line in fobj:
nums = []
nums = line.split(',')
num = nums[1]
int_num = int(num)
if int_num < min_num:
min_num = int(nums[1])
if int_num > max_num:
max_num = int(nums[1])
print(min_num,"\n", max_num)


'\ndef read_data(fname):\n min_num = 0\n max_num = 0\n try:\n fobj = open(fname, \'r\')\n except FileNotFoundError:\n print("Bad file name")\n for line in fobj:\n nums = []\n nums = line.split(\',\')\n num = nums[1]\n int_num = int(num)\n if int_num < min_num:\n min_num = int(nums[1])\n if int_num > max_num:\n max_num = int(nums[1])\n print(min_num,"\n", max_num)\nread_data("dog.txt")\n'
In [64]:
def stock_data(fname):
min_num = 0
max_num = 0
total = 0
mean = 0
median = 0
try:
fobj = open(fname, 'r')
except FileNotFoundError:
for line in fobj:
nums = []
nums = line.split(',')
max_stock = int(nums[2])
min_stock = int(nums[3])
if min_stock < min_num:
min_num = int(nums[3])
if max_stock > max_num:
max_num = int(nums[2])
for i in fobj:
total += int(i[1])
mean = (total / len(fobj))
print(min_num,"\n", max_num,"\n",mean)

--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-64-7002a87c76d6> in <module> 22 mean = (total / len(fobj)) 23 print(min_num,"\n", max_num,"\n",mean) ---> 24 read_data("AMZN.csv") <ipython-input-54-ba3e9be323cc> in read_data(fname) 10 nums = line.split(',') 11 num = nums[1] ---> 12 int_num = int(num) 13 if int_num < min_num: 14 min_num = int(nums[1]) ValueError: invalid literal for int() with base 10: 'Open'