👉 기본 환경

- Language: Python

- IDE: Replit

 

 

⌨️ 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Import the random module here
import random;
 
# Split string method
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
# 🚨 Don't change the code above 👆
 
#Write your code below this line 👇
print(names);
random_num = random.randint(0len(names));
print(names[random_num] + " is going to buy the meal today!")
IndexError: list index out of range
 
 
 

 

 

🖨️오류

IndexError: list index out of range

 

 

📡 원인

list의 범위를 넘어서는 index 사용

예: list 길이가 5일 때, 인덱스 범위는 0~4이므로 인덱스로 5를 사용하면 IndexError 발생

⭐ 리스트 인덱스 시작값은 0

 

 

📰 해결 방법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Import the random module here
import random;
 
# Split string method
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
# 🚨 Don't change the code above 👆
 
#Write your code below this line 👇
print(names);
random_num = random.randint(0len(names)-1);
print(names[random_num] + " is going to buy the meal today!")
IndexError: list index out of range
 
 
 

list 타입의 변수 names의 길이가 5일 경우, index가 갖을 수 있는 범위를 0~4로 설정해야 함

▶ randint 사용 시, 시작값을 0으로 할 경우에는 종료값은 list 길이 -1

 

👉 기본 환경

- Language: Python

- IDE: Replit

 

 

⌨️ 코드

1
2
3
names = ["Hello""World"];
random_num = random.randint(0, names.len());
 
 
 

 

 

🖨️오류

AttributeError: 'list' object has no attribute 'len'

 

 

📡 원인

list 타입의 names는 내장 메서드로 len()을 갖고 있지 않음

 

 

📰 해결 방법

1
2
3
names = ["Hello""World"];
random_num = random.randint(0len(names));
 
 
 

list 타입의 길이는 len()안에 list 타입의 변수를 매개변수로 전달

 

👉 기본 환경

- Language: Python

- IDE: Replit

 

 

⌨️ 코드

1
2
3
4
5
if height=120:
  print("Yes!");
else :
  print("No");
 
 

 

 

🖨️오류

SyntaxError: invalid syntax

 

 

📡 원인

if 조건문의 내용은 boolean 타입의 true, false로 반환될 수 있어야 함

 

 

📰 해결 방법

1
2
3
4
5
if height>=120:
  print("Yes!");
else :
  print("No");
 
 

true/false를 반환할 수 있도록 부등호 추가

 

1
2
3
4
5
if height==120:
  print("Yes!");
else :
  print("No");
 
 

true/false를 반환할 수 있도록 등호 추가

 

👉 기본 환경

- Language: Python

- IDE: Replit

 

 

⌨️ 코드

1
2
3
4
5
if height>=120:
print("Yes!");
else :
  print("No");
 
 

 

 

🖨️오류

IndentationError: expected an indented block

 

 

📡 원인

if 조건이 true일 경우, 실행되어야하는 부분이 들여쓰기로 작성되어야 인식

 

 

📰 해결 방법

1
2
3
4
5
if height>=120:
  print("Yes!");
else :
  print("No");
 
 

true일 경우, 실행되어야 하는 부분을 들여쓰기하여 작성

 

👉 기본 환경

- Language: Python

- IDE: Replit

 

 

⌨️ 코드

1
2
print(int(weight)/int(height)**2);
 
 
 

 

 

🖨️오류

ValueError: invalid literal for int() with base 10: '1.8'

 

 

📡 원인

int 타입의 값에 1.8 입력

 

 

📰 해결 방법

1
2
print(float(weight)/float(height)**2);
 
 
 

변수 weight, height 값이 변환 시, 실수일 경우 int()가 아닌 float()으로 형 변환