Difference between revisions of "Making AI with Python"
(→Introduction) |
(→Introduction) |
||
| Line 2: | Line 2: | ||
This manual will only work if you know Python. If you don't, go learn it at: [[Getting Started With Python Programming]]. | This manual will only work if you know Python. If you don't, go learn it at: [[Getting Started With Python Programming]]. | ||
| + | ===Program Example 1=== | ||
| + | |||
| + | '''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.''' | ||
| + | |||
| + | We can keep our code and modify some parts of it. | ||
| + | |||
| + | def check(a, min, max): | ||
| + | if a*5 > min - 1 and a*5 < max + 1: | ||
| + | return True | ||
| + | else: | ||
| + | return False | ||
| + | |||
| + | def print_check(range_min, range_max, check_min, check_max): | ||
| + | for i in range(range_min, range_max + 1): | ||
| + | if check(i, check_min, check_max): | ||
| + | print(i) | ||
| + | return | ||
| + | |||
| + | print_check(10, 99, 100, 999) | ||
| + | |||
| + | Why did we add so many functions? | ||
| + | |||
| + | Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though. | ||
| + | |||
| + | If we run our program, we get our answer. | ||
| + | |||
| + | All numbers from 20 to 99 work! | ||
Revision as of 21:57, 14 September 2023
Introduction
This manual will only work if you know Python. If you don't, go learn it at: Getting Started With Python Programming.
Program Example 1
Print all two digit positive integers
such that
is a three digit positive integer.
We can keep our code and modify some parts of it.
def check(a, min, max):
if a*5 > min - 1 and a*5 < max + 1:
return True
else:
return False
def print_check(range_min, range_max, check_min, check_max):
for i in range(range_min, range_max + 1):
if check(i, check_min, check_max):
print(i)
return
print_check(10, 99, 100, 999)
Why did we add so many functions?
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered hard-coded. We want our programs to be as soft-coded as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.
If we run our program, we get our answer.
All numbers from 20 to 99 work!