Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Writing your own functions (2/5) | Functions
Learn Python from Scratch

book
Writing your own functions (2/5)

All we have learned till now can be used inside the function. For example, you can easily put conditional statements inside the function body.

For example, we can define a function that will check if the number is odd or even.

# 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))
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
Compito

Swipe to start coding

Define a function is_positive checking if the number is positive (in that case return positive), negative (return negative), or equals zero (return zero).

Soluzione

# define a function
def is_positive(n):
if n > 0:
return('positive')
elif n < 0:
return('negative')
else:
return('zero')

# test your function on -5, 0 and 5
print('Number -5 is', is_positive(-5))
print('Number 0 is', is_positive(0))
print('Number 5 is', is_positive(5))

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 7. Capitolo 3
single

single

# define a function
def is_positive(n):
if _ _ _:
return('positive')
elif n < 0:
return('negative')
else:
return('_ _ _')

# test your function on -5, 0 and 5
print('Number -5 is', is_positive(-5))
print('Number 0 is', is_positive(0))
print('Number 5 is', is_positive(5))

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

some-alt