-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_function.py
More file actions
215 lines (168 loc) · 5.55 KB
/
Copy pathpython_function.py
File metadata and controls
215 lines (168 loc) · 5.55 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# python_function.py
# --------------------------------------------
# Basic practice with Python functions
# --------------------------------------------
print("=== Python Functions Practice ===\n")
# ------------------------------------------------
# 1. What is a function? (in code comments)
# ------------------------------------------------
# A function is a named block of code that:
# - Does ONE specific job
# - Can be reused many times
# - Can take input (parameters/arguments)
# - Can return a result (with 'return')
#
# Basic shape:
# def function_name(parameters):
# # code
# return something # optional
#
# We use functions to:
# - avoid repeating code (DRY: Don't Repeat Yourself)
# - organize our program into small pieces
# - make code easier to read and test
# ------------------------------------------------
# 2. Simple function: no parameters, no return
# ------------------------------------------------
def say_hello():
"""Print a simple greeting."""
print("Hello from a function!")
print("2) Calling say_hello() three times:")
say_hello()
say_hello()
say_hello()
print() # blank line
# ------------------------------------------------
# 3. Function with a parameter
# ------------------------------------------------
def greet(name):
"""Greet a person by name."""
print(f"Hello, {name}! Nice to meet you.")
print("3) Calling greet() with different names:")
greet("Loc")
greet("Tanner")
greet("Angie")
print()
# ------------------------------------------------
# 4. Function with parameters and a return value
# ------------------------------------------------
def add(a, b):
"""Return the sum of a and b."""
result = a + b
return result
print("4) Using add(a, b):")
x = 10
y = 5
sum_result = add(x, y)
print(f"{x} + {y} = {sum_result}")
print()
# ------------------------------------------------
# 5. Function that checks even/odd (int + bool)
# ------------------------------------------------
def is_even(number):
"""Return True if number is even, False otherwise."""
return number % 2 == 0
print("5) Checking if a number is even or odd (user input):")
user_number_str = input("Enter a whole number: ")
user_number = int(user_number_str)
if is_even(user_number):
print(user_number, "is even")
else:
print(user_number, "is odd")
print()
# ------------------------------------------------
# 6. Function working with strings
# ------------------------------------------------
def format_full_name(first_name, last_name):
"""
Return a nicely formatted full name.
- strip() removes spaces from start/end
- title() capitalizes first letter of each word
"""
full_name = f"{first_name.strip().title()} {last_name.strip().title()}"
return full_name
print("6) Formatting a full name with a function:")
fn = input("First name: ")
ln = input("Last name: ")
nice_name = format_full_name(fn, ln)
print("Formatted full name:", nice_name)
print()
# ------------------------------------------------
# 7. Function for number conversion (float + math)
# ------------------------------------------------
def c_to_f(celsius):
"""Convert Celsius to Fahrenheit."""
return celsius * 9 / 5 + 32
print("7) Converting Celsius -> Fahrenheit:")
c_str = input("Temperature in Celsius: ")
c_val = float(c_str)
f_val = c_to_f(c_val)
print(c_val, "°C is", f_val, "°F")
print()
# ------------------------------------------------
# 8. Function that returns multiple values (tuple)
# ------------------------------------------------
def word_stats(text):
"""
Return basic stats about a string:
- number of characters
- number of words
"""
chars = len(text)
words = len(text.split())
return chars, words
print("8) Word stats (characters and words):")
sentence = input("Type a sentence: ")
char_count, word_count = word_stats(sentence)
print("Characters:", char_count)
print("Words:", word_count)
print()
# ------------------------------------------------
# 9. Small function challenges (with solutions)
# ------------------------------------------------
def max_of_two(a, b):
"""Return the bigger of two numbers."""
if a > b:
return a
else:
return b
# could also be: return a if a > b else b
def is_positive(n):
"""Return True if number is positive, False if zero or negative."""
return n > 0
def repeat_text(text, times):
"""Return the text repeated 'times' times."""
return text * times
print("9) Extra function examples:")
print("max_of_two(10, 3) =", max_of_two(10, 3))
print("max_of_two(-2, -5) =", max_of_two(-2, -5))
print("is_positive(5) =", is_positive(5))
print("is_positive(-1) =", is_positive(-1))
print("is_positive(0) =", is_positive(0))
print("repeat_text('Hi ', 3) ->", repeat_text("Hi ", 3))
print()
# ------------------------------------------------
# 10. Practice ideas for YOU (try editing this file)
# ------------------------------------------------
# Try to:
# 1. Create a function:
# def subtract(a, b):
# # return a - b
# and call it a few times with different numbers.
#
# 2. Create a function:
# def bmi(weight_kg, height_m):
# # return BMI = weight / (height * height)
# then ask user for weight and height and print the BMI.
#
# 3. Create a function:
# def contains_at_symbol(text):
# # return True if "@" in text, else False
#
# 4. Create a function:
# def average(a, b, c):
# # return average of 3 numbers
#
# Edit this file, add your own functions at the bottom,
# run again, and see what happens!
print("=== End of python_function.py ===")