LoginSignup
0
1

More than 1 year has passed since last update.

Python boot camp by Dr.Angela day13

Last updated at Posted at 2021-05-11

Debug

以下に示すプログラムのどこが問題なのか指摘していく。

#Describe_Problem
def my_function():
  for i in range(1, 20):      #1から20まで連番で繰り返す
    if i == 20:               #もしiが20だったら
      print("You got it")     #printする

my_function()                 #my_function()を呼び出す。

#出力結果
何も出力されない

原因>> for i in range(4)が0から数えて4回繰り返すことをふまえると、カウント変数は0ベース(0オリジン)でカウントされると分かる。range(開始数, 終了数)という書き方で、range(1, 20)と書くことで添え字(index)が1番(=1)から19番(=19)までの19個のオブジェクトを生成するので、i=20になることはありえないため、printされない。
解決策>> L2→ for i in range(1,21)にする

[参考]
https://techacademy.jp/magazine/15828
https://naruport.com/blog/2019/8/14/python-tutorial-for-statement-and-range/

#Reproduce_the_Bug
from random import randint
dice_imgs = ["❶", "❷", "❸", "❹", "❺", "❻"]
dice_num = randint(1, 6)
print(dice_imgs[dice_num])

#出力結果 (何回かrunするうちにたまにこうなる)
Traceback (most recent call last):
  File "main.py", line 14, in <module>
    print(dice_imgs[dice_num])
IndexError: list index out of range

原因>> L3でdice_num = randint(1,6)にしているが、dice_imgsには①(index:0)~⑥(index:5)しかなく、仮にdice_num=6が選ばれてしまったらout of rangeになるのでErrorになる。さらに、index:0 (つまり"①")が出力されなくなっている。Errorにならない場合、出力される数としては②~⑥になっている。
解決策>> dice_num = randint(0,5)とする

#Play_Computer
year = int(input("What's your year of birth?"))
if year > 1980 and year < 1994:
  print("You are a millenial.")
elif year > 1994:
  print("You are a Gen Z.")

#出力結果
What's your year of birth?1979
>                              

原因>> 1980年~1994年より前,1994年以降で場合分けをしているので、1994年丁度に生まれた人と1980年以前に生まれた人に対しては何のアクションも示さず、突然プログラム終了となっている。
解決策>> どちらかの「>,<」に等号(=)をつけるのと、else: でそれ以外の場合にどうするかを追記する

#Print_is_Your_Friend
1   pages = 0
2   word_per_page = 0
3   pages = int(input("Number of pages: "))
4   word_per_page == int(input("Number of words per page: "))
5   total_words = pages * word_per_page
6   print(total_words)

#出力結果
Number of pages: 2
Number of words per page: 89
0

原因>> L4→ 「==」になっていることで、左辺と右辺が等しいかどうかを見て、True or Falseを返している。runする中でこれは実際に何の影響も及ぼしていない(ただ0を入れない限りFalseがreturnされているだけ)が、word_per_pageには入力値が渡されていないのでL2で定義したままのword_per_page=0であるため常にtotal=0になっている。
解決策>> L4「==」を「=」に直す

#Use_a_Debugger
1   def mutate(a_list):
2     b_list = []
3     for item in a_list:
4       new_item = item * 2
5     b_list.append(new_item)
6     print(b_list)

mutate([1,2,3,5,8,13])

#出力内容
[26]

原因>> L5→ b_list.appendがfor文の外にあることで、L3&L4で2倍にしたnew_itemが全くb_listに追加されず、最後にnew_itemに格納された26だけがL5のnew_itemに渡されてappendされているため、常に[26]のみが出力されている。本当はa_listの各項目をそれぞれ2倍した値をb_listに格納したいのだろう。
解決策>> L5→ インデントをfor文と揃えて、for文で毎回appendを回すようにする

続きはまた明日...

0
1
0

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
1