Reputation: 3
Code:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
num = input('Enter a number: ')
a.append(int(num))
a.sort()
print(a)
print(a.index(num))
Output:
Enter a number: 78
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 78, 89]
Traceback (most recent call last):
File "C:\Users\linda keator\PycharmProjects\game_1\main.py", line 8, in <module>
print(a.index(num))
ValueError: '78' is not in list
I made a python program that requests input from the user, which adds to the list of numbers above (fibonacci sequence for no reason).
How do I program it so that it will return the index of the number added from the input? It's sorted smallest to biggest with .sort()
. It says that 78 isn't in the list, even though it's being displayed as part of list just above the error message. What's the issue in my code?
Upvotes: 0
Views: 46
Reputation: 1
You are adding 'str' to a list. Try it like this:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
num = input("Enter Number:")
#a.append(int(num)) here you are appending str
print(type(num))
#Output <class 'str'>
b = int(num)
a.append(b)
a.sort()
print(a)
print(a.index(b))
Upvotes: 0
Reputation: 1796
The last line of code you have it looking for a str, not an integer:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
num = input('Enter a number: ')
a.append(int(num))
a.sort()
print(a)
print(a.index(int(num)))
Upvotes: 0
Reputation: 8962
You're attempting to find the index of num
which is a str
object because it was the return value of the input()
function which always returns a str
. You correctly cast num
to int
when you appended to a
, but this isn't a permanent modification. Before anything you need to do
num = int(num)
Then you can add it to your list
of numbers. A safer approach to this would be to get user input via a while
loop:
def get_integer_input():
while True:
try:
num = int(input("Enter a number: "))
break
except ValueError:
print("Invalid input, try again!\n")
return num
Upvotes: 2