笨办法学python第36节,我写的代码如下:
from sys import exit def rule(): print "Congratulations! You made the right choice." print "But is also a terrible choice." print "You have to abide by the contract of the devil." print "Input your choice: \n 1.dog \n 2.cat \n 3. panda" next = raw_input("> ") if next.isdigit(): next1 = int(next) if next1 == 1: print "Don‘t quarrel with me!" elif next1 == 2: print "Remember, good boyfriend won‘t quarrel with his girlfriend!" elif next1 == 3: print "Remember, don‘t quarrel with me!!!!!!!" else: print "Input a number in range(1,4)!" else: print "please input a number" exit(0) def start(): print "Do you want to be my boyfriend?" print "input ‘yes‘ or ‘no‘ " next = raw_input("> ") if next == "yes": rule() elif next == "no": print "How dare you!" else: print "You don‘t even know the rule, bye bye" start()
这个用的是raw_input("> "),下面的代码用的是input("> ")
from sys import exit def rule(): print "Congratulations! You made the right choice." print "But is also a terrible choice." print "You have to abide by the contract of the devil." print "Input your choice: \n 1.dog \n 2.cat \n 3. panda" next = input("> ") if next in range(1,4): if next == 1: print "Don‘t quarrel with me!" elif next == 2: print "Remember, good boyfriend won‘t quarrel with his girlfriend!" else: print "Remember, don‘t quarrel with me!!!!!!!" else: print "please input a number in range(1,4)" exit(0) def start(): print "Do you want to be my boyfriend?" print "input ‘yes‘ or ‘no‘ " next = raw_input("> ") if next == "yes": rule() elif next == "no": print "How dare you!" else: print "You don‘t even know the rule, bye bye" start()
注:
1. 第一个代码里面:next = raw_input("> "), 意思就是无论输入什么,都是字符串的类型,所以要在下面加上一句 next1 = int(next) 转换成数字进行判断。
2.第二个代码里面:用的 next = input("> "), 所以就不用 next.isdigit(): ,因为这个是对字符串进行的判断(参见上一节),这里的话就直接可以用 next in range(1,4):,但是应该注意的是在运行脚本的时候,如果输入字符串,要用“”引号引起来,否则会出现SyntaxError 。
3. 这两个函数均能接收字符串 ,但 raw_input() 直接读取控制台的输入(任何类型的输入它都可以接收)。而对于 input() ,它希望能够读取一个合法的 python 表达式,即你输入字符串的时候必须使用引号将它括起来,否则它会引发一个 SyntaxError 。
时间: 2024-10-14 16:09:14