Katie Stearns
Katie Stearns

Reputation: 65

Python loop - help me understand

I have python to generate a random code, in this case, "Lucy", and it prints as follows:

L
Lu
Luc
Lucy

I don't understand how it works, can someone explain?

import sys
mysteryString = sys.argv[1]
print("~ testing with mysteryString = {} ~".format(mysteryString))

#Above code was provided for me

charCount = ""
for mysteryChar in mysteryString:
    charCount = charCount + mysteryChar
    print(charCount)

Why is the charCount initialized outside the loop? Why does it print the characters the way it does?

Upvotes: 2

Views: 600

Answers (3)

Pat Moran
Pat Moran

Reputation: 1

From Python's Official Documentation - 8.3 The for Statement

"The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list)..."

In your example of code, "Lucy" is the string. The string is the sequence. The characters that compose it (i.e. "L", "u", "c", "y") are the "elements of a sequence."

I'm going to walk through your code line-by-line to see if it helps.

1.You assign sys.argv[1] to the variable mysteryString. Your sys.argv[1] is the string "Lucy".

mysteryString = sys.argv[1]

2.The program takes the variable mysteryString, formats the string with it, and prints the output.

print("~ testing with mysteryString = {} ~".format(mysteryString))

Output: ~ testing with mysterString = Lucy ~

3.This line initializes the variable charCount. Note that it is empty.

charCount = ""

4.This line marks the beginning of the for-statement (aka for-loop). The for-statement iterates (or "loops over") every element in the provided sequence. In order to loop over a sequence, you must assign each element in it to a variable. Here, that variable is mysteryChar. The first element of the sequence (i.e. the character "L") is assigned to variable mysteryChar.

for mysteryChar in mysteryString:

If it helps, you can think of what is happening at this point as:

mysteryChar = "L"

5.This line does a couple of cool things. First, it takes the value of charCount and adds it to the value of mysteryChar. Second, it assigns the values of charCount and mysteryChar to charCount.

    charCount = charCount + mysteryChar

Remember when in step 3, we assigned the variable charCount to an empty string?

charCount = ""

After step 5 executes:

charCount = "L"

6.This line prints charCount.

Code:

print(charCount)

Output:

L

7.Now, try to follow the code.

Code:

charCount = ""
for mysteryChar in mysteryString:
    charCount = charCount + mysteryChar
    print(charCount)

Output:

L

8.Continue to next iteration of the loop.

Code:

mysterString = "Lucy"
# Note: Before the second iteration of the loop, charCount = "L"
# This is because in the first iteration of the loop,
# "L" was added & assigned to the variable charCount
charCount = ""
for mysteryChar in mysteryString:
    charCount = charCount + mysteryChar
    print(charCount)

Output:

Lu

9.Continue to the next iteration of the loop

Code:

mysterString = "Lucy"
# Note: Before the third iteration of the loop, charCount = "Lu"
# This is because in the second iteration of the loop,
# "u" was added & assigned to the variable charCount
# At that point, charCount = "Lu"
charCount = ""
for mysteryChar in mysteryString:
    charCount = charCount + mysteryChar
    print(charCount)

Output:

Luc

10.This is all of the for-loop's output.

Output:

L
Lu
Luc
Lucy

Question:

"Why does it print the characters the way it does"

The for-loop prints the characters the way it does because it loops over each element in the sequence individually.

First Iteration Output:

L

Second Iteration Output:

Lu

Third Iteration Output:

Luc

Fourth Iteration Output:

Lucy

I started working on learning python about a year ago, so this stuff is relatively new to me, too. Welcome critiques / corrections if my explanation is misinformed.

Upvotes: 0

Jonathan Porter
Jonathan Porter

Reputation: 1556

The reason why charCount is initialized outside of the loop is because of scope.

A variable defined in the main part of the body belongs to the "global" scope. This means that it can be accessed by anything else throughout the file.

But a variable that is defined inside a function/loop is "local" to that function. This means that it only exists and is accessible from the point at which it is defined until the end of the function.

When we use the assignment operator (=) inside a function, its default behavior is to create a new local variable – unless a variable with the same name is already defined in the local scope.

So essentially, when we declare it inside of the loop as demonstrated below. It is re-initalizing the variable to = "" each time it loops through which is why it only prints out one character at a time.

I.e.

"" + "L"
reintialize charCount = ""
"" + "U"
etc

Variable declared outside loop:

enter image description here

Variable declared inside loop:

enter image description here

Upvotes: 1

BritishWerewolf
BritishWerewolf

Reputation: 3968

charCount = ""
for mysteryChar in mysteryString:
    charCount = charCount + mysteryChar
    print(charCount)

What this does is initialise a variable charCount which is your string.

Then we have a for loop. What this does is iterate through each letter of your string.

Then it will get the original string (which starts off blank) and adds a letter at a time.

Then print displays it.

The reason for declaring outside the loop is so that you can concatenation each letter to it.

Trying to do the charCount = charCount + mysteryChar when charCount doesn't exist will throw and error. So you create a blank string outside so that you can do this:

"" + "L"  
"L" + "U"  
"LU" + "C"  
"LUC" + "Y"  

Upvotes: 0

Related Questions