I don't understand why my code is looping when not supposed to
Question:
This is very simple, and I may look dumb, I’m completely new to Python
In my function user(), I put a while loop to see that only 1 word is entered and no numbers. Its a vowel counter that accepts 1 word
I don’t understand why it keeps looping
I think continue means to skip all code ahead and go back to loop
Can someone please help me out
def user():
global word
while True:
word = input(">")
j = word.split(" ")
if len(j) == 1:
pass
else:
continue
for _ in word:
if _.isdigit():
continue
else:
break
return word
def vowel_check():
global word
word = word.lower()
vowels = ["a","e","i","o","u"]
vowel_count = 0
for i in vowel:
if i in vowels:
vowel_count += 1
else:
pass
print(vowel_count)
user()
vowel_check()
Answers:
Both keywords, continue
and break
only apply to the "nearest" loop. Here you will fall out of the for
-loop, but are still kept in the while
-loop forever.
To solve this, you could instead of doing break in the while loop just return the found value here.
Rather than using global variables and various pass/continue/break structures you can simplify the whole process as follows:
VOWELS = set('aeiouAEIOU')
def user():
while True:
word = input('> ')
if len(word.split()) == 1: # exactly one word
if not any(c.isdigit() for c in word):
return word
def vowel_check(s):
return sum(c in VOWELS for c in s)
print(vowel_check(user()))
This is very simple, and I may look dumb, I’m completely new to Python
In my function user(), I put a while loop to see that only 1 word is entered and no numbers. Its a vowel counter that accepts 1 word
I don’t understand why it keeps looping
I think continue means to skip all code ahead and go back to loop
Can someone please help me out
def user():
global word
while True:
word = input(">")
j = word.split(" ")
if len(j) == 1:
pass
else:
continue
for _ in word:
if _.isdigit():
continue
else:
break
return word
def vowel_check():
global word
word = word.lower()
vowels = ["a","e","i","o","u"]
vowel_count = 0
for i in vowel:
if i in vowels:
vowel_count += 1
else:
pass
print(vowel_count)
user()
vowel_check()
Both keywords, continue
and break
only apply to the "nearest" loop. Here you will fall out of the for
-loop, but are still kept in the while
-loop forever.
To solve this, you could instead of doing break in the while loop just return the found value here.
Rather than using global variables and various pass/continue/break structures you can simplify the whole process as follows:
VOWELS = set('aeiouAEIOU')
def user():
while True:
word = input('> ')
if len(word.split()) == 1: # exactly one word
if not any(c.isdigit() for c in word):
return word
def vowel_check(s):
return sum(c in VOWELS for c in s)
print(vowel_check(user()))