'I am new to Python and I wonder what is wrong with this code
I am new to Python and I wonder what is wrong with this code, I searched for this,I guess in the end of the make_list function I have to return, and not print(). and in the end I have to write
if name[0]
and not if name[1]
, but what else is wrong with it?
Code:
def make_list(number):
names = []
for item in number:
names.append(input("Enter your name with a capital letter."))
print(names)
number = int(input("How many names need to be entered?"))
names = make_list(number)
for name in names:
if name [1] == 'A':
print("Name", name, "starts with A")
Compiler says:
Traceback (most recent call last):
File "<string>", line 8, in <module>
File "<string>", line 3, in make_list
TypeError: 'int' object is not iterable
Solution 1:[1]
This is my solution:
def make_list(number):
names = []
for _ in range(number):
names.append(input("Enter your name with a capital letter: "))
print(names)
return(names)
number = int(input("How many names need to be entered? "))
names = make_list(number)
for name in names:
if name.startswith('A'):
print("Name", name, "starts with A")
Results:
How many names need to be entered?3
Enter your name with a capital letter.RUNE
['RUNE']
Enter your name with a capital letter.PETER
['RUNE', 'PETER']
Enter your name with a capital letter.ANDERS
['RUNE', 'PETER', 'ANDERS']
Name ANDERS starts with A
Solution 2:[2]
You need to have range(numbers)
to iterate, and you also forgot to return names
from the make_list
function. Also, as the arrays in Python are zero-indexed, you probably want to check if name [0]
def make_list(number):
names = []
for item in range(number):
names.append(input("Enter your name with a capital letter."))
print(names)
return names
number = int(input("How many names need to be entered?"))
names = make_list(number)
for name in names:
if name [0] == 'A':
print("Name", name, "starts with A")
Solution 3:[3]
In python you can not loop through an integer. Try to switch for item in number
with for item in range(number)
I think this will solve your problem.
Solution 4:[4]
for item in number:
looks like you are attemping to repeat the loop number
times. In python you do that like this: for item in range(0, number):
. item
will range from 0
to number-1
Solution 5:[5]
actually number is an integer, the error is saying in line 3 you are trying to loop through an integer which is not possible
Wrong : for item in number
What you may do instead : for item in range(number)
Here is some reading on the range function https://www.w3schools.com/python/ref_func_range.asp
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | user56700 |
Solution 2 | |
Solution 3 | Tkun |
Solution 4 | Andy Brown |
Solution 5 | Aimad Harilla |