4. Lebih Banyak Alat Pengatur Aliran Control Flow — Dokumentasi Python 3.15.2
Navigasi index modul | berikut | sebelum | Python » 3.15.2 documentation » Tutorial Python » 4. Lebih Banyak Alat Pengatur Aliran Control Flow | Tema | 4. Lebih Banyak Alat Pengatur Aliran Control Flow ¶ As well as the while statement just introduced, Python uses a few more that we will encounter in this chapter. 4.1. Pernyataan if ¶ Mungkin tipe pernyataan yang paling terkenal adalah pernyataan if . Sebagai contoh: >>> x = int ( input ( "Please enter an integer: " )) Please enter an integer: 42 >>> if x < 0 : ... x = 0 ... print ( 'Negative changed to zero' ) ... elif x == 0 : ... print ( 'Zero' ) ... elif x == 1 : ... print ( 'Single' ) ... else : ... print ( 'More' ) ...
More Mungkin ada nol atau lebih bagian elif , dan bagian else adalah opsional. Kata kunci ' elif ' adalah kependekan dari 'else if', dan berguna untuk menghindari indentasi yang berlebihan. Sebuah if ... elif ... elif ... adalah urutan pengganti untuk pernyataan switch atau case yang ditemukan dalam bahasa lain. If you're comparing the same value to several constants, or checking for specific types or attributes, you may also find the match statement useful.
For more details see match Statements . 4.2. Pernyataan for ¶ Pernyataan for dalam Python sedikit berbeda dari apa yang mungkin Anda gunakan di C atau Pascal. Alih-alih selalu mengulangi perkembangan angka dalam aritmatika (seperti dalam Pascal), atau memberikan pengguna kemampuan untuk menentukan langkah iterasi dan kondisi berhenti (seperti C), Python pernyataan for diulangi pada item-item dari urutan apa pun (daftar list atau string), dalam urutan yang muncul dalam urutan.
Misalnya (tidak ada permainan kata-kata): >>> # Measure some strings: >>> words = [ 'cat' , 'window' , 'defenestrate' ] >>> for w in words : ... print ( w , len ( w )) ... cat 3 window 6 defenestrate 12 Kode yang memodifikasi koleksi collection sambil mengulangi koleksi yang sama bisa sulit untuk diperbaiki. Sebagai gantinya, biasanya lebih mudah untuk mengulang salinan koleksi atau membuat koleksi baru: # Create a sample collection users = { 'Hans' : 'active' , 'Éléonore' : 'inactive' , '景太郎' : 'active' } # Strategy: Iterate over a copy for user , status in users . copy () . items (): if status == 'inactive' : del users [ user ] # Strategy: Create a new collection active_users = {} for user , status in users . items (): if status == 'active' : active_users [ user ] = status 4.3.
Fungsi range() ¶ Jika Anda perlu mengulangi urutan angka, fungsi bawaan range() berguna. Ini menghasilkan urutan pregressions aritmatika: >>> for i in range ( 5 ): ... print ( i ) ... 0 1 2 3 4 Titik akhir yang diberikan tidak pernah menjadi bagian dari urutan yang dihasilkan; range(10) menghasilkan 10 nilai, indeks sah legal untuk item dengan urutan panjang 10. Dimungkinkan untuk membiarkan rentang mulai dari nomor lain, atau untuk menentukan kenaikan yang berbeda (bahkan negatif; kadang-kadang ini disebut 'step'): >>> list ( range ( 5 , 10 )) [5, 6, 7, 8, 9] >>> list ( range ( 0 , 10 , 3 )) [0, 3, 6, 9] >>> list ( range ( - 10 , - 100 , - 30 )) [-10, -40, -70] Untuk beralih pada indeks urutan, Anda dapat menggabungkan range() dan len() sebagai berikut: >>> a = [ 'Mary' , 'had' , 'a' , 'little' , 'lamb' ] >>> for i in range ( len ( a )): ... print ( i , a [ i ]) ...
0 Mary 1 had 2 a 3 little 4 lamb Dalam kebanyakan kasus seperti itu, bagaimanapun, lebih mudah untuk menggunakan fungsi enumerate() , lihat Teknik Perulangan . Hal aneh terjadi jika Anda hanya mencetak rentang range : >>> range ( 10 ) range(0, 10) Dalam banyak hal objek dikembalikan oleh range() berperilaku seolah-olah itu adalah daftar list , tetapi sebenarnya tidak. Ini adalah objek yang mengembalikan item berurutan dari urutan yang diinginkan ketika Anda mengulanginya, tetapi itu tidak benar-benar membuat daftar list , sehingga menghemat ruang.
We say such an object is iterable , that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted . We have seen that the for statement is such a construct, while an example of a function that takes an iterable is sum() : >>> sum ( range ( 4 )) # 0 + 1 + 2 + 3 6 Later we will see more functions that return iterables and take iterables as arguments.
In chapter Struktur Data , we will discuss list() in more detail. 4.4. break and continue Statements ¶ The break statement breaks out of the innermost enclosing for or while loop: >>> for n in range ( 2 , 10 ): ... for x in range ( 2 , n ): ... if n % x == 0 : ... print ( f " { n } equals { x } * { n // x } " ) ... break ... 4 equals 2 * 2 6 equals 2 * 3 8 equals 2 * 4 9 equals 3 * 3 The continue statement continues with the next iteration of the loop: >>> for num in range ( 2 , 10 ): ... if num % 2 == 0 : ... print ( f "Found an even number { num } " ) ... continue ... print ( f "Found an odd number { num } " ) ...
Found an even number 2 Found an odd number 3 Found an even number 4 Found an odd number 5 Found an even number 6 Found an odd number 7 Found an even number 8 Found an odd number 9 4.5. else Clauses on Loops ¶ In a for or while loop the break statement may be paired with an else clause. If the loop finishes without executing the break , the else clause executes. In a for loop, the else clause is executed after the loop finishes its final iteration, that is, if no break occurred.
In a while loop, it's executed after the loop's condition becomes false. In either kind of loop, the else clause is not executed if the loop was terminated by a break . Of course, other ways of ending the loop early, such as a return or a raised exception, will also skip execution of the else clause. This is exemplified in the following for loop, which searches for prime numbers: >>> for n in range ( 2 , 10 ): ... for x in range ( 2 , n ): ... if n % x == 0 : ... print ( n , 'equals' , x , '*' , n // x ) ... break ... else : ... # loop fell through without finding a factor ... print ( n , 'is a prime number' ) ...
2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 (Yes, this is the correct code. Look closely: the else clause belongs to the for loop, not the if statement.) One way to think of the else clause is to imagine it paired with the if inside the loop. As the loop executes, it will run a sequence like if/if/if/else. The if is inside the loop, encountered a number of times.
If the condition is ever true, a break will happen. If the condition is never true, the else clause outside the loop will execute. When used with a loop, the else clause has more in common with the else clause of a try statement than it does with that of if statements: a try statement's else clause runs when no exception occurs, and a loop's else clause runs when no break occurs. For more on the try statement and exceptions, see Menangani Pengecualian .
4.6. Pernyataan pass ¶ Pernyataan pass tidak melakukan apa-apa. Ini dapat digunakan ketika pernyataan diperlukan secara sintaksis tetapi program tidak memerlukan tindakan. Sebagai contoh: >>> while True : ... pass # Busy-wait for keyboard interrupt (Ctrl+C) ... Ini biasanya digunakan untuk membuat kelas minimal: >>> class MyEmptyClass : ... pass ... Tempat lain pass dapat digunakan adalah sebagai tempat-penampung place-holder untuk fungsi atau badan bersyarat conditional body saat Anda bekerja pada kode baru, memungkinkan Anda untuk terus berpikir pada tingkat yang lebih abstrak. pass diabaikan secara diam-diam: >>> def initlog ( * args ): ... pass # Remember to implement this! ...
For this last case, many people use the ellipsis literal ... instead of pass . This use has no special meaning to Python, and is not part of the language definition (you could use any constant expression here), but ... is used conventionally as a placeholder body as well. See The Ellipsis Object . 4.7. match Statements ¶ A match statement take
The rest of this page is on the live site.