我正在做一个简单的程序,要求3个输入,如果所有3个输入都匹配,则会打印欢迎消息。(姓名首字母==YNH,年龄==42,出生日期==1/27/74)。在
此外,还将打印用户名(youngnathanhather)的长度以及打印三个不同字符串之一的输入(颜色)。在
我遇到了一个问题,当我输入蓝色、粉色和黄色时,即使变量(颜色)不同,三个if语句都是真的并打印它们的字符串。在
也许我在这里漏掉了一大堆if语句,但有人知道这是怎么回事吗?我希望输入“Yellow”,只看到一个字符串打印。在
#checks if inputted information matches criteria.
#if all inputted information matches variable criteria
#(Initials == YNH, Age == 42, DOB == 1/27/74), then
#prints a Welcome message for the user.
if Initials == 'YNH':
if Age == '42':
if DOB == '1/27/74':
print('Welcome Young Nathan Heather')
print('Did you know that your name has ' +str((len('YoungNathanHeather'))) +' letters.')
#Asks for a color and prints a response based on if the color is pink, yellow, or blue
color = input("If you could describe your mood in a color, what would it be ?")
if color == 'blue' or 'Blue':
print('According to my research Master, Blue and Yellow together makes green. Green seems to be equal to money.')
elif color == 'pink' or 'Pink':
print('According to my research Master, Pink attracts women or makes a human into a women. Whatever comes first.')
elif color == 'yellow' or "Yellow":
print('According to my research Master, Yellow indicates a "mellow" mood. Prolong this mood if feasible.')
else:
print("My apologies Master. My research is shallow and I am not yet familiar with that mood's \"color\"")
else:
print('Sorry, Wrong Credentials Entered')
else:
print('Sorry, Wrong Credentials Entered')
else:
print('Sorry, Wrong Credentials Entered')
当你说
可以理解为
^{pr2}$如果
color == 'blue'
为真,则为真;如果'Blue'
为真,则为或。蓝色总是正确的。其他颜色也一样你可以这样做:
它将检查
color
是否存在于颜色列表中。但是‘蓝色’、‘蓝色’等呢?这里有一个更好的解决方案。在现在它可以匹配任何蓝色的大写字母!在
接下来,考虑这一部分:
这是a lot of repetition,但也有很多不必要的缩进,这使得代码更难阅读和调试。为什么不是更像:
这样做,你的代码将更容易阅读,也更容易编写!在
在Python中,这不起作用:
if color == 'blue' or 'Blue'
,它总是真的!。您必须将其更改为if color in ('blue', 'Blue')
或更好:if color in {'blue', 'Blue'}
。在为什么它什么都不做?因为这样写if时,Python检查
if color == 'blue'
,如果为True,则执行;如果为False,则继续检查if 'Blue'
。假设您的颜色是红色,那么第一部分条件不满足,因此Python就转到if 'Blue'
。现在,这总是正确的,因为根据Python的说法:bool(any string except empty string)
是真的,bool(any number except 0*)
也是如此!因此,由于任何事物的布尔值都为真,所以无论您向它输入的内容是空字符串还是0,都始终满足if color == 'blue' or 'Blue'
的if条件。在另外,您可以将所有的
if
连接到一行:if Initials == 'YNH' and Age == '42' and DOB == '1/27/74'...
*准确地说,0和它的变体,比如0L,0j,0.0,0.00。。。在
相关问题 更多 >
编程相关推荐