Skip to content

Instantly share code, notes, and snippets.

@mayankdawar
Created March 16, 2020 10:21
Show Gist options
  • Save mayankdawar/213eaa9d9db42a9c7be5e60402a7a140 to your computer and use it in GitHub Desktop.
Save mayankdawar/213eaa9d9db42a9c7be5e60402a7a140 to your computer and use it in GitHub Desktop.
Create a string called first_forty that is comprised of the first 40 characters of emotion_words2.txt.
#Create a string called first_forty that is comprised of the first 40 characters of emotion_words2.txt.
file = open("emotion_words2.txt","r")
const = file.read()
first_forty = const[:40]
@hadrocodium
Copy link

hadrocodium commented Apr 10, 2023

#Create a string called first_forty that is comprised of the first 40 characters of emotion_words2.txt.

# This breaks from the inner loop to the outer loop and from there immediately breaks outside the whole thing.
# To achieve this I used if-statement, exit_variable which contains a Boolean value that is changed to True once we get the first 
# forty characters, and of course break statement.
# The if statement along with exit_variable is immediately before the inner loop, so the break statement inside the if-statement exits the outermost loop.

count = 0
exit_variable = False
first_forty = ''

with open('emotion_words2.txt', 'r') as file_ref:
    for line in file_ref:
        line = line.strip()
        if exit_variable:
            break 
        for char in line:
            count += 1
            if count == 41:
                exit_variable = True
                break
            first_forty += char

print('first_forty', first_forty)
print('\nlen(first_forty)', len(first_forty))

@hadrocodium
Copy link

hadrocodium commented Apr 10, 2023

#Create a string called first_forty that is comprised of the first 40 characters of emotion_words2.txt.

# This solution uses a function to break from a nested loop immediately to the outside of the whole loop thing.
def first_forty_func(file_name):
    first_forty = ''
    count = 0
    
    with open(file_name, 'r') as file_ref:
        for line in file_ref:
            line = line.strip()
            for char in line:
                count += 1
                if count == 41:
                    return first_forty
                first_forty += char

first_forty = first_forty_func('emotion_words2.txt')                

print('first_forty', first_forty)
print('\nlen(first_forty)', len(first_forty))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment