dimanche 30 juin 2019

Difference between if and for syntax in Python

I'm new to coding and confused about situations in which to use if vs. for.

In a recent Kaggle micro-lesson, I first tried using for where if was the correct use. The question: "In the cell below, define a function called sign which takes a numerical argument and returns -1 if it's negative, 1 if it's positive, and 0 if it's 0."

My original answer was this:

def sign(num):
    for num < 0:
        return -1
    for num > 0:
        return 1
    for num == 0:
        return 0

The correct answer used if where I used for. So I was wondering, what is the distinction between the two? I couldn't find anything really comparing the two.

Aucun commentaire:

Enregistrer un commentaire