Sto provando ad usare list come array e voglio inserire valori interi nell'elenco in modo da poter eseguire alcune operazioni aritmetiche su di esso.
m=int(input())
L'ho sempre usato per ottenere qualche input intero da parte dell'utente.
//creating an array
myArray=[]
inp=int(input("Please enter the length of array you wish to create"))
for m in range(inp):
myArray.append(int(input()))
print(myArray)
Ma questo non funziona, perché?
Errore: letterale non valido per int () con base 10
risposte:
2 per risposta № 1Va bene, dal momento che l'input sarebbe analizzato come una stringa e int
puoi solo stringere stringhe che sono solo numeri in numeri interi ... sei in grossi guai per un input errato poiché fermerebbe immediatamente il tuo programma.
Suggerirei di usare a while
ciclo e try-except
istruzioni di eccezione per la gestione degli errori.
NOTA per Python 2.x: Uso raw_input
da input
risulterebbe in a NameError: name <input_string> is not defined
se si passano caratteri senza virgolette.</ Em>
>>> my_array = [] # camelCase is not the convention in Python
>>>
>>> array_length = None
>>> while array_length is None:
... try:
... array_length = int(input("Please enter the length of array you wish to create: "))
... except ValueError:
... print("Invalid input - please enter a finite number for the array length.")
...
Please enter the length of array you wish to create: 4
>>>
>>> print(array_length)
4
>>> while len(my_array) < array_length:
... try:
... my_array.append(int(input()))
... except ValueError:
... print("Invalid input - please enter a number!")
...
1
abc
Invalid input - please enter a number!
2
3
4
>>>
>>> print(my_array)
[1, 2, 3, 4]
Esecuzione come script
# -*- coding: utf-8 -*-
INVALID_NUMERIC_INPUT_MSG = "Invalid input - please enter a finite number with no spaces!"
KEYBOARD_INTERRUPTION_MSG = "Keyboard interruption: program exited."
def main():
my_array = []
print()
array_length = None
while array_length is None: # accept input until valid
try:
array_length = int(input("Please enter the length of array you wish to create: "))
except ValueError:
print(INVALID_NUMERIC_INPUT_MSG)
except KeyboardInterrupt:
print("n" + KEYBOARD_INTERRUPTION_MSG)
quit()
print("Your array length is {}.".format(array_length))
print()
while len(my_array) < array_length:
try:
my_array.append(int(input()))
except ValueError:
print(INVALID_NUMERIC_INPUT_MSG)
except KeyboardInterrupt:
print("n" + KEYBOARD_INTERRUPTION_MSG)
quit()
assert len(my_array) == array_length # check for program correctness
print()
print("Your array is: {}".format(my_array))
print()
if __name__ == "__main__":
main()
Esecuzione nella mia console:
$ python3 input-program.py
Please enter the length of array you wish to create: 4
Your array length is 4.
1
2
3
4
Your array is [1, 2, 3, 4]
0 per risposta № 2
La forzatura alla coercizione int può essere fatta solo provandola, per vedere se l'input era un numero.
Qui creiamo un array azzerato e un array numerato consecutivamente (un intervallo)
In Python si chiama un array un elenco
array = [0]
try:
array = array * int(raw_input("How long? ->"))
print array
except:
print "try using a number"
O
try:
array = range(int(raw_input("How long? ->")))
print array
except:
print "try using a number"
PS questo è il codice Python v2 non v3