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
Related
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
Write a program in Python that reads a sequence of integer inputs (data) from the user and then prints the following results:
the total of all the inputs
the smallest of the inputs
the largest of the inputs
the number of even inputs
the number of odd inputs
the average of all of the inputs
You do not know how many numbers the user will want to type in, so you must ask her each time if she has another number to add to the sequence.
So far this is my code but I want to know if there's a way without using the sys module
import sys
# declare a variable largest which has smallest integer value
# -sys.maxsize gives the smallest integer value,you can also use any smallest value
largest = -sys.maxsize
# declare a variable smallest, that is assigned with maximum integer value
smallest = sys.maxsize
# declare variables total to store the sum of all numbers
total = 0
# option variable is to store the user option Y or N
option = 'y'
# declare variables to count odd, even and totalCount
evenCount = 0
oddCount = 0
totalCount = 0
print("This program will calculate statistics for your integer data.")
# run the loop when the user enters y or Y
while option == 'y' or option == 'Y':
# take input of number
number = int(input("Please type a number: "))
# add the number to total
total = total + number
# increase totalCount
totalCount = totalCount + 1
# calculate smallest
if number < smallest:
smallest = number
# calculate largest
if number > largest:
largest = number
# calculate count of even and odd numbers
if number % 2 == 0:
evenCount = evenCount + 1
else:
oddCount = oddCount + 1
option = input("Do you have another number to enter? ")
# calculate average
average = total / totalCount
# print the output
print("\nThe total of your numbers is:", total)
print("The smallest of your numbers is:", smallest)
print("The largest nof yout numbers is:", largest)
print("The number of even numbers is:", evenCount)
print("The number of odd numbers is:", oddCount)
print("The average of your numbers is:", average)
The answer to "can it be done?" when it comes to programming is almost always "yes."
In this case, you can test if you're on the first loop iteration and set smallest and largest accordingly.
E.g.
option = 'y'
first_loop = True
while option.lower() == 'y':
x = int(input("Please type a number: "))
if first_loop:
smallest = x
first_loop = False
elif x < smallest:
smallest = x
option = input("Do you have another number to enter? ")
print(f"Smallest number entered is {smallest}")
You might also collect the input numbers into a list.
option = 'y'
inputs = []
while option.lower() == 'y':
x = int(input("Please type a number: "))
inputs.append(x)
option = input("Do you have another number to enter? ")
Now if you have all of the input numbers in inputs, then calculating a minimum and maximum is just min(inputs) and max(inputs).
Interesting approach, when I have problems like this I use float('inf') or float('-inf'). Can easily be worked into your approach.
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:
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)
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