Pynative while loop tutorial -- confused

Click For Summary
SUMMARY

The discussion focuses on creating a while loop in Python that displays each character of a string while skipping spaces. The initial code provided by a user resulted in an "IndexError" due to incorrect indexing, as it attempted to access characters beyond the string's length. The correct approach involves using a while loop with a condition that checks if the index is less than the string length. Alternative solutions, including using a for loop and list comprehension, were also suggested to achieve the same result without errors.

PREREQUISITES
  • Understanding of Python while loops
  • Familiarity with string indexing in Python
  • Knowledge of control flow statements, specifically if and continue
  • Basic understanding of Python list comprehensions
NEXT STEPS
  • Learn about Python string methods, particularly isspace()
  • Explore Python error handling with try-except blocks
  • Investigate Python for loops for iterating over strings
  • Study list comprehensions in Python for concise data manipulation
USEFUL FOR

This discussion is beneficial for beginner to intermediate Python developers, educators teaching programming concepts, and anyone looking to improve their understanding of string manipulation and control flow in Python.

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   Reactions: 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   Reactions: 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 = '')
 

Similar threads

Replies
3
Views
2K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 10 ·
Replies
10
Views
3K
Replies
8
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 21 ·
Replies
21
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
Replies
5
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K