Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Use of if/else Statements in Python Functions | Functions in Python
Introduction to Python (dev copy)

bookUse of if/else Statements in Python Functions

Everything we've discussed up to this point can be utilized within a function. For instance, you can easily embed conditional statements within the body of a function. In the third section, you crafted an if/else statement to determine if a number is odd or even. But, this code is set up for specific numbers.

If you wanted to evaluate a different number, you'd either have to replicate the same code block with a new number or modify the existing number before the conditional check. Instead, it's more efficient to encapsulate this code within a function and then invoke it for various numbers as needed.

12345678910
# Define a function def is_odd(n): if n % 2 == 0: return "even" else: return "odd" # Testing function print('2 is', is_odd(2)) print('3 is', is_odd(3))
copy

Note

Just a heads up: A number is deemed even if it divides by 2 with no remainder. The % operator is used to find this remainder.

Clearly, the function accurately recognizes 2 as even and 3 as odd. You can call upon this function as often as required for various numbers.

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 6. Luku 5

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Suggested prompts:

Kysy minulta kysymyksiä tästä aiheesta

Tiivistä tämä luku

Näytä käytännön esimerkkejä

Awesome!

Completion rate improved to 1.64

bookUse of if/else Statements in Python Functions

Pyyhkäise näyttääksesi valikon

Everything we've discussed up to this point can be utilized within a function. For instance, you can easily embed conditional statements within the body of a function. In the third section, you crafted an if/else statement to determine if a number is odd or even. But, this code is set up for specific numbers.

If you wanted to evaluate a different number, you'd either have to replicate the same code block with a new number or modify the existing number before the conditional check. Instead, it's more efficient to encapsulate this code within a function and then invoke it for various numbers as needed.

12345678910
# Define a function def is_odd(n): if n % 2 == 0: return "even" else: return "odd" # Testing function print('2 is', is_odd(2)) print('3 is', is_odd(3))
copy

Note

Just a heads up: A number is deemed even if it divides by 2 with no remainder. The % operator is used to find this remainder.

Clearly, the function accurately recognizes 2 as even and 3 as odd. You can call upon this function as often as required for various numbers.

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 6. Luku 5
some-alt