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.
99
1
2
3
4
5
6
7
8
9
10
# 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))
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
99
1
2
3
4
5
6
7
8
9
10
11
12
13
# 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?
Grazie per i tuoi commenti!
Sezione 7. Capitolo 3
single
99
1
2
3
4
5
6
7
8
9
10
11
12
13
# 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
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione