0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

python構文編

Last updated at Posted at 2018-08-27

xを1から100までのランダムな整数として取得し、
xが80以上の場合にaと、xが60以上の場合はbと、それ以下の場合はcと出力するコードを書け

from random import randint
x = randint(1, 100)

if x >= 80 :
    print("a")
elif x >= 60 :
    print("b")
else :
    print("c")

文字列aが空白でなければaを、空白の場合は"文字が入力されていません"と表示するコードを書け

a = " "
if a == str :
    print(a)
else :
    print("文字が入力されていません。")

出力
"文字が入力されていません。"

whileについて

countの値を1から順番に表示し、10以上になったらループを抜けるwhile文を書け(10は表示しない)

count = 1

while count < 10 :
    print(count)
    count += 1

xに1から10までのランダムの整数を代入し、xが3の倍数の場合にループを抜けるwhile文を書け
また、ループを抜けるまで毎回xの値を表示せよ

from random import randint

while True :
    x = randint(1, 10)
    print(x)
    if x % 3 == 0 :
        break

1から10までのランダムな整数を取るxの2乗の値を当てるゲームを作れ
なお、2回正解する、またはqを入力したらループを抜けゲームが終了するようにせよ

from random import randint
correct = 0

while correct < 2 :
    x = randint(1, 10)
    ans = x**2
    question = "{}の2乗の値は?Qで終了します。".format(x)
    value = input(question)
    if value == str(ans) :
        print("正解です。")
        correct += 1
    elif value == "Q" :
        print("クイズを中断します")
        break
    else :
        print("不正解です。")

for文について

2つのサイコロの目の組み合わせを出力するコードを書け   (1,1)のように

x = range(1, 7)
y = range(1, 7)

for i in x :
    for j in y :
        print("({},{})".format(i,j))

リストをfor文で回し、文字列の場合、1を、それ以外の場合、0を出力するコードを書け

nums = [1,2,3,4,"a",5]
for num in nums :
    if isinstance(num, str) :
        print(1)
    else :
        print(0)

try文

2つの引数a,bを取り、a / bを返す関数を作れ。
ただし、例外が発生した場合は"エラー"という文字列を返す仕様にせよ。

def func(a, b):
        try :
            print(a / b)
        except :
            print("エラー")
            
func(4, "r")

出力結果 エラー

2つの引数a,bを取り、a / bを返す関数を作れ。aとbは文字列かもしれないので整数にせよ。
ただし、整数に変換できない例外が発生した場合は"整数を入力してください"という文字列を、
0除算で例外が発生した場合は、"bは0以外にしてください"という文字列を返す仕様にせよ。
また、例外に関わらず、最後に"処理終了"と表示する機能も含めよ。

def func(a, b) :
    try :
        return int(a) / int(b)
    except ValueError :
        return "整数を入力してください" # 数値に変換できなかった時
    except ZeroDivisionError :
        return "bは0以外にしてください。"
    finally :
        print("処理終了")
    
print(func(4, 2))

リストをfor文で回し、それぞれを2で割った数を出力せよ。例外の場合は、エラー内容を出力せよ。

nums_1 = [1,2,3,4,"a",5] 
for x in nums_1 :
    try :
        print(x // 2)
    except Exception as error :
        print("エラーになりました。")
        print(error) 

本日はここまでお疲れ様でした!

0
3
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?