-
Notifications
You must be signed in to change notification settings - Fork 0
/
e_functions_1_solution.py
43 lines (35 loc) · 1.55 KB
/
e_functions_1_solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
## Simple functions exercises - Solutions
# 1. Define a function named `is_two`.
# It should accept one input and return `True` if the passed input is either the number or the string `2`, `False` otherwise.
def is_two(x):
if x == 2 or x == "2":
return True
else:
return False
# 2. Define a function named that prints a greeting to a user, accepting a name parameter.
# Example: `say_hello("Jane")` prints `"Hello, Jane!"`
def say_hello(name):
print("Hello, " + name + "!")
# 3. Define a function that accepts a string argument in this format: 3+4. Your function should return the result (7) as an integer.
def add_numbers(string):
first = int(string[0])
second = int(string[2])
return first + second
# 4. What does this function do? What does it return? Rewrite the function with a better name.
def square(x):
return x * x
# 5. What is the difference between the previous function and this one?
def do_something(x):
print(x * x)
# The difference is that this function prints the result, but does not return it.
# The value cannot be used in other calculations.
# 6. Write a function that accepts two arguments: a string and a letter.
# The function should count the number of occurrences of that letter in the string.
# Example: `count_letter("banana", "a")` should return `3`.
def count_letter(string, letter):
return string.count(letter)
# What does this code do? What is the value of `result`?
def do_something(x):
x = x + 1
result = do_something(4)
# This code does nothing. The value of result is None.