簡體   English   中英

在Python2中,with和if有什么區別?

[英]What is the difference between with and if in Python2?

我在這里查看使用此代碼的INI配置文件實現:

# 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))

如果找不到配置文件,我想輸出一些東西,但是Python文檔沒有對else條件做任何說明,所以我考慮在這里使用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使用if...else塊代替with塊,我會看到什么樣的差異?

好吧,一個區別是if塊不會解析。 賦值語句不是Python中的表達式。 另一個是它不會自行關閉文件- 這是with完成的

您真正要尋找的是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檢查其errno 。)

測試一個條件以查看其是否為真,然后在滿足條件的示例之后執行代碼塊:

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.

With語句是布爾操作,可以與文件I / O一起使用,或者這是我所見過的最多的操作。

例如:

with open(somefile):
    do some stuff.

我所看到的else子句似乎只能在條件從未滿足的情況下使用try / if語句的結尾,並且基本上是使用它,如果try語句由於某種原因失敗或其他原因,這就是您的意思現在執行。

with open(somefile):
    try:
        do stuff.
else:
exit loop/ do something else.

-------------------------------------------------- ------------------------------

說實話,我喜歡一會兒陳述。 您可以在while循環中嵌套更多條件語句,對於循環來說,如果循環(我喜歡嵌套循環)可以極大地簡化代碼編寫過程。

這是我不久前寫的一段代碼片段:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM