Pynative while loop tutorial -- confused

AI Thread Summary
The discussion revolves around creating a while loop in Python to display each character of a string while skipping spaces. A user initially encounters an "IndexError" due to attempting to access an out-of-bounds index while iterating through the string. Suggestions include adjusting the loop condition to prevent exceeding the string length and using a for loop as a simpler alternative. The conversation emphasizes the importance of correctly indexing and offers various methods to achieve the desired output without errors. Ultimately, the goal is to effectively display characters while omitting spaces.
shivajikobardan
Messages
637
Reaction score
54
Thread moved from the technical forums to the schoolwork forums
Summary:: confused in program.

Write a while loop to display each character from a string and if a character is a space, then don’t display it and move to the next character.

Use the if condition with the continue statement to jump to the next iteration. If the current character is space, then the condition evaluates to true, then the continue statement will execute, and the loop will move to the next iteration by skipping the remeaning body.


what is this program supposed to do can you explain a bit about that?

1638524405893.png


Here is what it is doing. But it is very unclear to me what are we trying to do.It doesn't make any sense. IMO what it means is to not display spaces but display other alphabets. SO I wrote a code-:but this code doesn't work properly as I would like it to work. It gives error at last after doing everything right.

Python:
word=input("Enter a string")
i=-1
while(i<=len(word)):
    i =i+ 1
    if (word[i].isspace()):
        continue
    print(word[i],end="")

Enter a string-: Joe Biden

Output-: JoeBiden

Which I believe is correct what I want in that above program.

But here is an error that is ruining my mood.

File "E:\Udemy My Courses\LoopsTutorials\main.py", line 6, in <module>
if (word.isspace()):
IndexError: string index out of range
 
Last edited by a moderator:
Physics news on Phys.org
Your string "Joe Biden" is composed of 9 elements, but if you follow what your code is doing step by step, at some point you are trying to obtain the 10th element. I.e., at some point, your code asks for 'word[9]' which, since the word only has 9 characters, doesn't exist. That's what the error is telling you as "string index (9) out of range (0-8)"
 
Last edited:
shivajikobardan said:
Summary:: confused in program.

Write a while loop to display each character from a string and if a character is a space, then don’t display it and move to the next character.

Use the if condition with the continue statement to jump to the next iteration. If the current character is space, then the condition evaluates to true, then the continue statement will execute, and the loop will move to the next iteration by skipping the remeaning body.


what is this program supposed to do can you explain a bit about that?

View attachment 293496

Here is what it is doing. But it is very unclear to me what are we trying to do.It doesn't make any sense. IMO what it means is to not display spaces but display other alphabets. SO I wrote a code-:but this code doesn't work properly as I would like it to work. It gives error at last after doing everything right.

Code:
word=input("Enter a string")
i=-1

while(i<=len(word)):
    i =i+ 1

You've checked whether i is less than or equal to len(word), and then immediately increased it. So now it might be 1 + len(word), which is out of bounds. Since list indexing starts at zero, it is in fact out of bounds when it equals len(word).
 
Gaussian97 said:
Your string "Joe Biden" is composed of 9 elements, but if you follow what your code is doing step by step, at some point you are trying to obtain the 10th element. I.e., at some point, your code asks for 'word[10]' which, since the word only has 9 characters, doesn't exist. That's what the error is telling you as "string index (10) out of range (0-9)"
I understand why it is coming, IDK if this is fixable.
 
Gaussian97 said:
Your string "Joe Biden" is composed of 9 elements, but if you follow what your code is doing step by step, at some point you are trying to obtain the 10th element. I.e., at some point, your code asks for 'word[10]' which, since the word only has 9 characters, doesn't exist. That's what the error is telling you as "string index (10) out of range (0-9)"
You're off by one here. The string contains 9 characters, so the indexes run from 0 to 8. word[8] is the last character of the string.

shivajikobardan said:
I understand why it is coming, IDK if this is fixable.
Of course it's fixable.
 
shivajikobardan said:
I understand why it is coming, IDK if this is fixable.
As @Mark44 said, of course it's fixable. You could check how many characters are in the string before you start the loop and only iterate that high. Or you could use an iterator and only iterate through the characters in the string. Or you could use a try..except inside the loop and break from the loop if it fails. There are probably other ways as well.

This site gives some ideas. https://www.geeksforgeeks.org/iterate-over-characters-of-a-string-in-python/
 
Look to your while condition and ask yourself whether to use < or <=.
 
phyzguy said:
Or you could use an iterator and only iterate through the characters in the string.
Something like this:
Python:
word=input("Enter a string ")
for ch in word:
   if ch != ' ':
      print (ch, end = '')
 
Mark44 said:
You're off by one here. The string contains 9 characters, so the indexes run from 0 to 8. word[8] is the last character of the string.
True, it was a typo, I've corrected it thanks.
Mark44 said:
Something like this:
Python:
word=input("Enter a string ")
for ch in word:
   if ch != ' ':
      print (ch, end = '')
Well, technically the question asks for a while loop.
 
  • Like
Likes shivajikobardan
  • #10
Gaussian97 said:
Well, technically the question asks for a while loop.
Right, but I was elaborating one of the suggestions that @physguy made about iterating through the characters in the string.

Here's a while loop version:
Python:
word=input("Enter a string...  ")
wordLen = len(word)
i = 0

while(i < wordLen):
   if (word[i].isspace()):
      i += 1
   else:
      print(word[i], end='')
      i += 1
 
  • Like
Likes jedishrfu
  • #11
Another possibility uses list comprehension.
Python:
word=input("Enter a string ")

# Create a list of the characters with spaces removed.
shortStrList = [ch for ch in word if ch != ' ']
# Print each character in the list.
for ch in shortStrList:
   print (ch, end = '')
 
Back
Top