python - Print values of array according to input -
i trying print values of list according user input, i.e. if user inputs 3, prints elements 1, 2 , 3. if user inputs 5, prints elements, 1,2,3,4 , 5. have written below code giving me error:
var1 = [ '1', '2', '3', '4' , '5'] x = input('enter number of sites') print('the values are', var1[1:x] )
this error coming:
slice indices must integers or none or have __index__ method
any appreciated.
in python3, input
built-in function returns string, , since list indices can integers error message.
to fix it, should convert result of input
function integer, this:
var1 = [ '1', '2', '3', '4' , '5'] x = int(input('enter number of sites')) print('the values are', var1[1:x])
you can format string nicely separated commas, instance:
to_print = ', '.join(var[1: x])) print('the values are', to_print)
Comments
Post a Comment