刚开始学python,做一个练习的时候发现程序能跑起来但输入的结果不对。

题目:挑选10岁到12岁的女孩,要询问年龄和性别(M表示男,F表示女)。(如果不是女孩就不必询问年龄了。)当时错误的程序:

import sys

sex = raw_input("Enter your sex:")


if "M" == sex:

   print "You are boy,exit."

   sys.exit()

age = float(raw_input("Enter your age:"))

if "F" == sex:

   print "Sex is: ", sex

   print "Age is: ", age

elif 10 <= age and age <= 12:

   print "Good"

else:

   print "exit."

当输入一个大于等于10小于等于12的数时直接打印exit.

   后来找出来原因,如果sex等于F时已经成立了,所以不会向下执行了。所以下面大于等于10小于等于12的判断根本没有执行。所以要写成if 10 <= age and age <= 12: 而不是elif.所以思想一定要清晰,少犯如此低级错误。而且程序不够全面,上面只定义了sex等于M 或 F,如果输入其他的则不能判断出来。最后修改的代码如下:

import sys

sex = raw_input("Enter your sex(just M or F):")  #定义只能输入M 或 F


if "M" == sex:                                   #如果等于M时直接退出。

   print "You are boy.please you exit."

   sys.exit()

if sex != "M" and sex != "F":                    #如果不等于M也不等于F 时

   print "Please enter again"

   sys.exit()

age = float(raw_input("Enter your age:"))

if "F" == sex and 10 <= age and age <= 12:        #等于F 而 age的值>=10且<=12.

   print "Good"

else:

   print "Please you exit."

上面是我自己写的代码。但看到作者的代码后才知道自己把问题想复杂了。

下面是作者的代码,只有九行就解了问题,(我把输出的部分改了,这个无所谓,主要是思想):

sex = raw_input("Are you male of female?('m' 或 'f')" )

if sex == 'f':

   age = int(raw_input('what is your age?'))

   if age >= 10 and age <= 12:

       print "GOOD"

   else:

       print "EXIT"

else:

   print "Only girls!"