In: Computer Science
The question: Write a program in Python that writes four random integers in range 1-100 on a file named 'num.txt'. Write try-except block to handle at least two standard python error (any two errors).
Hints: import random def main(): # Local variables # Open output file. # Write random numbers to the file. # Write it on to the file. # Close the file. # Call the main function. main()
Here is my answer: please let me know if anything is wrong with it. thanks
"
import random
# define the min and max of the random numbers
min = 1
max = 100
def main():
#get four random numbers from 1 to 100 or min to max
number1 = random.randint(min,max)
number2 = random.randint(min,max)
number3 = random.randint(min,max)
number4 = random.randint(min,max)
#write TRY/EXCEPT statment
try:
#OPEN a file named num.txt
outfile = open('num.txt', 'w')
#WRITE the random numbers to the file
outfile.write(str(number1) + '\n')
outfile.write(str(number2) + '\n')
outfile.write(str(number3) + '\n')
outfile.write(str(number4) + '\n')
#PRINT the numbers
print(number1)
print(number2)
print(number3)
print(number4)
#write TRY/EXCEPT statment
except ValueError as err:
print(err)
except IOError:
print("An error occured trying to read the file.")
except KeyboardInterrupt:
print("Something went wrong when writing to the file.")
except:
print("An error occured.")
finally:
outfile.close()
#call the function
main()
"
Here is the answer..
CODE:
import random
# define the min and max of the random numbers
min = 1
max = 100
def main():
#get four random numbers from 1 to 100 or min to max
number1 = random.randint(min,max)
number2 = random.randint(min,max)
number3 = random.randint(min,max)
number4 = random.randint(min,max)
#write TRY/EXCEPT statment
try:
#OPEN a file named num.txt
outfile = open('num.txt', 'w')
#WRITE the random numbers to the file
outfile.write(str(number1) + '\n')
outfile.write(str(number2) + '\n')
outfile.write(str(number3) + '\n')
outfile.write(str(number4) + '\n')
#PRINT the numbers
print(number1)
print(number2)
print(number3)
print(number4)
#write TRY/EXCEPT statment
except ValueError as err:
print(err)
except IOError:
print("An error occured trying to read the file.")
except KeyboardInterrupt:
print("Something went wrong when writing to the file.")
except:
print("An error occured.")
finally:
outfile.close()
#call the function
main()
output:
When we press ctrl+c
if you have any doubts please COMMENT...
I think there are no errors in your code.if you didn't get output please check indentation
If you understand the answer please give THUMBS UP...