Hướng dẫn are nested if else are allowed in python - được lồng vào nhau nếu khác được phép trong python


Có thể có một tình huống khi bạn muốn kiểm tra một điều kiện khác sau khi một điều kiện giải quyết thành true. Trong tình huống như vậy, bạn có thể sử dụng Nested nếu xây dựng.if construct.

Trong một cấu trúc nếu được lồng, bạn có thể có một nếu ... Elif ... khác xây dựng bên trong một cái khác nếu ... Elif ... khác xây dựng.if construct, you can have an if...elif...else construct inside another if...elif...else construct.

Cú pháp

Cú pháp của lồng nhau nếu ... elif ... cấu trúc khác có thể là -

if expression1:
   statement(s)
   if expression2:
      statement(s)
   elif expression3:
      statement(s)
   elif expression4:
      statement(s)
   else:
      statement(s)
else:
   statement(s)

Thí dụ

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"

Khi mã trên được thực thi, nó sẽ tạo ra kết quả sau -

Expression value is less than 200
Which is 100
Good bye!

python_decision_making.htm

Nó luôn luôn hợp pháp trong việc lập trình C để làm tổ IF-Else, điều đó có nghĩa là bạn có thể sử dụng một câu nếu hoặc khác nếu câu lệnh khác nếu hoặc khác nếu câu lệnh.

Tại sao chúng ta sử dụng lồng nhau nếu

  • Nested nếu các câu lệnh khác được sử dụng để thực thi đoạn mã khác nhau khi chúng ta có nhiều hơn hai tùy chọn để xử lý.
    • Các chương trình Python của chúng tôi tạo ra cơ bản ‘nếu điều này, hãy thực hiện điều đó với các câu lệnh if. Bằng cách đó, mã của chúng tôi đưa ra quyết định trong khi nó chạy. Nhưng để xử lý các tình huống phức tạp, chúng ta cũng có thể đặt một câu hỏi IF trong một câu khác. Hãy để xem làm thế nào.
    • Trong bài viết này:
  • Nếu các tuyên bố phụ thuộc vào IFS khác: Python sườn lồng nhau ifs
    • Mẫu mặc định: Nếu câu lệnh bên trong khác
    • Mẫu mặc định: Nếu câu lệnh bên trong khối mã
      #!/usr/bin/python
      
      var = 100
      if var < 200:
         print "Expression value is less than 200"
         if var == 150:
            print "Which is 150"
         elif var == 100:
            print "Which is 100"
         elif var == 50:
            print "Which is 50"
         elif var < 50:
            print "Expression value is less than 50"
      else:
         print "Could not find true expression"
      
      print "Good bye!"
      
      1
    • Các chương trình ví dụ Python sử dụng các câu lệnh nếu
  • Ví dụ: So sánh tuổi với câu lệnh nếu được lồng
  • Ví dụ: lồng nhau nếu điều đó xử lý hàng tồn kho sản phẩm

Ví dụ: Đánh giá đầu vào của người dùng với các câu lệnh nếu được lồng

Các cách khác để mã hóa Python nếu các câu lệnhnested if statement is an if statement that is nested (meaning, inside) another if statement or if/else statement. Those statements test true/false conditions and then take an appropriate action (Lutz, 2013; Matthes, 2016). That’s how we execute Python code conditionally (Python Docs, n.d.).

Khi chúng tôi có một câu lệnh IF hoặc IF/ELSE thường xuyên, chúng tôi sẽ kiểm tra một điều kiện và sau đó thực thi một số mã. Nhưng một câu lệnh nếu được lồng nhau cũng phụ thuộc vào cách kiểm tra

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
2 trước đó đánh giá. Đây là một cách để thực hiện các điều kiện được kiểm tra với nhau. Nó cũng cung cấp cho chương trình của chúng tôi cơ hội thực thi mã giữa các câu lệnh IF. Hãy để xem làm thế nào.

# Mẫu mặc định: Nếu câu lệnh bên trong khác

Có hai cách chính để tạo ra một tuyên bố nếu lồng nhau. Tùy chọn đầu tiên là đặt câu lệnh IF bên trong khối mã

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
2. Tùy chọn khác là đặt câu lệnh IF trong mã
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
1 của câu lệnh IF/ELSE.

Vì vậy, cách tiếp cận đầu tiên khiến chúng ta đặt một câu tuyên bố IF bên trong một câu khác. Đây là cách trông như thế nào:

if conditionA:
    # Code that executes when 'conditionA' is True

    if conditionB:
        # Code that runs when 'conditionA' and
        # 'conditionB' are both True

Python đánh giá câu tuyên bố Nested này khi điều kiện của câu lệnh IF trước đó là

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
5. Khi
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
6 là
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
7, câu lệnh nếu của chúng tôi không bao giờ chạy. Điều đó xảy ra ngay cả khi tình trạng của chính nó là
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
5.

Lưu ý rằng, khi câu lệnh IF đầu tiên kiểm tra

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
5, lần thứ hai không được đảm bảo để chạy. Rốt cuộc, điều kiện của câu lệnh Nest đó cũng phải kiểm tra
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
5. Vì vậy, mã của câu lệnh nếu chỉ chạy khi
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
6 và
Expression value is less than 200
Which is 100
Good bye!
2 là
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
5. Nếu một hoặc cả hai là
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
7, mã đó không thực thi.

# Mẫu mặc định: Nếu câu lệnh bên trong khối mã #!/usr/bin/python var = 100 if var < 200: print "Expression value is less than 200" if var == 150: print "Which is 150" elif var == 100: print "Which is 100" elif var == 50: print "Which is 50" elif var < 50: print "Expression value is less than 50" else: print "Could not find true expression" print "Good bye!" 1

Cách thứ hai để thực hiện câu lệnh NESTED IF là đặt câu lệnh IF bên trong mã

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
1 của câu lệnh IF/ELSE. Đây là cách trông như thế nào:

if conditionA:
    # Code here executes when 'conditionA' is True
else:
    # Code that runs when 'conditionA' is False

    if conditionB:
        # Code that runs when 'conditionA' is False
        # and 'conditionB' is True

Bây giờ câu lệnh Nested của chúng ta chỉ có thể chạy khi điều kiện của câu lệnh nếu/khác là

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
7. Bởi vì khi điều kiện đó là
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
5, khối mã chứa câu lệnh nếu không bao giờ thực thi.

Tuy nhiên, ngay cả khi câu lệnh IF/other Tuyên bố điều kiện kiểm tra

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
7, câu lệnh Nested IF không luôn chạy. Rốt cuộc, tình trạng riêng của nó phải là
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
5 để điều đó xảy ra.

Vì vậy, đối với đoạn trích ở trên, câu lệnh nếu được tổ chức chỉ thực hiện khi

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
6 là
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
7 và
Expression value is less than 200
Which is 100
Good bye!
2 là
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
5. Điều này cho thấy một tính năng thiết yếu của câu lệnh Nested IF: chúng chỉ chạy phụ thuộc vào các câu lệnh IF khác.and
Expression value is less than 200
Which is 100
Good bye!
2 is
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
5. This shows an essential feature of the nested if statement: they only run dependent on other if statements.

Sự chỉ định của một tuyên bố nếu lồng nhau là quan trọng. Có bao nhiêu tab hoặc không gian cho mỗi dòng xác định mã nào thuộc về câu lệnh IF.

Nếu chúng ta hiểu sai thụt lề, Python nghĩ rằng một số mã không thuộc về câu lệnh nếu được tổ chức và chương trình của chúng tôi hành động kỳ lạ hoặc tạo ra lỗi.

# Các chương trình ví dụ Python sử dụng các câu lệnh Nested If

Bây giờ chúng ta đã biết cách mà câu lệnh nếu hoạt động, hãy để khám phá một số chương trình ví dụ hoàn chỉnh.

# Ví dụ: So sánh tuổi với câu lệnh nếu được lồng

Khi chúng ta sử dụng câu lệnh Nested IF, chúng ta thường thực hiện các so sánh bổ sung sau một câu lệnh IF thường xuyên. Chương trình dưới đây là một ví dụ về điều đó. Trước tiên chúng tôi kiểm tra xem người đó là người lớn. Sau đó, chúng tôi thực hiện các so sánh bổ sung để xem liệu anh ấy hoặc cô ấy đã tốt nghiệp hay nhận được giấy phép lái xe:

age = 19
isGraduated = False
hasLicense = True

# Look if person is 18 years or older
if age >= 18:
    print("You're 18 or older. Welcome to adulthood!")

    if isGraduated:
        print('Congratulations with your graduation!')
    if hasLicense:
        print('Happy driving!')

Đầu tiên chúng tôi thực hiện ba biến.

if conditionA:
    # Code that executes when 'conditionA' is True

    if conditionB:
        # Code that runs when 'conditionA' and
        # 'conditionB' are both True
5 có giá trị
if conditionA:
    # Code that executes when 'conditionA' is True

    if conditionB:
        # Code that runs when 'conditionA' and
        # 'conditionB' are both True
6.
if conditionA:
    # Code that executes when 'conditionA' is True

    if conditionB:
        # Code that runs when 'conditionA' and
        # 'conditionB' are both True
7 là
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
7. Và
if conditionA:
    # Code that executes when 'conditionA' is True

    if conditionB:
        # Code that runs when 'conditionA' and
        # 'conditionB' are both True
9 có giá trị
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
5.

Sau đó, một tuyên bố nếu người đó từ 18 tuổi trở lên. Vì biến

if conditionA:
    # Code that executes when 'conditionA' is True

    if conditionB:
        # Code that runs when 'conditionA' and
        # 'conditionB' are both True
5 của chúng tôi có giá trị
if conditionA:
    # Code that executes when 'conditionA' is True

    if conditionB:
        # Code that runs when 'conditionA' and
        # 'conditionB' are both True
6, điều kiện đó kiểm tra
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
5. Mã bên trong đó nếu câu lệnh đầu tiên có chức năng
if conditionA:
    # Code here executes when 'conditionA' is True
else:
    # Code that runs when 'conditionA' is False

    if conditionB:
        # Code that runs when 'conditionA' is False
        # and 'conditionB' is True
4 nói điều gì đó nhảm nhí.

Sau đó, chúng tôi thực hiện hai câu tuyên bố nếu được lồng nhau. Đầu tiên kiểm tra biến

if conditionA:
    # Code that executes when 'conditionA' is True

    if conditionB:
        # Code that runs when 'conditionA' and
        # 'conditionB' are both True
7. Vì biến đó là
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
7, nên câu lệnh IF IF này không thực thi.

Các tuyên bố khác được lồng nhau nhìn lên

if conditionA:
    # Code that executes when 'conditionA' is True

    if conditionB:
        # Code that runs when 'conditionA' and
        # 'conditionB' are both True
9. Biến đó là
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
5, và vì vậy Python thực thi mã của nó. Có chức năng
if conditionA:
    # Code here executes when 'conditionA' is True
else:
    # Code that runs when 'conditionA' is False

    if conditionB:
        # Code that runs when 'conditionA' is False
        # and 'conditionB' is True
4 chúc người đó hạnh phúc lái xe. Lưu ý rằng chúng tôi không phải kiểm tra xem người đó là người lớn; Đó là một cái gì đó hàng đầu nếu tuyên bố đã làm. Vì vậy, thông điệp lái xe hạnh phúc chỉ có thể hiển thị cho người lớn.

Ở đây, đầu ra mà chương trình tạo ra:

You're 18 or older. Welcome to adulthood!
Happy driving!

# Ví dụ: Nested nếu điều đó xử lý hàng tồn kho sản phẩm

Trong chương trình dưới đây, chúng tôi so sánh kích thước của một đơn đặt hàng thương mại điện tử mới với số lượng hàng tồn kho còn lại. Nếu có đủ hàng tồn kho, chúng tôi có một tuyên bố nếu được tuyên bố xem có bao nhiêu gói hàng.

Mã chương trình nhỏ là:

itemsOrdered = 30
itemsInStock = 32

print("Got an order for", itemsOrdered, "items. In stock:", itemsInStock)

# Compare order size against inventory
if itemsOrdered >= itemsInStock:
    print("Resupply the inventory. We're running out!")
else:
    packageCount = round(itemsOrdered / 8)

    if packageCount > 1:
        print("We need multiple packages to fulfil this order!")

Đầu tiên chúng tôi thực hiện hai biến,

age = 19
isGraduated = False
hasLicense = True

# Look if person is 18 years or older
if age >= 18:
    print("You're 18 or older. Welcome to adulthood!")

    if isGraduated:
        print('Congratulations with your graduation!')
    if hasLicense:
        print('Happy driving!')
0 và
age = 19
isGraduated = False
hasLicense = True

# Look if person is 18 years or older
if age >= 18:
    print("You're 18 or older. Welcome to adulthood!")

    if isGraduated:
        print('Congratulations with your graduation!')
    if hasLicense:
        print('Happy driving!')
1. Họ nhận được các giá trị của
age = 19
isGraduated = False
hasLicense = True

# Look if person is 18 years or older
if age >= 18:
    print("You're 18 or older. Welcome to adulthood!")

    if isGraduated:
        print('Congratulations with your graduation!')
    if hasLicense:
        print('Happy driving!')
2 và
age = 19
isGraduated = False
hasLicense = True

# Look if person is 18 years or older
if age >= 18:
    print("You're 18 or older. Welcome to adulthood!")

    if isGraduated:
        print('Congratulations with your graduation!')
    if hasLicense:
        print('Happy driving!')
3. Sau đó, chúng tôi xuất ra các giá trị của chúng với hàm
if conditionA:
    # Code here executes when 'conditionA' is True
else:
    # Code that runs when 'conditionA' is False

    if conditionB:
        # Code that runs when 'conditionA' is False
        # and 'conditionB' is True
4.

Sau đó, một câu lệnh IF/ELSE đánh giá nếu kích thước thứ tự (

age = 19
isGraduated = False
hasLicense = True

# Look if person is 18 years or older
if age >= 18:
    print("You're 18 or older. Welcome to adulthood!")

    if isGraduated:
        print('Congratulations with your graduation!')
    if hasLicense:
        print('Happy driving!')
0) lớn hơn hoặc bằng (
age = 19
isGraduated = False
hasLicense = True

# Look if person is 18 years or older
if age >= 18:
    print("You're 18 or older. Welcome to adulthood!")

    if isGraduated:
        print('Congratulations with your graduation!')
    if hasLicense:
        print('Happy driving!')
6) các mục còn lại trong kho (
age = 19
isGraduated = False
hasLicense = True

# Look if person is 18 years or older
if age >= 18:
    print("You're 18 or older. Welcome to adulthood!")

    if isGraduated:
        print('Congratulations with your graduation!')
    if hasLicense:
        print('Happy driving!')
1). Vì kích thước đơn hàng không lớn hơn những gì công ty có trong kho, Python thực hiện khối mã
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
1.

Ở đó chúng tôi tính toán có bao nhiêu gói đơn hàng này cần. Cho rằng, chúng tôi chia kích thước thứ tự với

age = 19
isGraduated = False
hasLicense = True

# Look if person is 18 years or older
if age >= 18:
    print("You're 18 or older. Welcome to adulthood!")

    if isGraduated:
        print('Congratulations with your graduation!')
    if hasLicense:
        print('Happy driving!')
9 và làm tròn giá trị đó thành một số toàn bộ với hàm
You're 18 or older. Welcome to adulthood!
Happy driving!
0. Chúng tôi lưu trữ kết quả trong biến
You're 18 or older. Welcome to adulthood!
Happy driving!
1.

Một câu lệnh nếu sau đó thấy có nhiều hơn (

You're 18 or older. Welcome to adulthood!
Happy driving!
2)
You're 18 or older. Welcome to adulthood!
Happy driving!
3 là cần thiết. Khi đó,
if conditionA:
    # Code here executes when 'conditionA' is True
else:
    # Code that runs when 'conditionA' is False

    if conditionB:
        # Code that runs when 'conditionA' is False
        # and 'conditionB' is True
4 nói rằng chúng ta cần nhiều gói.

Lưu ý rằng câu lệnh nếu câu nói này an toàn khi cho rằng có đủ các mặt hàng để gửi đi. Đó là vì điều kiện của câu lệnh IF/ELSE đã kiểm tra điều đó. Nếu không có đủ mục, mã

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
1 không thực thi và chúng tôi cũng không được tuyên bố nếu chúng tôi không.

Ở đây, những gì chương trình đầu ra của chương trình trông giống như:

Got an order for 30 items. In stock: 32
We need multiple packages to fulfil this order!

# Ví dụ: Đánh giá đầu vào của người dùng với các câu lệnh Nested If

Tất nhiên lồng nhau nếu các tuyên bố cũng hữu ích trong các kịch bản phức tạp hơn. Một ví dụ về điều đó là chương trình dưới đây. Kịch bản Python này yêu cầu người dùng đặt tên cho thành phố thủ đô của Đức. Chúng tôi theo dõi số lượng người dùng cần và đưa ra gợi ý dựa trên số lượng người dùng đoán.

Mã đầy đủ của chương trình là:

question = "What's the capital of Germany? "
attempts = 0

while True:
    attempts = attempts + 1
    response = input("Attempt #" + str(attempts) + " | " + question)

    if response.lower() == "berlin":
        print("Correct! Thanks for playing")
        break
    else:
        print("Incorrect.")
        if attempts == 1:
            print("Hint: An American president once said:",
                  "Ich bin ein ........")
        if attempts == 2:
            print("Hint: In the Cold War, a wall split this city.")
        if attempts == 3:
            print("Hint: the city name starts with a 'B'.")

Trước tiên chúng tôi thực hiện biến

You're 18 or older. Welcome to adulthood!
Happy driving!
6, trong đó chúng tôi lưu trữ câu hỏi đố vui của chúng tôi để sử dụng sau. Với biến
You're 18 or older. Welcome to adulthood!
Happy driving!
7, chúng tôi đếm được bao nhiêu người đã đoán người dùng đã làm.

Khi chúng ta tạo một vòng lặp

You're 18 or older. Welcome to adulthood!
Happy driving!
8 vô hạn. Khi bắt đầu vòng lặp, chúng tôi tăng biến
You're 18 or older. Welcome to adulthood!
Happy driving!
7 với một. Sau đó, chúng tôi đặt câu hỏi. Cho rằng chúng tôi sử dụng biến
You're 18 or older. Welcome to adulthood!
Happy driving!
6 bên trong hàm
itemsOrdered = 30
itemsInStock = 32

print("Got an order for", itemsOrdered, "items. In stock:", itemsInStock)

# Compare order size against inventory
if itemsOrdered >= itemsInStock:
    print("Resupply the inventory. We're running out!")
else:
    packageCount = round(itemsOrdered / 8)

    if packageCount > 1:
        print("We need multiple packages to fulfil this order!")
1. Chúng tôi lưu trữ câu trả lời của người dùng trong biến
itemsOrdered = 30
itemsInStock = 32

print("Got an order for", itemsOrdered, "items. In stock:", itemsInStock)

# Compare order size against inventory
if itemsOrdered >= itemsInStock:
    print("Resupply the inventory. We're running out!")
else:
    packageCount = round(itemsOrdered / 8)

    if packageCount > 1:
        print("We need multiple packages to fulfil this order!")
2.

Sau đó, chúng tôi đánh giá biến đó với một câu lệnh IF/ELSE. Điều kiện

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
2 có xem liệu câu trả lời trong chữ thường (
itemsOrdered = 30
itemsInStock = 32

print("Got an order for", itemsOrdered, "items. In stock:", itemsInStock)

# Compare order size against inventory
if itemsOrdered >= itemsInStock:
    print("Resupply the inventory. We're running out!")
else:
    packageCount = round(itemsOrdered / 8)

    if packageCount > 1:
        print("We need multiple packages to fulfil this order!")
4) có khớp (
itemsOrdered = 30
itemsInStock = 32

print("Got an order for", itemsOrdered, "items. In stock:", itemsInStock)

# Compare order size against inventory
if itemsOrdered >= itemsInStock:
    print("Resupply the inventory. We're running out!")
else:
    packageCount = round(itemsOrdered / 8)

    if packageCount > 1:
        print("We need multiple packages to fulfil this order!")
5)
itemsOrdered = 30
itemsInStock = 32

print("Got an order for", itemsOrdered, "items. In stock:", itemsInStock)

# Compare order size against inventory
if itemsOrdered >= itemsInStock:
    print("Resupply the inventory. We're running out!")
else:
    packageCount = round(itemsOrdered / 8)

    if packageCount > 1:
        print("We need multiple packages to fulfil this order!")
6 hay không. Khi có, chức năng
if conditionA:
    # Code here executes when 'conditionA' is True
else:
    # Code that runs when 'conditionA' is False

    if conditionB:
        # Code that runs when 'conditionA' is False
        # and 'conditionB' is True
4 cho biết người dùng đã hiểu đúng. Sau đó, chúng tôi dừng vòng lặp với câu lệnh
itemsOrdered = 30
itemsInStock = 32

print("Got an order for", itemsOrdered, "items. In stock:", itemsInStock)

# Compare order size against inventory
if itemsOrdered >= itemsInStock:
    print("Resupply the inventory. We're running out!")
else:
    packageCount = round(itemsOrdered / 8)

    if packageCount > 1:
        print("We need multiple packages to fulfil this order!")
8.

Khi người dùng không hiểu đúng, mã

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
1 sẽ thực thi. Ở đó chúng tôi có ba tuyên bố nếu được lồng nhau. Mỗi người đánh giá một số lần thử khác nhau. Đối với người dùng lần đầu tiên thất bại, câu lệnh Nested Nested đầu tiên cung cấp gợi ý đầu tiên. Trên các lần thử thứ hai và thứ ba, các tuyên bố khác nhau cho các gợi ý khác nhau.

Ở đây, cách thức đầu ra của chương trình có thể nhìn:

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
0

Thay vì sử dụng một số câu lệnh nếu được lồng nhau, chúng tôi cũng có thể mã hóa chương trình này với một loạt các câu lệnh IF được xâu chuỗi lại với nhau. Xem Python sườn xếp tầng nếu tuyên bố để tìm hiểu thêm.

# Các cách khác để mã Python nếu các câu lệnh

Bên cạnh việc đặt một câu tuyên bố IF trong một câu khác, Python cũng có các loại câu lệnh IF khác:

  • Câu lệnh IF thường xuyên thực hiện mã bất cứ khi nào một điều kiện kiểm tra
    #!/usr/bin/python
    
    var = 100
    if var < 200:
       print "Expression value is less than 200"
       if var == 150:
          print "Which is 150"
       elif var == 100:
          print "Which is 100"
       elif var == 50:
          print "Which is 50"
       elif var < 50:
          print "Expression value is less than 50"
    else:
       print "Could not find true expression"
    
    print "Good bye!"
    
    5.
  • Mặt khác, một câu lệnh if/other cũng thực thi mã khi điều kiện kiểm tra
    #!/usr/bin/python
    
    var = 100
    if var < 200:
       print "Expression value is less than 200"
       if var == 150:
          print "Which is 150"
       elif var == 100:
          print "Which is 100"
       elif var == 50:
          print "Which is 50"
       elif var < 50:
          print "Expression value is less than 50"
    else:
       print "Could not find true expression"
    
    print "Good bye!"
    
    7.
  • Với câu lệnh nếu/khác, chúng tôi đặt mã nếu/khác mã bên trong khối mã
    #!/usr/bin/python
    
    var = 100
    if var < 200:
       print "Expression value is less than 200"
       if var == 150:
          print "Which is 150"
       elif var == 100:
          print "Which is 100"
       elif var == 50:
          print "Which is 50"
       elif var < 50:
          print "Expression value is less than 50"
    else:
       print "Could not find true expression"
    
    print "Good bye!"
    
    2 hoặc
    #!/usr/bin/python
    
    var = 100
    if var < 200:
       print "Expression value is less than 200"
       if var == 150:
          print "Which is 150"
       elif var == 100:
          print "Which is 100"
       elif var == 50:
          print "Which is 50"
       elif var < 50:
          print "Expression value is less than 50"
    else:
       print "Could not find true expression"
    
    print "Good bye!"
    
    1 khác. Điều đó làm cho câu lệnh nếu/khác chạy dựa trên câu lệnh IF khác.
  • Và với câu lệnh CASCADED IF, chúng tôi đánh giá một loạt các điều kiện riêng biệt cho đến khi một trong số chúng là
    #!/usr/bin/python
    
    var = 100
    if var < 200:
       print "Expression value is less than 200"
       if var == 150:
          print "Which is 150"
       elif var == 100:
          print "Which is 100"
       elif var == 50:
          print "Which is 50"
       elif var < 50:
          print "Expression value is less than 50"
    else:
       print "Could not find true expression"
    
    print "Good bye!"
    
    5.

Xem tất cả các bài viết trong danh mục IF để tìm hiểu nhiều hơn về Python IF Statements.

# Bản tóm tắt

Một câu lệnh Nested là một câu lệnh IF được đặt bên trong một câu lệnh khác. Có hai cách để làm một.nested if statement is an if statement placed inside another if statement. There are two ways to make one.

Chúng ta có thể đặt một câu lệnh IF bên trong mã

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
2 của câu lệnh IF khác. Trước khi câu lệnh nếu câu lệnh thực thi, cả điều kiện của nó và câu lệnh nếu câu lệnh trước phải là
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
5.

Ngoài ra, chúng tôi làm tổ một câu lệnh IF bên trong mã

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
1 của câu lệnh IF/ELSE. Điều đó vẫn yêu cầu điều kiện Nested IF Statement là
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
5, nhưng bây giờ điều kiện của trước đó nếu/khác phải là
#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"
7.

Bất kể cách chúng tôi thực hiện một câu lệnh nếu được lồng, thực thi của nó luôn phụ thuộc vào câu lệnh nếu hoặc nếu/khác.

Người giới thiệu

Lutz, M. (2013). Học Python (Phiên bản thứ 5). Sebastopol, CA: O hèReilly Media.

Matthes, E. (2016). Python Crash Course: Một phần giới thiệu thực hành, dựa trên dự án về lập trình. San Francisco, CA: Không có báo chí tinh bột.

Python.org (N.D.). Báo cáo ghép. Truy cập vào ngày 10 tháng 8 năm 2019, từ https://docs.python.org/3/reference/compound_stmts.html

Xuất bản ngày 30 tháng 8 năm 2019.

«Tất cả Python nếu/bài viết khác

Được lồng nếu

Trả lời 1: Có, bạn có thể.Một nếu là một câu lệnh IF là mục tiêu của câu lệnh IF khác.Lồng nhau nếu các câu lệnh đề cập đến một câu lệnh IF bên trong một câu lệnh khác.Yes, you can. A nested if is an if statement that is the target of another if statement. Nested if statements refers to an if statement inside another if statement.

Là lồng nhau nếu

11. If-Else được cho phép trong Python?Expl: Có! Nested if-else được phép trong Python.Yes! Nested if-else is allowed in Python.

Được lồng nếu

Nó luôn luôn hợp pháp trong việc lập trình C để làm tổ IF-Else, điều đó có nghĩa là bạn có thể sử dụng một câu nếu hoặc khác nếu câu lệnh khác nếu hoặc khác nếu câu lệnh., which means you can use one if or else if statement inside another if or else if statement(s).

Tại sao chúng ta sử dụng lồng nhau nếu

Nested nếu các câu lệnh khác được sử dụng để thực thi đoạn mã khác nhau khi chúng ta có nhiều hơn hai tùy chọn để xử lý.to execute different piece of code when we have more than two options to handle.