Bagaimana Anda menggunakan perintah kecuali di python?

Saat Anda menyertakan klausa

def calculate_bmi(height, weight): """ calculate body mass index (BMI) """ return weight / height**2

Code language: Python (python)
5, klausa else dijalankan setelah klausa

def calculate_bmi(height, weight): """ calculate body mass index (BMI) """ return weight / height**2

Code language: Python (python)
0 dan sebelum klausa

def calculate_bmi(height, weight): """ calculate body mass index (BMI) """ return weight / height**2

Code language: Python (python)
8

Python coba…kecuali…contoh pernyataan lain

Mari kita ambil beberapa contoh penggunaan pernyataan try...except...else

1) Menggunakan pernyataan coba…kecuali…lain untuk alur kontrol

Contoh berikut mengilustrasikan cara menggunakan klausa try...except...else untuk mengembangkan program yang menghitung indeks massa tubuh (BMI)

Pertama, tentukan fungsi untuk menghitung (BMI) berdasarkan tinggi dan berat badan

def calculate_bmi(height, weight): """ calculate body mass index (BMI) """ return weight / height**2

Code language: Python (python)

Kedua, tentukan fungsi lain untuk mengevaluasi BMI

def evaluate_bmi(bmi): """ evaluate the bmi """ if 18.5 <= bmi <= 24.9: return 'healthy' if bmi >= 25: return 'overweight' return 'underweight'

Code language: Python (python)
_

Ketiga, tentukan fungsi

def evaluate_bmi(bmi): """ evaluate the bmi """ if 18.5 <= bmi <= 24.9: return 'healthy' if bmi >= 25: return 'overweight' return 'underweight'

Code language: Python (python)
1 baru yang meminta pengguna untuk memasukkan tinggi dan berat badan, dan mencetak hasil BMI

def main(): try: height = float(input('Enter your height (meters):')) weight = float(input('Enter your weight (kilograms):')) except ValueError as error: print('Error! please enter a valid number.') else: bmi = round(calculate_bmi(height, weight), 1) evaluation = evaluate_bmi(bmi) print(f'Your body mass index is {bmi}') print(f'This is considered {evaluation}!')

Code language: Python (python)
_

Fungsi

def evaluate_bmi(bmi): """ evaluate the bmi """ if 18.5 <= bmi <= 24.9: return 'healthy' if bmi >= 25: return 'overweight' return 'underweight'

Code language: Python (python)
1 menggunakan pernyataan try...except...else untuk mengontrol alurnya. Jika Anda memasukkan tinggi dan berat yang tidak dapat dikonversi ke angka, pengecualian

def evaluate_bmi(bmi): """ evaluate the bmi """ if 18.5 <= bmi <= 24.9: return 'healthy' if bmi >= 25: return 'overweight' return 'underweight'

Code language: Python (python)
4 akan terjadi

Jika tidak ada pengecualian yang terjadi, klausa else akan dijalankan. Ini menghitung indeks BMI dan menampilkan evaluasi

Gabungkan semuanya

def calculate_bmi(height, weight): """ calculate body mass index (BMI) """ return weight / height**2 def evaluate_bmi(bmi): """ evaluate the bmi """ if 18.5 <= bmi <= 24.9: return 'healthy' if bmi >= 25: return 'overweight' return 'underweight' def main(): try: height = float(input('Enter your height (meters):')) weight = float(input('Enter your weight (kilograms):')) except ValueError as error: print(error) else: bmi = round(calculate_bmi(height, weight), 1) evaluation = evaluate_bmi(bmi) print(f'Your body mass index is {bmi}') print(f'This is considered {evaluation}!') main()

Code language: Python (python)
_

2) Menggunakan Python coba…kecuali…lain dan akhirnya contoh

Klausa else dijalankan tepat sebelum klausa

def calculate_bmi(height, weight): """ calculate body mass index (BMI) """ return weight / height**2

Code language: Python (python)
5 jika tidak ada pengecualian terjadi dalam klausa

def calculate_bmi(height, weight): """ calculate body mass index (BMI) """ return weight / height**2

Code language: Python (python)
0

Contoh berikut menunjukkan cara menggunakan klausa ________4______9

fruits = { 'apple': 10, 'orange': 20, 'banana': 30 } key = None while True: try: key = input('Enter a key to lookup:') fruit = fruits[key.lower()] except KeyError: print(f'Error! {key} does not exist.') except KeyboardInterrupt: break else: print(fruit) finally: print('Press Ctrl-C to exit.')

Code language: Python (python)

Bagaimana itu bekerja

  • Pertama, tentukan kamus

    def main(): try: height = float(input('Enter your height (meters):')) weight = float(input('Enter your weight (kilograms):')) except ValueError as error: print('Error! please enter a valid number.') else: bmi = round(calculate_bmi(height, weight), 1) evaluation = evaluate_bmi(bmi) print(f'Your body mass index is {bmi}') print(f'This is considered {evaluation}!')

    Code language: Python (python)
    _0 yang berisi tiga elemen
  • Kedua, gunakan loop

    def main(): try: height = float(input('Enter your height (meters):')) weight = float(input('Enter your weight (kilograms):')) except ValueError as error: print('Error! please enter a valid number.') else: bmi = round(calculate_bmi(height, weight), 1) evaluation = evaluate_bmi(bmi) print(f'Your body mass index is {bmi}') print(f'This is considered {evaluation}!')

    Code language: Python (python)
    _1 untuk berulang kali mendapatkan masukan dari pengguna. Itu menghentikan loop sampai pengguna menekan

    def main(): try: height = float(input('Enter your height (meters):')) weight = float(input('Enter your weight (kilograms):')) except ValueError as error: print('Error! please enter a valid number.') else: bmi = round(calculate_bmi(height, weight), 1) evaluation = evaluate_bmi(bmi) print(f'Your body mass index is {bmi}') print(f'This is considered {evaluation}!')

    Code language: Python (python)
    2
  • Ketiga, gunakan klausa

    def evaluate_bmi(bmi): """ evaluate the bmi """ if 18.5 <= bmi <= 24.9: return 'healthy' if bmi >= 25: return 'overweight' return 'underweight'

    Code language: Python (python)
    _9 di dalam loop

    def main(): try: height = float(input('Enter your height (meters):')) weight = float(input('Enter your weight (kilograms):')) except ValueError as error: print('Error! please enter a valid number.') else: bmi = round(calculate_bmi(height, weight), 1) evaluation = evaluate_bmi(bmi) print(f'Your body mass index is {bmi}') print(f'This is considered {evaluation}!')

    Code language: Python (python)
    1. Kami menggunakan input pengguna untuk menemukan elemen dalam kamus

Jika kunci tidak ada, pengecualian

def main(): try: height = float(input('Enter your height (meters):')) weight = float(input('Enter your weight (kilograms):')) except ValueError as error: print('Error! please enter a valid number.') else: bmi = round(calculate_bmi(height, weight), 1) evaluation = evaluate_bmi(bmi) print(f'Your body mass index is {bmi}') print(f'This is considered {evaluation}!')

Code language: Python (python)
5 terjadi, kecuali klausa akan dijalankan

Jika pengguna menekan

def main(): try: height = float(input('Enter your height (meters):')) weight = float(input('Enter your weight (kilograms):')) except ValueError as error: print('Error! please enter a valid number.') else: bmi = round(calculate_bmi(height, weight), 1) evaluation = evaluate_bmi(bmi) print(f'Your body mass index is {bmi}') print(f'This is considered {evaluation}!')

Code language: Python (python)
2, pengecualian

def main(): try: height = float(input('Enter your height (meters):')) weight = float(input('Enter your weight (kilograms):')) except ValueError as error: print('Error! please enter a valid number.') else: bmi = round(calculate_bmi(height, weight), 1) evaluation = evaluate_bmi(bmi) print(f'Your body mass index is {bmi}') print(f'This is considered {evaluation}!')

Code language: Python (python)
7 terjadi yang mengeksekusi pernyataan

def main(): try: height = float(input('Enter your height (meters):')) weight = float(input('Enter your weight (kilograms):')) except ValueError as error: print('Error! please enter a valid number.') else: bmi = round(calculate_bmi(height, weight), 1) evaluation = evaluate_bmi(bmi) print(f'Your body mass index is {bmi}') print(f'This is considered {evaluation}!')

Code language: Python (python)
8 untuk menghentikan loop

Jika kunci ditemukan di kamus

def main(): try: height = float(input('Enter your height (meters):')) weight = float(input('Enter your weight (kilograms):')) except ValueError as error: print('Error! please enter a valid number.') else: bmi = round(calculate_bmi(height, weight), 1) evaluation = evaluate_bmi(bmi) print(f'Your body mass index is {bmi}') print(f'This is considered {evaluation}!')

Code language: Python (python)
_0, program akan mencetak elemen yang ditemukan

Klausa

def calculate_bmi(height, weight): """ calculate body mass index (BMI) """ return weight / height**2

Code language: Python (python)
8 selalu dijalankan. Ini menunjukkan pengingat kepada pengguna bahwa mereka harus menekan Ctrl-C untuk keluar

Bagaimana Anda menggunakan kecuali dengan Python?

Pernyataan try… exception Python menjalankan kode di bawah pernyataan “try” . Jika kode ini tidak berhasil dijalankan, program akan berhenti di baris yang menyebabkan kesalahan dan kode "kecuali" akan berjalan. Blok coba memungkinkan Anda untuk menguji blok kode untuk kesalahan.

Bagaimana cara mencoba kecuali pernyataan bekerja di Python?

Pernyataan try berfungsi sebagai berikut. .
Pertama, klausa coba (pernyataan antara kata kunci coba dan kecuali) dijalankan
Jika tidak ada pengecualian yang terjadi, klausa pengecualian dilewati dan eksekusi pernyataan try selesai
Jika pengecualian terjadi selama eksekusi klausa try, klausa lainnya akan dilewati

Bagaimana Anda mencetak kecuali dengan Python?

Jika Anda akan mencetak pengecualian, lebih baik menggunakan print(repr(e)) ; dasar Pengecualian. Implementasi __str__ hanya mengembalikan pesan pengecualian, bukan jenisnya. Atau, gunakan modul traceback, yang memiliki metode untuk mencetak pengecualian saat ini, diformat, atau traceback penuh.

Bagaimana Anda kecuali semua pengecualian dengan Python?

Cara lain untuk menangkap semua pengecualian Python saat terjadi selama runtime adalah dengan menggunakan kata kunci raise . Ini adalah proses manual di mana Anda dapat secara opsional meneruskan nilai ke pengecualian untuk mengklarifikasi alasan mengapa itu dimunculkan. jika x