Python Sintaksia: Vigeu, Aina za Data, Masharti, Vitanzi

Vigezo na Aina za Data

Python ni lugha ya programu iliyochapishwa kwa nguvu, ikimaanisha kuwa hauitaji kutangaza aina tofauti kabla ya kuzitumia. Ifuatayo ni mifano ya tamko tofauti na baadhi ya aina za data za kawaida:

Tangazo linalobadilika:

variable_name = value

Aina za data za kawaida:

  • Nambari kamili( int): age = 25
  • Nambari ya sehemu ya kuelea( float): pi = 3.14
  • Kamba( str): name = "John"
  • Boolean( bool): is_true = True

 

Kauli za Masharti

Taarifa za masharti katika Python hutumika kuangalia hali na kutekeleza taarifa kulingana na matokeo ya tathmini. Miundo ya if, else, na elif(la sivyo ikiwa) inatumika kama ifuatavyo:

if kauli:

if condition:  
    # Execute this block if condition is True  

else kauli:

else:  
    # Execute this block if no preceding if statement is True  

elif (else if) kauli:

elif condition:  
    # Execute this block if condition is True and no preceding if or else statement is True  

 

Vitanzi

Python inasaidia aina mbili za kitanzi zinazotumika kawaida: for kitanzi na while kitanzi, kuwezesha utekelezaji unaorudiwa wa taarifa.

for kitanzi:

for variable in sequence:  
    # Execute statements for each value in the sequence  

while kitanzi:

while condition:  
    # Execute statements while the condition is True  

 

Mfano Maalum:

# Variable declaration  
age = 25  
name = "John"  
  
# Conditional statement  
if age >= 18:  
    print("You are of legal age.")  
else:  
    print("You are not of legal age.")  
  
# Loop  
for i in range(5):  
    print("Hello there!")  
  
count = 0  
while count < 5:  
    print("Loop number:", count)  
    count += 1  

Inapotekelezwa, msimbo ulio hapo juu utaangalia umri na kuchapisha ujumbe unaofaa, kisha uzungushe ujumbe Hello there!  mara tano kwa kutumia for kitanzi, na hatimaye uchapishe thamani za while kitanzi.