0

while, if in python. Help with code.

sentence=str(input()) x=0 y=len(sentence) while y>=x: if sentence[x]==" ": x=x+1 print(sentence) print("end") I am trying to print sentence event time there is an empty space in the sentence itself and then print end, but l am not sure what I'm doing wrong.

12th Mar 2020, 6:37 AM
GusPrzygora
GusPrzygora - avatar
5 odpowiedzi
+ 3
GusPrzygora Oh. just put x = x + 1 outside the if condition and in while loop change y>=x to y>x. Below are some alternatives You can use count function. sentense.count(" ") It will count the number of spaces in sentence and you can then print using the for loop. (you can also use while loop hut for loop is better in this case) s = input() sp = s.count(" ") for i in range(sp): print(s) print("end") #if you want the same code with while loop s = input() sp == s.count(" ") x = 0 while x<sp: print(s) x += 1 print("end") About your code, instead of using while loop, use for loop. for i in sentence: if i == " ": print(sentence) print("end") #if you want same code with while loop sentence = input() length = len(sentence) x = 0 while x<length: if sentence [x] == " " : print(sentence) x += 1 print("end")
12th Mar 2020, 10:31 AM
Utkarsh Sharma
Utkarsh Sharma - avatar
+ 2
I can only see that the while loop will be an infinite loop unless the sentence is just " " (space) Can you explain more briefly what issues are you encountering and what does your code do?
12th Mar 2020, 7:38 AM
Utkarsh Sharma
Utkarsh Sharma - avatar
+ 2
Hi GusPrzygora Not quite sure where to start here. Could you give an example input, & what you expect the output to be? First fix: sentence = input()
12th Mar 2020, 7:42 AM
Rik Wittkopp
Rik Wittkopp - avatar
0
Sorry guys, I'm quite a beginner, so l apologize if I'm not so clear :) what l want to do is: given a random sentence, print that sentence as many times as amount of empty spaces are in that sentence, and afterwards print 'end' Example: Input: 'eggs spam eggs' Output: eggs spam eggs eggs spam eggs end Thanks!
12th Mar 2020, 9:30 AM
GusPrzygora
GusPrzygora - avatar
0
Thank you so much! I'll check it out :)
12th Mar 2020, 1:02 PM
GusPrzygora
GusPrzygora - avatar