python 笔记 if语句的简单嵌套 《笨办法学Python》习题31 ——1.3

这篇博客是作者在学习《笨办法学Python》时关于习题31的笔记,主要讨论了if语句的简单嵌套。内容涉及符号使用规范,if语句的无限嵌套原理,以及遇到的缩进错误问题。作者通过示例代码ex31.py和ex31_1.py展示了如何解决制表符与空格混用导致的错误,并解释了正确理解if语句执行逻辑的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

习题 31: 作出决定

目标与感悟:

•符号不能混用,制表符和4个空格两者只能同时使用一个(同一种功能时)。

•知晓if语句的使用,理论上可以无限嵌套。

•嵌套,我理解就跟树的分支一样。

•if语句只返回为Ture的第一个区块,如果一直没有符合的将会结束操作,所以,想法一定要完善。

 

ex31.py

#-*- coding:utf-8-*-
print "You enter a dark room with two doors. Do you go throuth door #1 or door #2?"
 
door = raw_input("> ")
 
if door == "1":
	print "There's a giant bear here eating a cheese cake. What do you do?"
	print "1. Take the cake."
	print "2. Scream at the bear."
	bear = raw_input("> ")
 
    if bear == "1":
		print "The bear eats your face off. Good job!"
	elif bear == "2":
		print "The bear eats your legs off. Good job!"
	else:
	print "Well, doing %s is probably better. Bear runs away." %bear
elif door == "2":
	print "You stare into the endless abyss at Cthulhu's retina."
	print "1. Blueberries."
	print "2. Yellow jacket clothespins."
	print "3. Understanding revolvers yelling melodies."
	insanity = raw_input("> ")
	if insanity == "1" or insanity == "2":
		print "Your body survives powered by a mind of jello. Good job!"
	else:
		print "The insanity rots your eyes into a pool of muck. Good job!"
else:
	print "You stumble around and fall on a knife and die. Good job!"

运行结果:



很奇怪,出错了`````````````

看语法结构什么的好像也没什么问题,报错的内容即缩进对应级别不匹配,就是可能多加了什么括号之类.

后来打开notepad显示空格和制表符


看起来都是4个空格距离,但符号不一样就是不一样,应该是制表符(TAB),修改完毕后则正常了。


正确输出结果:

ex31.py


下面测试一个简单三层嵌套:

ex31_1.py

#-*- coding:utf-8-*-
 
print "Enter one number (1-10),please."
 
a = raw_input("> ")
if a == "1":
	print "1. Take the cake."
	print "2. ET is very interesting!"
	print "3. Scream at the bear."
	b = raw_input("> ")
	if b == "1":
		print "Yeah ,cake is vert delicious!What kind of cake do you like?"
		print "1. apple cake."
		print "2. banana cake."
		print "3. orange cake."
		c = raw_input("> ")
		if c == "1":
			print "Yeah,apple cake is vert delicious!"
 
else:
	print "You stumble around and fall on a knife and die. Good job!"

运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值