I am trying to check an array for the largest and smallest number. I have tested multiple times with different numbers and I am getting 9 as my highest value even if I enter a value higher than that. Any thoughts?
index = 0
MAX_NUMBERS = 20
numArray = []
stopProgram = 'ZZZ'
for i in range(0, MAX_NUMBERS):
userNumber = input("Enter a number. 20 numbers total.")
numArray.append(userNumber)
index += 1
largeNum = numArray[0]
smallNum = numArray[0]
for i in range(0,MAX_NUMBERS): #Testing for largest and smallest numbers
if numArray[i] < smallNum:
smallNum = numArray[i]
if numArray[i] > largeNum:
largeNum = numArray[i]
print("Here is your list of numbers: ")
for i in range(0, MAX_NUMBERS):
print("Numbers entered: " + str(numArray[i]))
print("The largest number was: " + str(largeNum))
print("The smallest number was: " + str(smallNum))
By default, all input taken by input() function is of <'str'> data type. The int() function converts it from <'str'> to <'int'> before adding it to the list. Try this:
index = 0
MAX_NUMBERS = 20
numArray = []
stopProgram = 'ZZZ'
for i in range(0, MAX_NUMBERS):
userNumber = int(input("Enter a number. 20 numbers total.")). #wrapped the statement in int() function
numArray.append(userNumber)
index += 1
largeNum = numArray[0]
smallNum = numArray[0]
for i in range(0,MAX_NUMBERS): #Testing for largest and smallest numbers
if numArray[i] < smallNum:
smallNum = numArray[i]
if numArray[i] > largeNum:
largeNum = numArray[i]
print("Here is your list of numbers: ")
for i in range(0, MAX_NUMBERS):
print("Numbers entered: " + str(numArray[i]))
print("The largest number was: " + str(largeNum))
print("The smallest number was: " + str(smallNum))
By the way I would suggest using max and min functions to do the job.
Try wrapping your input with an int so it would be converted to type integer then you can check which number is bigger
Ie
yourNumber = int(input("write number"))
You can also use the min and Max built in python function which would save you more lines of code
Use min
& and max
buildin methods to save you time. Use string formatting
(f-string) rather than append
string for efficiency
index = 0
MAX_NUMBERS = 20
numArray = []
#stopProgram = 'ZZZ'
for i in range(0, MAX_NUMBERS):
userNumber = int(input(f"Enter a number. {MAX_NUMBERS} numbers total."))
numArray.append(userNumber)
index += 1
#largeNum = numArray[0]
#smallNum = numArray[0]
#for i in range(0,MAX_NUMBERS): #Testing for largest and smallest numbers
# if numArray[i] < smallNum:
# smallNum = numArray[i]
# if numArray[i] > largeNum:
# largeNum = numArray[i]
print("Here is your list of numbers: ")
for i in range(0, MAX_NUMBERS):
print("Numbers entered: " + str(numArray[i]))
print(f"The largest number was: {max(numArray)}")
print(f"The smallest number was: {min(numArray)}")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.