Why won't it write to the file? - python-3.x

So I have the code:
def logdata(x, y):
try:
f = open('multlog.txt', 'a')
f.write("{0:g} * {1:g} = {2:g}\n".format(x,y, (x*y)))
except ValueError:
f.write("Error, you tried to multiply by something that wasn't a number")
raise
finally:
f.close()
print("This is a test program, it logs data in a text file, 'multlog.txt'")
fn = input("Enter the first number you'd like to multiply by: ")
sn = input("Enter the second number you'd like to multiply by: ")
logdata(int(fn), int(sn))
And what I want it to do, is when it reaches a value error, for it to write to the file,"Error, you tried to multiply by something that wasn't a number". But, if the file reaches a value error if the user inputs a letter, say "j",ValueError: invalid literal for int() with base 10: 'j', it doesn't write to the file!

At least two problems:
The file is not open for writing (or appending) in the except block.
As #DSM points out in a comment, the ValueError is being raised when you call int()
I would rewrite to something like the below example.
If you use the with statement then you can do without the finally block.
def logdata(x, y):
with open('multlog.txt', 'a') as f:
try:
x = int(x); y = int(y)
f.write("{0:g} * {1:g} = {2:g}\n".format(x,y, (x*y)))
except ValueError:
f.write("Error")
print("This is a test program, it logs data in a text file, 'multlog.txt'")
fn = input("Enter the first number you'd like to multiply by: ")
sn = input("Enter the second number you'd like to multiply by: ")
logdata(fn, sn)

Related

TypeError: string indices must be integers --> Python

I wanted to create a python function which should read each
character of a text file and then count and display
the occurrence of alphabets E and T individually (including
small cases e and t too).
def test():
f = open("poem.txt",'r')
count = 0
count1 =0
try:
line = f.readlines()
for i in line:
for x in line:
if (i[x] in 'Ee'):
count+=1
else:
if (i[x] in 'Tt'):
count1+=1
print("E or e",count)
print("T or t",count1)
except EOFError:
f.close()
test()
This is what I tried
And it gave :
File "/Users/ansusinha/Desktop/Tution/Untitled15.py", line 23, in test
if (i[x] in 'Ee'):
TypeError: string indices must be integers
What am I missing here?
You are missing the fact that Python strings come with a .count() method.
You can read the entire file with
file_as_string = f.read()
and then count occurrences of any substring with
amount_of_E = file_as_string.count('E')
Check out str.count in Python documentation.
With
amount_of_Ee = file_as_string.lower().count('e')
you count occurrences of both E and e and with
amount_of_Tt = file_as_string.lower().count('t')
you are done with counting using two lines of code.
In your own code you try to index a string with another string, but string indices must be integers.
With for x in line: you actually wanted for x in i: where then the x will be a single character of line i you could directly use in if x in 'eE':.
But there is no need for the loops at all as Python strings come with the .count() method, so just use it.
Because, f.readlines() does not read only line, it reads all lines.
Code should be like this
def test():
f = open("poem.txt",'r')
count = 0
count1 =0
try:
lines = f.readlines()
for line in lines:
for char_in_line in line:
if (char_in_line in 'Ee'):
count+=1
elif (char_in_line in 'Tt'):
count1+=1
print("E or e",count)
print("T or t",count1)
except EOFError:
f.close()
test()
If your poem.txt is this,
LaLaLa
I'm shoes.
Who are you?
Then i[x] should be like this i["LaLaLa"]

The code works incorrectly and displays incomprehensible numbers:

The code works incorrectly and displays incomprehensible numbers:
3.612432554629948e + 76
Displays incomprehensible values,it should be like this:
And should output:
A large number for example:
HEX: 8459f630cd86ddfa329b3d13d5217d45df1d5e9a56a63f6a3d7ab8b794c35c12
DEC: 59864244547079690871082685810675850360550404961977540588162601013229404773394
# Covert a file with lines of hex values in "hex.txt" to decimal
# values and write to "dec.txt"
# NOTE: This program only handles Value errors and replaces them
# with the string XXXXX, no other error handling is performed
HEXLIST_FILENAME = "hex.txt"
DECLIST_FILENAME = "dec.txt"
def loadHex():
"""
Returns a list of Hex strings from a file
"""
hexList = []
print ("Loading hex list from file...")
try:
inFile = open(HEXLIST_FILENAME, 'r')
except IOError:
print('No such file "hex.txt"')
#more error handeling here
for line in inFile:
hexList.append(line.strip().upper())
print (len(hexList)), "Numbers loaded."
return hexList
def hexToDec(hexString):
"""
Takes in a string representing a hex value
Returns a decimal number string
"""
try:
i=int(hexString,16)
except ValueError:
print('Oops! There was an invalid number in hex.txt...')
print('Invalid number replaced with XXXXX')
i='XXXXX'
return str(i/float(2**21))
def exportDec(decList):
"""
"""
outFile=open(DECLIST_FILENAME,'w')
for num in decList:
outFile.write(num+"\n")
outFile.close()
print ("Success! Decimal numbers written to dec.txt")
decList = []
hexVals=loadHex()
for hexnum in hexVals:
decList.append(hexToDec(hexnum))
exportDec(decList)
s=input()('Press Enter to exit...')
Not sure why you are dividing the converted value by 2**21 in your hexToDec method:
return str(i/float(2**21))
The division is unnecessary and you would get the correct output if you just
return str(i)
directly from your hexToDec method.

In Python 3.x, how to read any number then return half of the number?

I want to ask the user to enter a number which can be float, integer and complex number, but Python 3 considers it as string if I use the input function. If I don't know what type of number the user will enter, how do I calculate the half of the input number?
You can use ast.literal_eval to safely interpret strings as though they were Python literals:
from ast import literal_eval
print(type(literal_eval("1"))) # <class 'int'>
print(type(literal_eval("1.0"))) # <class 'float'>
print(type(literal_eval("1+1j"))) # <class 'complex'>
I would parse it as complex, then only print out the real part if the imaginary part is zero:
try:
num = complex(input('Enter something: '))
except ValueError:
print('Invalid input')
if num.imag:
print(num / 2)
else:
print(num.real / 2)
Another option is a nested try-except:
num = input('Enter something: ')
try:
print(int(num) / 2)
except ValueError:
try:
print(float(num) / 2)
except ValueError:
try:
print(complex(num) / 2)
except ValueError:
print('Invalid input')

While calculating median I am getting run time error for all the test cases in python 3

# Enter your code here. Read input from STDIN. Print output to STDOUT
from statistics import median
a=str(input())
l=a.split(' ')
for i,v in enumerate(l):
l[i]=float(v)
print('%.9f'%median(l))
Try with some data validation to check the error,
# Enter your code here. Read input from STDIN. Print output to STDOUT
from statistics import median
a = str(input('Enter the series of values - '))
try:
l = [float(value.strip()) for value in a.split(' ') if value.strip()]
except Exception as error:
print('Error while float conversion - {}'.format(error))
l = []
if l:
print('%.9f' % median(l))
else:
print('Enter valid inputs.')

Python 3: Checking for the length and data type. & Error Fix

I am having some problems with my project:
With the code I currently have, I am getting an error:
Traceback (most recent call last):
File "\Username\Folder\Folder2\design2.py", line 13, in <module>
elif numberplate3.isaplha():
AttributeError: 'str' object has no attribute 'isaplha'
Here is the code:
while True:
import time
numberplate1 = str(input("Enter in the first 2 letters of the numberplate"))
if numberplate1.isalpha():
print("Verification 1 Success")
numberplate2 = str(input("Enter in the next 2 chars of the numberplate"))
if numberplate2.isdigit():
print("Verification 2 Success")
numberplate3 = str(input("Enter the last 3 digits of the numberplate"))
if numberplate3.isdigit():
print("Verification 3 Fail")
break
elif numberplate3.isaplha():
print("Verification Passed")
start
elif numberplate2.isalpha():
print("Verification 2 Failed")
break
elif numberplate1.isdigit():
print("Return to the start")
break
start = time.time()
inp = input("Please press enter when car has left monitoring area\n>")
end = time.time()
print("Car took {:.2f} seconds ".format(end-start))
print("Car travelled at {:.2f} m/s. ".format(200/(end-start)))
The program will check the format of a numberplate, but I would also like for it to check for the length too. (It checks to see if it has a letter, number etc, but it needs to check for the length on each check)
If possible, a program that checks for the numberplate format would really help.
Checking for LETTER-LETTER-NUMBER-NUMBER LETTER-LETTER-LETTER (AB12 CDE) If not, I am fine with help on my current program
Thanks
Your first problem is just a typo: You misspelled 'isaplha'; it should be 'isalpha'.
For your other question: You can make your program a whole lot simpler by using a regular expression for matching the number plate, like this:
import re
while True:
numberplate = input("Enter the numberplate: ").lower()
if re.match("[a-z]{2}[0-9]{2}[a-z]{3}", numberplate):
print("Verification Success")
break
else:
print("Verification Failed")
Here, the regular expression "[a-z]{2}[0-9]{2}[a-z]{3}" means "two letters, two digits, three letters".

Resources