+ 2
Hello guys i have a question. Actually i'm very beginner in programming.
I want to know how to call the string in input using number in python? for example i have 3 strings "apple", "banana", "orange" "apple" = 1 "banana" = 2 "orange" = 3 so when i put no 1 in input and the output will be "apple" no 2 is "banana" and no 3 is "orange" anyone knows? Thank you!
14 Réponses
+ 7
# Access a list by index.
lst = ["apple", "banana", "orange"]
sel = int(input())
print(lst[sel-1])
+ 6
Ah, ok. I think they were just asking for clarification on how it worked.
+ 4
DrChicken24 Any problem with my answer?
+ 4
I was hoping for a correction - Knowing that I'm not the best at Python. I assumed that the question was asking for numerical input to get string returns, but perhaps it wasn't the case?
+ 3
I am not sure I understand...
But here:
First, don't put quotation marks around the words.
When you say print(1), it will be an error because you didn't define 1. Quite the contrary, you defined apple as 1 instead of 1 as apple.
So if you do print(apple), the output will be 1.
+ 3
Hatsy Rei Thank you so much! its worked! I appreciate that.😁
+ 3
you can do it easly using lists :
fruits = [ "apple", "banana", "orange" ]
'''
note that computers start counting from 0 , not from 1,
so the first item's index is 0 , second is 1 and so on .
'''
user_input = ( int(input(">>> ")) ) - 1
print(
fruits [user_input]
)
___________________________________
we can also add new items to fruits list :
lets add mmm strawberry !
fruits.append("strawberry")
#returns : ["apple", "banana", "orange", "strawberry" ]
___________________________________
we can give it a number !
lest add coconut as a 2nd item , note that computer counts from 0
fruits.insert( 1, "coconut" )
___________________________________
#lets put every thing together ..
fruits = [ "apple", "banana", "orange" ]
fruits.append( "strawberry" )
fruits.insert( 1, "coconut" )
'''
REMEMBER that computers start counting from 0 , not from 1,
so the first item's index is 0 , second is 1 and so on .
'''
user_input = ( int(input(">>> ")) ) - 1
print(
fruits [user_input]
)
#fruits : [ "apple", "coconut", "banana", "orange", "strawberry" ]
+ 2
@Hatsy Rei
Nope, just accidentally clicked dislike instead of like :P
+ 2
Jan Markus the best explaination for me and the code is perfect! Thank you so much!
+ 2
Curios Basant The code is simple but worked. i liked it! Thank you!
+ 2
Ahmad Muhammad Thank you! you have helped to make it more clear for me
+ 1
Hatsy Rei and DrChicken24 Thank you for your help!
+ 1
Hatsy Rei you said you are not best in python but you answer me in just 1 minute! now i'm thinking about my knowlage in python. hmm