Home > database >  Can I compare IF and FOR in python?
Can I compare IF and FOR in python?

Time:02-25

I have a problem with this code, Can i Use a IF beetwen a FOR in python?

In this code I want know if the first letter is a consonant or a vowel, but the code do a error

word = input("Enter a word: ")
word = word.lower()
vowel="aeiou"
if word[0] == for i in vowel:
        word = word "way"
        print(word)
else:
        word = word[1:len(word)]  "ay"
        print(word)

Input In [16] if word[0] == for i in vowel: ^ SyntaxError: invalid syntax

Can I compare FOR with an IF? What is the correct sintax for that?

CodePudding user response:

You don't need a for loop at all. Instead, you can use the in operator to check if a string contains a substring, like so:

word = input("Enter a word: ")
word = word.lower()
vowel = "aeiou"

if word[0] in vowel:
  word = word   "way"
  print(word)
else:
  word = word[1:len(word)]   "ay"
  print(word)

For example, if you ran this code and entered "hello", the result would be "elloay". If you entered "aardvark", the result would be "aardvarkway".

CodePudding user response:

What you need to do is move the for loop outside the if statement. It should look something like this:

word = input("Enter a word: ")
word = word.lower()
vowel="aeiou"
for i in vowel:
    if word[0] == i:
            word = word "way"
            print(word)
    else:
            word = word[1:len(word)]  "ay"
            print(word)

CodePudding user response:

other way to do this maybe more simple or efficient

word = input("Enter a word: ")
word = word 'way' if word.lower()[0] in ['a','e','i','o','u'] else word[1:len(word)] 'ay'
print(word)
  • Related