Python中if / else循环的问题 [英] Issues with a if/else loop in Python

查看:215
本文介绍了Python中if / else循环的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Python创建这个Pig Latin翻译器,但是在我尝试缩小它之前它运行良好。

I am trying to make this Pig Latin translator in Python and it was working well until I tried to downsize it a bit.

有人可以看看这段代码并告诉我为什么,当我在开头输入一个没有元音的单词时,它仍会在if语句中打印元音代码?

Can someone please take a look at this code and tell me why, when I type in a word without a vowel at the beginning it will still print the "vowel" code in this if statement?

代码:

pyg = 'ay'

original = raw_input('Enter a word: ')
low_original = original.lower()

if len(low_original) > 0 and low_original.isalpha():
        print low_original
        if low_original[0] == 'a' or 'e' or 'i' or 'o' or 'u':
                print "vowel"
                pyg_vowel = low_original + pyg
                print pyg_vowel
        else:
                print "consonant"
                pyg_cons = low_original[1: ] + low_original[0] + pyg
                print pyg_cons
else:
        print 'empty'


推荐答案

你需要分别检查所有的元音。

You need to do a check for all the vowels separately.

目前,您的if条件评估为: -

Currently, your if condition is evaluated as: -

if (low_original[0] == 'a') or 'e' or 'i' or 'o' or 'u':

返回其条件中的第一个真值,该值将为 True e 这里,取决于你的第一个条件是否为真。现在,因为'e'被评估为 True ,所以两个值都是 true ,因此你的条件总是 true

or returns the first true value in its condition, which will either True or e here, depending upon your first condition is True or not. Now, since 'e' is evaluated to True, so both the values are true, hence your condition will always be true.

你应该这样做: -

You should do it like this: -

if low_original[0] in 'aeiou':

或: -

if low_original[0] in ('a', 'e', 'i', 'o', 'u'):

这篇关于Python中if / else循环的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆