Pynative while loop tutorial -- confused

In summary: The code above is much more efficient than using a while loop. It iterates through each character in the string and only prints out the character if it is not a space. This avoids the issue of trying to access an index that doesn't exist and also eliminates the need for the continue statement.In summary, the goal of this program is to display each character from a string, skipping over any spaces. The code provided uses a while loop and the continue statement to achieve this, but it encounters an error due to trying to access an index that is out of bounds. This can be fixed by using a for loop that iterates through each character in the string.
  • #1
shivajikobardan
674
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
  • #2
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:
  • #3
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).
 
  • #4
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.
 
  • #5
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.
 
  • #6
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/
 
  • #7
Look to your while condition and ask yourself whether to use < or <=.
 
  • #8
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 = '')
 
  • #9
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 = '')
 

1. What is a while loop in Python?

A while loop in Python is a control flow statement that allows a block of code to be executed repeatedly as long as a certain condition is met. It is useful for automating repetitive tasks and iterating through a set of data.

2. How do I use a while loop in my code?

To use a while loop in your code, you first need to define the condition that will be checked at the beginning of each iteration. Then, you can write the code that you want to be executed repeatedly inside the loop. Make sure to include a way to update the condition so that the loop doesn't become infinite.

3. What is the difference between a while loop and a for loop?

A while loop and a for loop are both used for iteration, but they have some key differences. A for loop is typically used for iterating through a known set of data, while a while loop is better for situations where the number of iterations is not known beforehand. Additionally, a for loop will always execute the code at least once, while a while loop may not if the initial condition is not met.

4. How do I avoid an infinite while loop?

To avoid an infinite while loop, make sure that the condition being checked will eventually become false. This can be done by including an update to the condition inside the loop, such as incrementing a counter or changing a variable's value. It's also helpful to test your code with different inputs to ensure that the loop will terminate in all cases.

5. Can I use a while loop with other control flow statements?

Yes, a while loop can be used in conjunction with other control flow statements such as if/else statements or try/except statements. This allows for more complex and dynamic code that can handle different scenarios and conditions.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
3
Views
509
  • Engineering and Comp Sci Homework Help
Replies
8
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
12
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
10
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
21
Views
2K
  • Programming and Computer Science
Replies
5
Views
994
  • Programming and Computer Science
Replies
5
Views
885
  • Engineering and Comp Sci Homework Help
Replies
3
Views
2K
  • Programming and Computer Science
2
Replies
55
Views
4K
Back
Top