条件不起作用。它应该是一个if语句,但是if语句正在完成我的所有语句,而不仅仅是我需要的几个语句

时间:2014-11-07 04:10:31

标签: python conditional-statements

#Just defining strings needed for later
Mc = "Mc"
O = "O'"

#What is your name?
name = raw_input('What is your first name?')
name2 = raw_input('What is your last name?')

#Setting up the grammar for all of these weirdly typed names
game = name.lower()
game2 = name2.lower()
lame = game[1:len(game)]
lame2 = game2[1:len(game2)]
Name = game[0].upper() + lame
Name2 = game2[0].upper() + lame2

#For the names with a Mc in it
if Name2[0:1] == "mc" or "MC":
    Last_Name = Mc + Name2[2].upper() + Name2[3:len(Name2)]

#For the names with an O'name in it
elif Name2[0:1] == "O'" or "o'":
    Last_Name = O + Name2[2].upper() + Name2[3:len(Name2)]

#For the regular names
else:
    Last_Name = Name2

#For the liars
if len(Name) + len(Name2) > 25:
    print "STOP LYING!"

#Lets finally print this beast
else:
    print "Welcome " + Name + " " + Last_Name + "!"

这应该是格式化名称来打印它们,当它们有一个McLastname时,它会修复大小写,但是当我输入任何姓氏时,它会用Mc替换前2个字母,即使名字没有从一个mc开始。如果我输入姓氏如Smith,则将其更改为McIth。有没有办法改变这个,所以如果名字以mc或MC开头,它只会改变前两个字母给Mc?感谢。

2 个答案:

答案 0 :(得分:0)

if Name2[0:1] == "mc" or "MC":

应该是

if Name2[0:1] == "mc" or Name2[0:1] == "MC":

否则此if语句始终为true,因为“MC”为真。

答案 1 :(得分:0)

本声明:

 if Name2[0:1] == "mc" or "MC":

总是如此。这相当于说这是真的,名字以&#34; mc&#34;开头。或者是&#34; MC&#34;是吗?但是在Python中,非空字符串总是为真,所以第二部分总是为真,所以整个事情总是如此。< / p>

你打算写:

 if Name2[0:1] == "mc" or Name2[0:1] == "MC":

但也可以写

 if Name2[0:1] in ("mc", "MC"):

 if Name2[0:1].upper() == "MC":