Code View 1

AY_Dasar_list,tuple,dict.ipynb

Link sumber source code;
// Some code
if expression :
    statement_1
    statement_2
    ....
     else : 
   statement_3 
   statement_4
   ....
a=10
if(a>10):
    print("Value of a is greater than 10")
else :
    print("Value of a is 10")

Value of a is 10

// Some code
if .. elif .. else statement

if expression1 :
         statement_1
         statement_2
         ....   
   
     elif expression2 : 
     statement_3 
     statement_4
     ....     
   elif expression3 : 
     statement_5 
     statement_6
     ....................    
   else : 
     statement_7 
     statement_8
var1 = 1+2j
if (type(var1) == int):
    print("Type of the variable is Integer")
elif (type(var1) == float):
    print("Type of the variable is Float")
elif (type(var1) == complex):
    print("Type of the variable is Complex")
elif (type(var1) == bool):
    print("Type of the variable is Bool")
elif (type(var1) == str):
    print("Type of the variable is String")
elif (type(var1) == tuple):
    print("Type of the variable is Tuple")
elif (type(var1) == dict):
    print("Type of the variable is Dictionaries")
elif (type(var1) == list):
    print("Type of the variable is List")
else:
    print("Type of the variable is Unknown")

Outputnya Type of the variable is Complex

# Nested if .. else statement
Syntax:
     if expression1 :
         if expression2 :
          statement_3
          statement_4
        ....
      else :
         statement_5
         statement_6
        ....
     else :
	   statement_7 
       statement_8
age = 38
if (age >= 11):
  print ("You are eligible to see the Football match.")
  if (age <= 20 or age >= 60):
      print("Ticket price is $12")
  else:
      print("Tic kit price is $20")
else:
    print ("You're not eligible to buy a ticket.")

Outputnya: You are eligible to see the Football match. Tic kit price is $20

### for loop
Like most other languages, Python has for loops, but it differs a bit from other like C or Pascal. In Python for loop is used to iterate over the items of any sequence including the Python list, string, tuple etc. The for loop is also used to access elements from a container (for example list, string, tuple) using built-in function range().

Syntax:

for variable_name in sequence :
    statement_1
    statement_2
    ....
#The list has four elements, indices start at 0 and end at 3
color_list = ["Red", "Blue", "Green", "Black"]
for c in color_list:
    print(c)

Python for Loop dan Fungsi range()

Fungsi range() digunakan untuk menghasilkan deret bilangan bulat yang berurutan. Fungsi ini sering digunakan dalam perulangan for.

Fungsi range() memiliki tiga bentuk dengan parameter sebagai berikut:

  1. range(a)

    • Menghasilkan deret angka dari 0 hingga a-1 (dengan kenaikan 1).

    • Contoh:

      for i in range(5):
          print(i)

      Output:

      0
      1
      2
      3
      4
  2. range(a, b)

    • Menghasilkan deret angka dari a hingga b-1 (dengan kenaikan 1).

    • Contoh:

      for i in range(2, 6):
          print(i)

      Output:

      2
      3
      4
      5
  3. range(a, b, c)

    • Menghasilkan deret angka dari a hingga b-1 dengan langkah c.

    • Contoh:

      for i in range(1, 10, 2):
          print(i)

      Output:

      1
      3
      5
      7
      9

Sintaks for Loop dengan range()

Berikut adalah format umum penggunaan for loop dengan range():

for <variable> in range(<start>, <stop>, <step>):
    # Blok kode yang akan dieksekusi

Jika hanya satu parameter diberikan (range(a)), maka start secara default dimulai dari 0, stop adalah a, dan step adalah 1.

Iterasi dalam Python: Tuple, List, dan Dictionary

Python menyediakan for loop untuk mengiterasi berbagai tipe data seperti tuple, list, dan dictionary. Berikut adalah contoh-contoh yang mudah dipahami:


1. Iterasi pada Tuple

Contoh berikut menghitung jumlah bilangan genap dan ganjil dalam sebuah tuple:

# Deklarasi tuple
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) 

# Inisialisasi variabel penghitung
count_odd = 0
count_even = 0

# Iterasi setiap elemen dalam tuple
for x in numbers:
    if x % 2 == 0:
        count_even += 1  # Jika habis dibagi 2, berarti genap
    else:
        count_odd += 1   # Jika tidak, berarti ganjil

# Menampilkan hasil
print("Jumlah bilangan genap :", count_even)
print("Jumlah bilangan ganjil :", count_odd)

Penjelasan:

  • Modulus operator (%) digunakan untuk mengecek apakah sebuah angka genap (hasil x % 2 == 0) atau ganjil (x % 2 != 0).

  • Loop for menelusuri setiap elemen dalam tuple dan meningkatkan count_even atau count_odd sesuai dengan hasil modulus.


2. Iterasi pada List

Dalam contoh berikut, kita akan mencetak setiap elemen dalam list beserta tipe datanya.

# Deklarasi list dengan berbagai tipe data
datalist = [1452, 11.23, 1+2j, True, '4lamdata', (0, -1), [5, 12], {"class": 'V', "section": 'A'}]

# Iterasi setiap elemen dalam list
for item in datalist:
    print("Tipe dari", item, "adalah", type(item))

Penjelasan:

  • type(item) digunakan untuk mendapatkan tipe data setiap elemen dalam list.

  • For loop akan mengiterasi setiap item dan mencetak nilai serta tipe datanya.


3. Iterasi pada Dictionary

Kita bisa mengiterasi dictionary dengan mengakses key atau key dan value sekaligus.

# Deklarasi dictionary
color = {"red": "merah", "blue": "biru", "green": "hijau"}

# Iterasi hanya pada key
for key in color:
    print("Kunci:", key, "-> Nilai:", color[key])

Atau dengan items() untuk mengakses langsung key dan value:

for key, value in color.items():
    print("Kunci:", key, "| Nilai:", value)

Penjelasan:

  • for key in dictionary menelusuri hanya kunci dictionary.

  • dictionary.items() memungkinkan kita mengakses key dan value dalam satu iterasi.

color = {"c1": "Red", "c2": "Green", "c3": "Orange"}
for key in color:
    print(key)
// Output
c1
c2
c3
# Following for loop iterates through its values :

color = {"c1": "Red", "c2": "Green", "c3": "Orange"}
for value in color.values():
   print(value)
// Output
Red
Green
Orange
m_bisdig = dict([
    ('kelas A', 'alam'),
    ('kelas B', 'budi'), 
    ('kelas C', 'cinta') ])

m_bisdig
// Output
{'kelas A': 'alam', 'kelas B': 'budi', 'kelas C': 'cinta'}
#DICTIONARY ERROR
m_bisdig = dict([
    ('kelas A', 'alam', 'anton', 'ali'),
    ('kelas B', 'budi', 'badu','beni' ),
    ('kelas C', 'cinta','chika', 'chandar') ])

m_bisdig
person = {}
person['fname'] = 'Joe'
person['lname'] = 'Fonebone'
person['age'] = 51
person['spouse'] = 'Edna'
person['children'] = ['Ralph', 'Betty', 'Joey']
person['pets'] = {'dog': 'Fido', 'cat': 'Sox'}

person
x = {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
x

Last updated