0

i want a print current index of array using:

import os
import datetime
import time

a = time.strftime("%d", time.localtime())
list1 = ["123", 123, 123, 132, 123, 123, 123, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
print(list1[a])
input('Press ENTER to exit')

But console is close What happen?

huh_again
  • 35
  • 1
  • 7
  • What does "*console is close (error)*" mean? Please provide all output (and error messages) that you are getting. – walnut Oct 25 '19 at 16:18
  • @uneven_mark Console not have errors.. Console closing. I edited code. – huh_again Oct 25 '19 at 16:20
  • Python is not responsible for closing your console. What OS are you using and how are you running the script? Try opening a command line and running the script from there, so that you can see all error messages printed, after Python exited. – walnut Oct 25 '19 at 16:22
  • @uneven_mark Window 10, how see? – huh_again Oct 25 '19 at 16:27
  • I am not too familiar with Windows. Try [this question](https://stackoverflow.com/questions/4621255/how-do-i-run-a-python-program-in-the-command-prompt-in-windows-7), although it may be out-of-date for Python 3.x (I don't know). – walnut Oct 25 '19 at 16:33

3 Answers3

0

I dont think you can pass a string to a list index

print(list1[a]) # Lists take integers as indices
0

I don't know what does it means that the console is closing without an error.

when running you code I get the following, using python 2.7:

>>> print(list1[a])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str

This is caused because the return of time.strftime("%d", time.localtime()) is a string variable.

The change in your code needs to be:

print(list1[int(a)])

which will transform that string into an integer.

do notice that there is a lot of issue you need to take care of:

  1. make sure that the number string you assigning to a is valid
  2. make sure you you don't enter an index that does not exist
David
  • 8,113
  • 2
  • 17
  • 36
0

Try this instead, i hope it gives you the output you needed!

a = int(time.strftime("%d", time.localtime()))
list1 = ["123", 123, 123, 132, 123, 123, 123, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
print(list1[a])