ソースコード
#coding:utf-8
#function 関数
# python 内臓関数 built functionの利用
# 既存モジュール
import os
os.system("clear")
import random
# を戻す return
x = random.randint(2,20)
print (f'この乱数は{x:2g}')
import math
d = int(input('何度ですか?'))
a = math.radians(d)
print(f'cos({d})={math.cos(a):5.2f}')
# 自己定義関数の作成と呼び出し
# ある挨拶文を出力する、その回数を引数とする
# 関数の定義 definition
def hello(name):
print(f"Hello {name}!")
def hello_1(name):
print(f"Hello {name}!")
def multi_hello(x, y):
for i in range(x):
hello(y)
def multi_hello_2(x, name):
for i in range(x):
hello_1(name)
# 関数の呼び出し実行 call and execute
name = input('名前: ')
hello(name)
name = input('名前: ')
hello_1(name)
name = input('名前: ')
x = int(input('何回する? '))
multi_hello(x, name)
name = input('名前: ')
x = int(input('何回する? '))
multi_hello_2(x, name)
# 関数の戻り値
#関数return文の戻り値
#単一の戻り値を返す
def add(a,b):
return a+b
#単一の関数戻り値の受取
print(f'3+4={add(3,4)}\n')
x = add(3,4)
print(f'3+4={x}\n')
#複数の戻り値を返す
def plus_minus_mult(a,b):
return a+b,a-b,a*b
#複数の関数戻り値の受取
print(plus_minus_mult(3,5))
c,d,e = plus_minus_mult(3,5)
print(f'\n3+5={c}\n')
print(f'3-5={d}\n')
print(f'3*5={e}\n')
#関数の戻り値
#四則演算関数 加減乗除
def plus(a,b):
return a+b
def minus(a,b):
return a-b
def mult(a,b):
return a*b
def divide(a,b):
if b != 0:
return a/b
else:
return "error"
def getData():
x = int(input('一つの整数を入力してください:'))
return x
def menu():
while True:
print ('''
+ 加算
- 減算
* 乗算
/ 非零除算
以上の演算子を1個だけ入力してください。
''')
op=input('どうぞ: ')
while op in ['+','-','*','/']:
return op
def pmmd(x,y,ch):
if ch =='+':
ans = plus(x,y)
elif ch =='-':
ans = minus(x,y)
elif ch =='*':
ans = mult(x,y)
elif ch =='/':
ans = divide(x,y)
return ans
#プログラム本体
again = True
while again:
print('\n-----------四則演算-----------')
a=getData()
choice = menu()
b=getData()
result = pmmd(a,b,choice)
print(f'\n\t {a} {choice} {b} = {result}\n')
#計算を続けるか
ask = input('計算を続けますか? \n\tEnterキー: 計算を続けます。 他のキー: やめます。 \n')
if ask != "":
again = False
print("Thank YOU!\n")