One of the skills I am trying to learn is nested commands in Python as I am learning Python being a newbie. As such I have come up with this code. I am not sure what the mistake is. Here is the code:
file = open ("C:\\Users\\text.txt", "r")
print(file.read())
while True:
content=file.readline()
if not content:
break
return int(content.find(str(i)) for i in range (10))
The error I am getting is
SyntaxError: 'return' outside function
Despite the obvious, I cannot find where my error is. Some help please!
From reading each line of the file to return every number it finds on that line, whether that number is in between the word or standing alone.
Assuming that what you're trying to do is read a text file, iterate through each line of this file, find all numeric values that exist on each line and return those numbers that were found, you can consider using regex.
Option 1: finding both floats and integers
If you're trying to find both whole numbers (e.g., 1, 2, 3, ...) and fractions (e.g., 3.2, 5.15, 1.2345), you could write something like this:
Example
Assuming your text file looks like this:
The above solution would return the following list of numbers:
Option 2: Finding only whole numbers
If instead you're trying to find only whole numbers, replace the variable
patterndefined inside thefind_numeric_valuesfunction to this:For the text file from the previous example, now the final output would be instead:
Option 3: Finding single-digit numbers
If you're trying to extract from text numbers as single digit values, you could change the variable
patterntopattern = r'(\d)'(no+sign at the end).Making this change would return the following list:
Notes
What's wrong with your original code
The error you're having occurs because you're trying to use a
returnstatement outside amethodor afunction. To use areturnstatement you would need to move some of your code to a function and call it inside yourwhile..loop. For example:Bear in mind that the above code will only stop raising the exception you've mentioned in your question. It won't however achieve your desired output.
Use
withstatement when reading a text fileInstead of using
file = open("C:\\Users\\text.txt", "r"), it's always a good idea to use thewithstatement for opening files.The
withstatement ensures that resources are properly managed. When the block under thewithstatement is exited, the file is automatically closed, even if an exception is raised inside the block. This automatic management helps prevent file leaks, where files might remain open if an error occurs before theclose()method is called.In other words, instead of writing something like:
You should consider writing it like this: