Find Largest and Smallest number code not working on python - python

Design a program with a loop that lets the user enter a series of numbers. The user should enter - 99 to signal the end of the series. After all the numbers have been enter been entered, the program should display the largest and smallest numbers entered.
when I go to run my program and enter a number like "4" it returns saying the smallest and largest number is 4. But when I want to put a series of numbers like "3,4,5" it gives an error. I don't know if I am typing it wrong or if there is an issue with my program. Let me know what you guys think
def main():
displayWelcome()
inputNum = int(); smallest = int(); largest = int()
smallest = None
largest = None
SENTINEL = -99
# program description
while True:
inputNum=int(input('Enter a number (Zero indicates end of input): '))
if inputNum == SENTINEL:
print('End of program')
break
if smallest is None or inputNum < smallest:
smallest = inputNum
if largest is None or inputNum > largest:
largest = inputNum
displayLargestSmallest(largest, smallest)
def displayWelcome():
print ('This program displays the largest and smallest numbers \
entered by the user from a series of numbers')
def displayLargestSmallest(largest, smallest):
#module to display numbers input
print('The largest number input is ', largest)
print('The smallest number input is', smallest)

You are complicating things, now you will receive a set of numbers in an array, and you will extract the largest number, its number, and the smallest number and print it as follows:

Related

How do I stop Python from splitting a double digit integer into two single integers in my code

This is the task
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
intnum = int(num)
except ValueError:
print('Invalid')
continue
for size in (num):
if largest is None:
largest = size
if smallest is None:
smallest = size
if largest < size:
largest = size
if smallest > size:
smallest = (size)
print("Maximum is", largest)
print('Minimum is', smallest)type here
The code works when I use one digit numbers but if i use a double digit number like 10 then then it prints 0 as the smallest number
for example if I entered
1,3,10,2,6, done
even though the smallest number is 1 it would print:
maximum is 6
minimum is 0
I'm struggling to figure it out so any help would be appreciated, thanks!
You were almost right, you can remove the for loop and just compare the maximum and minimum values with the intnum variable. The code would look like this.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
intnum = int(num)
except ValueError:
print('Invalid')
continue
if largest is None:
largest = intnum
if smallest is None:
smallest = intnum
if largest < intnum:
largest = intnum
if smallest > intnum:
smallest = (intnum)
print("Maximum is", largest)
print('Minimum is', smallest)
This works fine.
You can reduce if statement by apply reverse cycology.
From starting initializing largest with the smallest value i.e(float('-inf')) and smallest with the largest value i.e.(float('inf'))
and checking the user input if the number>largest modify largest. number<smallest modify smallest
One edgecase let's say user not input any number directly rights done than it will print inf -inf which is not correct. so just converted them into no minimum no maximum
Code:
largest = float('-inf')
smallest = float('inf')
while True:
num = input("Enter a number: ")
if num.lower() == "done": #Works for Done also..
break
try:
intnum = int(num)
except ValueError:
print('Invalid')
continue
if intnum>largest:
largest=intnum
if intnum<smallest:
smallest = intnum
print("Maximum is", largest if largest!=float('-inf') else 'No maximum')
print('Minimum is', smallest if smallest!=float('inf') else 'No minimum')
Also you can take both if inside the try statement also..!
Output:
When user not input any number
Enter a number: done
Maximum is No maximum
Minimum is No minimum
When user input only one number
Enter a number: 4
Enter a number: done
Maximum is 4
Minimum is 4
Normal case when user input more than 1 number
Enter a number: 2
Enter a number: 7
Enter a number: 1
Enter a number: 3
Enter a number: 8
Enter a number: 9
Enter a number: done
Maximum is 9
Minimum is 1

How to find the smallest number using a while loop?

I cannot use min, boolean or any other keyword or function.
they can enter positive or negative number, so the smallest value will be set as their first number. If they enter 0 as the first number, a program aborted message will appear. Otherwise, they can enter number and then, hit 0. Then a message will pop up stating the smallest number.
def main():
smallest = 0
while smallest == 0 :
num = int(input("Please enter a number "))
if num==0:
print("Program aborted")
elif smallest == 0:
smallest = num
elif num < smallest:
num = smallest
num = int(input("Please enter a number "))
print("Your smallest number was", smallest)
main()
so with this code, it will print two numbers and it will give the smallest. but it shouldn't automatically stop after two numbers, it should stop after 0 is entered.
You don't need to take seperate input for the smallest.
Please use the below code. It will find you the smallest number.
def main():
smallest = None
while True :
num= int(input("Please enter a number "))
if num == 0:
print("Program aborted")
break
elif smallest is None:
smallest = num
elif num < smallest:
smallest = num
print("Your smallest number was", smallest)
main()
Output:
Please enter a number 5
Please enter a number 3
Please enter a number 2
Please enter a number -10
Please enter a number 6
Please enter a number 0
Program aborted
Your smallest number was -10
you can do something like this:
nums = [int(i) for i in input("Enter the numbers seperated by a space:\n" ).split()]
smallest = nums[0]
for num in nums:
if num < smallest:
smallest = num;
print(f"The smallest number out of {nums}, is {smallest}");
what the code does is first it allows you to input a string of numbers, (separated by a space of course), and then takes each number and puts it in a list. Then it temporarily sets the smallest number to the first number in the list, and iterates through the list one by one to check the numbers in the list against the smallest number. If the current number that it is checking is smaller than the smallest number variable, then it becomes the new smallest number. At the end, it prints out the smallest number in a print statement.
oops sorry forgot it had to use a while loop

How to use max() and min() for two or three digit numbers from user input

I am trying to find the maximum and minimum values of a series of numbers inputted by the user. I get only a semantic error, where both the max and min values are the last number inputted by the user.
This is what I have tried:
largest = None
smallest = None
while True:
snum = input("Enter a number: ")
if snum != "done" :
try:
largest = max(snum)
smallest = min(snum)
except:
print("Invalid Input")
continue
else:
break
print("Maximum is",largest)
print("Minimum is",smallest)
I used the try and except block to error check the user input.
I checked other similar questions such as: How to show max the max and min from user input, but I did not really understand the answer given.
Your first problem is here:
inum = int(snum)
largest = max(snum)
smallest = min(snum)
You're converting the user value (which always comes in as a string) into an integer and storing it in inum. But then you're calling max and min on the original string value, not the number.
Your second problem is that you are only ever checking one number at a time - snum is always filled with the latest number, with other numbers being forgotten.
You need to store each inputted number in a list, and then call max and min on the list as a whole.
Here's a potential solution:
num_list = []
while True:
user = input("Enter a number: ")
if user == "done":
break
try:
inum = int(user)
num_list.append(inum)
except:
print("Invalid input!")
print("The largest number was", max(num_list))
print("The smallest number was", min(num_list))

Python code returning error depending on IDE

I am doing a course and the code is one of the excercises.
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
I believe I have found correct code to pass the assignment - it does work fine in Pycharm, however when I try to submit it on the web IDE it returns different value. Could someone explain why this is happening?
I am using Pycharm and tried it also on www.py4e.com website (where returns different output).
largest = None
smallest = None
while True:
num = input("Enter number:")
if num == 'done':
break
try:
num = int(num)
except:
print("Invalid input")
if smallest is None or num < smallest:
smallest = num
if largest is None or largest > num:
largest = num
print("Maximum", largest)
print("Minimum", smallest)
In Pycharm it returns:
Maximum is 10
Minimum is 2
At www.py4e.com it returns:
Maximum is 2
Minimum is 2
Change the condition for the largest number and also, place if statements inside try block as below or else it will break before taking another input.
largest = None
smallest = None
while True:
num = input("Enter number:")
if num == 'done':
break
try:
num = int(num)
if smallest is None or num < smallest:
smallest = num
if largest is None or largest < num:
largest = num
except:
print("Invalid input")
print("Maximum", largest)
print("Minimum", smallest)

While loop won't terminate

Learning Python. This task is to allow the user to enter numbers as long as the number isn't -99. If the sentinel -99 is entered, the user will no longer be able to enter numbers, and the largest and smallest numbers that have already been entered will be displayed. When I enter the number -99, however, the loop continues to ask for new numbers.
#main module
def main():
#Instructions for user
print ("This program will allow the user to enter several numbers,
positive ")
print ("or negative, and sort the largest and smallest numbers from
them.")
#First number entered by user
inputNum = input ("Enter a number other than -99 to be sorted: ")
#variables
number = inputNum
small=number
large=number
#while loop for getting/sorting numbers
while number != -99:
if number < small:
small = number
elif number > large:
large = number
inputNum = input("Enter a number other than -99 to be sorted: ")
lgSm()
#Module for displaying large and small numbers
def lgSm():
print ("The largest number you entered is: ", large)
print ("The smallest number you entered is: ", small)
main()
Edit:
Solved. I forgot to add the variables inside the ()...I'm not sure what these are called, but I do understood their function. Are they called placeholder variables?
#main module
def main():
#Instructions for user
print ("This program will allow the user to enter several numbers, positive ")
print ("or negative, and sort the largest and smallest numbers from them.")
#First number entered by user
inputNum = int (input ("Enter a number other than -99 to be sorted: "))
#variables
number=inputNum
small=number
large=number
while number != -99:
if number < small:
small = number
elif number > large:
large = number
inputNum = int (input("Enter a number other than -99 to be sorted: "))
number = inputNum
lgSm(large, small)
#Module for displaying large and small numbers
def lgSm(lg, sm):
print ("The largest number you entered is: ", lg)
print ("The smallest number you entered is: ", sm)
main()
Modify your while loop to update number variable; the value of number is not changing inside the loop
while number != -99:
if number < small:
small = number
elif number > large:
large = number
inputNum = int(input("Enter a number other than -99 to be sorted: "))
number = inputNum ## this line in particular

Categories

Resources