Step 11 Function Practice -- Creating a Practical Program Using the Basics Learned So Far
Last time, we learned the basics of "functions."
This time, let's combine the variables, if statements, for loops, while loops, lists, dictionaries, and functions we have learned so far to create a slightly more practical program!
However, before we do that, I will introduce a new keyword.
1. What is an import statement?
Python comes with convenient toolboxes called "standard libraries" from the start.
By writing an import statement on the first line of your program, you can take out that toolbox and use it.
Example: When using the random module to select a value at random
import randomYou write it like this.
With this, you will be able to use the features of the random module in the code that follows.
Here, let's take up the method called "random.choice()" and learn how to use it first.
What is random.choice()?
random.choice() is a function that randomly picks one element from a list or similar.
Example:
import random
fruits = ["apple", "banana", "orange"]
choice = random.choice(fruits)
print("選ばれたフルーツ:", choice)Every time you run it, one of "apple," "banana," or "orange" from the fruits list will be selected and displayed.
➤ choice = to select means, so
it is easy to remember as "pick one at random" → random.choice().
2. Fortune-telling program
By combining lists, functions, and random.choice(), you can create a simple fortune-telling program.
import random
def omikuji():
results = ["大吉", "中吉", "小吉", "凶"]
choice = random.choice(results)
print("今日の運勢は…", choice, "です!")
# 実行
omikuji()In this program, a different result will be displayed every time you run it. Let's try to predict today's fortune (*^^*)
3. Simple calculator
Let's create a function that receives two numbers and an operator and performs a calculation.
def calc(a, b, op):
if op == "+":
return a + b
elif op == "-":
return a - b
elif op == "*":
return a * b
elif op == "/":
return a / b
else:
return "不明な演算子です"
# 実行例
print(calc(10, 5, "+")) # 15
print(calc(10, 5, "*")) # 50The key is to specify the arithmetic operator symbol as the third argument when calling the function.
I'm sure you can change it into a more fun program, and it would be even better if you used input statements to ask the user for the numbers and the operator, so please give it a try (=゚ω゚)ノ
4. Grade evaluation program
By combining dictionaries and functions, you can process multiple pieces of data at once.
def judge(scores):
for subject, score in scores.items():
if score >= 90:
print(subject, ":", score, "点 → とてもよくできました!")
elif score >= 60:
print(subject, ":", score, "点 → 合格です")
else:
print(subject, ":", score, "点 → もう少しがんばりましょう")
# 実行例
my_scores = {"math": 85, "english": 92, "science": 58}
judge(my_scores)In the for loop, the "key" in the dictionary is stored in the subject variable, and the "value" is stored in the score variable.
This makes it possible to evaluate each subject individually.
This also seems like something you could modify using input statements ( *´艸`)
5. A "Question App" that continues with a while loop
Finally, let's create a simple "Question App" using functions and a while loop.
def ask():
while True:
word = input("好きな食べ物は?(exitで終了):")
if word == "exit":
print("終了します。")
break
else:
print("あなたは", word, "が好きなんですね!")
# 実行
ask()This program is designed to use "while True:" to keep asking for your favorite food until "exit" is entered.
Since this isn't very interesting as is, once you understand this program, be sure to try using the random module to change the content so that various questions are asked randomly!
Practice Problems
Create a function that uses import random to randomly select and display one item from a list of favorite drinks.
Create a function that takes two numbers, performs division, and returns the result (if you try to divide by 0, display "Cannot divide").
Create a function that puts "subjects and scores" into a dictionary, calculates the average score, and returns it.
Using a while loop, wrap a program that keeps asking for a name until the user enters "exit" into a function.
Using a for loop and a function, create a program that displays the "multiplication table for 2".
Summary
You can use standard libraries with import
You can make random selections from a list with random.choice()
By combining functions with the grammar learned so far, you can create practical programs such as a "fortune-telling app," "calculator," "grade evaluator," and "question app."
Are you getting better at writing longer programs?
Next time, we will take these further and challenge ourselves to the step of "growing small apps into larger ones"!
Next article
いいなと思ったら応援しよう!
よろしければ応援お願いします! いただいたチップは引き続きプログラミングや学びについて、皆さんの利益になるようなよい記事を書くことで恩返しをさせていただきます!