So im trying to make a code that takes an number input from the user and with that input it will display a x number of other inputs to fill in data to be writed it down on a .txt file. But i can’t really make it stop showing even with a if x > f: break.
Im still learning python and got this far with my little project.
f = file.write(input("Probes:"))
if f == 1:
file.write(" One Single Soil Probe")
else:
file.write(" Multiple Soil Probes")
file.write(" \n")
# System
x = 1
for a in range(f):
file.write("SP" + str(x) + ": ")
file.write(input("SP " + str(x) + ": " + " \n"))
file.write("m")
x = x + 1
if f > x:
break
else:
continue
file.write(" \n")
file.close()
>Solution :
There are a number of issues with the code as presented.
First of all, while file.write may return a number, it’s not a useful number in this context: it returns the number of bytes written to the file. SO that’s the first change you need to make.
f = input("Probes:")
Howewver, input returns a string, so we need to convert that to a number. If we ignore error checking, it’s quite simple:
f = int(input("Probes:"))
Now we’ve lost the file.write call, so we need to add that back in. However, file.write takes a string:
f = int(input("Probes:"))
file.write(str(f))
The next bit is OK now:
f = int(input("Probes:"))
file.write(str(f))
if f == 1:
file.write(" One Single Soil Probe")
else:
file.write(" Multiple Soil Probes")
file.write(" \n")
Next we have your processing loop. You really shouldn’t be combining reads and writes like that, it makes it difficult to understand what’s going on. I’d re-write it something like this:
for a in range(f):
sp_val = input("SP " + str(a+1) + ": " + " \n")
file.write("SP" + str(a+1) + ": " + sp_val + "m\n")
file.write(" \n")
file.close()
Then there’s a couple of tricks you can use to make it even cleaner. First is the with statement, secondly is fstrings:
with open(filename) as file:
f = int(input("Probes:"))
file.write(str(f))
for a in range(f):
sp_val = input(f"SP {a+1}: \n")
file.write(f"SP{a+1}: {sp_val}m\n")
file.write(" \n")
The final point I’d make is to rename some of the variables to make it clearer what they do, and to avoid hiding builtin functions:
with open(filename) as ouput_file:
probe_num = int(input("Probes:"))
ouput_file.write(str(probe_num))
for a in range(probe_num):
sp_val = input(f"SP {a+1}: \n")
ouput_file.write(f"SP{a+1}: {sp_val}m\n")
ouput_file.write(" \n")