I tried to use the last part of the code but it doesn't work it just says false there might be some errors and if your wondering i have a txt file with names
import string
string.ascii_letters
'abcdefghijklmnOpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
import random
letter = random.choice(string.ascii_letters)
print(letter)
file = open("names.txt")
found = [] #Result will Store
for m in file:
if m.startswith(letter): #It will check if the input value match with from begining of the signl world
found.append(m) # Store the value if match
for f in found:
print("\n" f)
print("Total Words is " str((len(found))))
rika = input("name: ")
print(rika in found)
CodePudding user response:
I did an example, where names.txt contains:
- Thomas
- Peter
- Jens
Your Code:
import string, random
letter = random.choice(string.ascii_letters)
print(letter)
with open("names.txt") as file:
found = [] #Result will Store
for m in file:
if m.startswith(letter): #It will check if the input value match with from begining of the signl world
found.append(m.strip()) # Store the value if match, remember to strip newline
for f in found:
print("\n" f)
print("Total Words are " str(len(found)))
if found:
rika = input("name: ")
print(rika if rika in found else "Not found")
Result:
J
Jens
Total Words is 1
name: Jens
Jens
I changed your file handling and open it using a context manager, in that way it will automatically close the file after using it. I also checked if found contain any data before asking for input.