Here is my code below : I created a list of random numbers. There are inputs for variables that should be int or string, but I need to handle the ValueError in case "a" or "b" or "long" is not an integer. In fact, the program should handle the case when the user write "stop" for those values, then the program has to stop. Is there an easy way to do that ?
def rechercheIndiceMin(tab):
mini=tab[0]
indiceMin=0
for i in range(0,len(tab)):
if tab[i]<mini:
mini=tab[i]
indiceMin=i
return("L'indice minimum est :",indiceMin)
def rechercheIndiceMax(tab):
maxi=tab[0]
indiceMax=0
for i in range(0,len(tab)):
if tab[i]>maxi:
maxi=tab[i]
indiceMax=i
return("L'indice maximum est :",indiceMax)
import random
print("Soit un tableau tab de taille long avec des aléas [a,b]")
while True:
try:
a=int(input("Insérez a :"))
b=int(input("Insérez b :"))
long=int(input("Insérez longueur du tableau :"))
tab=[0]*long
if b<a:
buffer=a
a=b
b=buffer
for i in range(0,long):
tab[i]=random.randint(a,b)
break
except ValueError:
print("Insérer un entier svp :")
print(tab)
indiceMin=rechercheIndiceMin(tab)
print(indiceMin)
indiceMax=rechercheIndiceMax(tab)
print(indiceMax)
Thank you very much,
Benoit
At the first input, do not immediately convert to int. Compare the input value with the literal 'stop' and break if it matches. Only then should you try to convert to int.
There's a lot more code in the question than is actually necessary.
Here's an optimised version of the program that also answers the original question:
from random import randint
def recherche(tab, func):
z = func(tab)
for i, x in enumerate(tab):
if x == z:
return i
print("Soit un tableau tab de taille long avec des aléas [a,b]")
while (a := input("Insérez a (ou stop) : ")) != 'stop':
try:
a = int(a)
b = int(input("Insérez b : "))
long = int(input("Insérez longueur du tableau : "))
if a > b:
b, a = a, b
tab = [randint(a, b) for _ in range(long)]
print(tab)
print(recherche(tab, min))
print(recherche(tab, max))
except ValueError:
print("Insérer un entier svp :")