Tuesday, March 19, 2024

Python Tutorial - Loop - 007

Untuk kondisi khusus, eksekusi code bisa diulang (repeat), untuk itu Python menyediakan mekanisme yang disebut "loop." 


Image - Di pedesaan, ilustrasi.

Struktur loop dalam Python adalah: for, while dan nested loops.

Loop "for" dipakai untuk pengulangan "objects" seperti lists, strings dan tuples.
items = ["agus", "benu", "cica", "deli"]

for item in items:
    print(item)
Output: 
agus
benu
cica
deli
>>> 

Using "range"
range() function to make easy to make repeatition
for i in range(1, 10):
print(i)
output:
1
2
3
4
5
6
7
8
9
>>> 


Loop "While"
correctNumber = 5
guess = 0

while guess != correctNumber:
    guess = int(input("Guess the number: "))
if guess != correctNumber:
print('False guess')

print('You guessed the correct number')
Note : No output


Nested Loops
for x in range(1, 10): for y in range(1, 10): print("(" + str(x) + "," + str(y) + ")") SyntaxError: expected an indented block

# Posting sebelumnya:

JJJJJJJJJ

No comments:

Post a Comment