Reputation: 25
Anyone can please check my code?
When the user inputs exactly 4 digits, check whether the inputted number appears in the first 10,000 characters (after the decimal) of the text file(which name is "square root of 2.txt") and tell the user its position using .find() method.
Make a new file called inputted_number.txt. Modify the code so that all the valid input is saved in that file. The contents of that file should look something like this:
3210
3222
4771
I don' know how to use re.find(), is that re.search? My codes below:
#import my file
myfile = open("sqroot2_10kdigits.txt")
txt = myfile.read()
myfile.close()
# while True block use re.find
while True:
try:
number = str(input("Enter four digits: "))
int(number)
if re.findall(r'\d\d\d\d',txt)) == True:
print(f'The digits {int(number} appear in the first 10,000 characters of the square root of 2.' )
print(f'They appear starting on the {starting position}th character after the decimal.' )
else :
print(f'Sorry, the digits {int(number)} do not appear in the first 10,000 characters of the square root of 2.')
#NO.5 make a new file
with open('inputted_number.txt.', 'w') as filehandle:
filehandle.write('\n')
Anyone can check my code please!
Upvotes: 0
Views: 65
Reputation: 660
For what you are describing you do not need a regex.
txt = '2319871325876234897034589734527861' \
'3098623409862349856243598672354897' \
'2348776623534078459996505467097201'
while True:
number = input("Enter four digits (q to quit): ")
if number.lower() == 'q':
break
elif len(number) != 4 or not number.isdigit():
print("Please enter four numbers")
continue
pos = txt.find(number)
if pos > -1:
print(
f'The digits {number} appear in the first '
'10,000 characters of the square root of 2.'
f'They appear starting on the {pos}th '
'character after the decimal.'
)
else:
print(
f'Sorry, the digits {number} do not appear '
'in the first 10,000 characters of the '
'square root of 2.'
)
Among the changes:
Upvotes: 1