我正在查看使用此代码的INI配置文件实现here:
# Load the configuration file
with open("config.ini") as f:
sample_config = f.read()
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(io.BytesIO(sample_config))
如果找不到配置文件,我想输出一些内容,但是the Python documentation没有说明else
条件的任何内容,所以我在考虑使用{{1}在这里阻止:
if...else
使用# Load the configuration file
if f = open("config.ini"):
sample_config = f.read()
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(io.BytesIO(sample_config))
else
print "Could not open config file"
块代替if...else
块会看到哪种差异?
答案 0 :(得分:4)
嗯,一个区别是if
块不会解析。赋值语句不是Python中的表达式。另一个原因是它不会自己关闭文件 - that’s what the with
accomplishes。
您真正需要的是try
,因为open
在无法找到文件时抛出异常:
try:
# Load the configuration file
with open("config.ini") as f:
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(f)
except FileNotFoundError:
# handle exception
(如果您使用的是旧版本的Python,则需要抓住OSError
和check its errno
。)
答案 1 :(得分:1)
测试一个条件以查看它是否为真,然后在满足条件后执行代码块示例:
a = 1
if a != 1:
do something here.
elif a ==1: # elif takes the place of else, literally means else if a ==/!= some value execute this.
do something else.
a With语句是一个布尔操作,它可以与文件I / O一起使用,或者是我见过它的最多。
示例可能是:
with open(somefile):
do some stuff.
我所看到的else子句似乎只是在从未满足条件时尝试使用if / if语句的结尾,并且它的使用基本上是,如果try语句由于某种原因而失败,这个是你现在执行的。
with open(somefile):
try:
do stuff.
else:
exit loop/ do something else.
<强> -------------------------------------------- ------------------------------------ 强>
说实话,我喜欢轻松的时间陈述。你可以在while循环中嵌套更多的条件语句,for循环,if循环(我已经来到了LOVE嵌套循环),它们简化了编写代码的过程。
以下是我不久前写的一篇文章的代码片段:
while continue_loop == 'Y': # gives user an option to end the loop or not
# and gives you more flexibility on how the loop runs.
ac = 0
acc = 0
accu = 0
accum = 0
try: # the try block, gets more info from user, and stores it inside variables.
bday = int(input("Please enter the day you were born! \n->"))
bmonth = int(input("Please enter the month you were born\n ->"))
byear = int(input("Please enter the year you were born!\n->"))
birth = bday + bmonth + byear
sum1 = str(birth)
for x in sum1: # iteration over the variable.
accum1 += int(x)
accum2 = str(accum1)