While loop won't terminate - python

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

Related

Calculating a minimum number input without using sys module

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.

Write a program that keeps reading positive numbers from the user until the user entered negative numbers

Write a program that keeps reading positive numbers from the user. The program should only quit when the user enters a negative value. Once the user enters a negative value the program should print the average of all the numbers entered.
Here is my code so far
def main():
number = 1
numbers = []
while (number > 0):
number = int(input("Enter a number, put in a negative number to end: "))
if number > 0 :
numbers.append(number)
ratarata = len(numbers)
print ("Average number entered: ", ratarata)
main()
This is the output:
Rather than having an item counter and a running total, use a list as follows:
list_ = list()
while (n := int(input("Enter a number, put in a negative number to end: "))) >= 0:
list_.append(n)
print('Average number entered: ', sum(list_) / len(list_) if list_ else 0)
Note:
This will fail if the input cannot be converted to int
sum_num=0
count=0
while True:
val=int(input())
if val>=0:
sum_num+=val
count+=1
else:
break
try:
print(sum_num/count)
except ZeroDivisionError:
print(0)
ZeroDivisionError will come when your first input in not positive number
while True: is infinite loop which will take infinite input until condition are true.
This is my working answer
number=1
numbers=[]
while number>0:
number=float(input("Enter a positive number. (or a negative number to quit)"))
if number>0:
numbers.append(number)
print("The sum of your numbers is", sum(numbers))
print("The average is", (sum(numbers)/len(numbers)))

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

Find Largest and Smallest number code not working on 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:

including a loop for the function so it can ask the user to re enter a number if the number is incorrect

I need to modify my program so it includes a prime read with a loop. the document is saying for my getNumber function it should ask the user only to input a number between 2 and 30, the getScores function should ask the user to input a number between 0 and 100. it they don't get a number between that it should tell them re enter a number. I don't get any errors when running the program but not sure what I am missing in order to make sure its running properly to include the re enter a number part. here is the code:
# main
def main():
endProgram = 'no'
print
while endProgram == 'no':
totalScores = 0
averageScores = 0
number = 0
number = getNumber(number)
totalScores = getScores(totalScores, number)
averageScores = getAverage(totalScores, averageScores, number)
printAverage(averageScores)
endProgram = input('Do you want to end the program? yes or no ')
while not (endProgram != 'yes' or endProgram != 'no'):
print('Enter yes or no ')
endProgram = input('Do you want to end the program? (yes or no )')
# this function will determine how many students took the test
def getNumber(number):
number = int(input('How many students took the test: '))
return number
while number < 2 or number > 30:
print('Please enter a number between 2 and 30')
number = int(input('How many students took the test: '))
# this function will get the total scores
def getScores(totalScores, number):
for counter in range(0, number):
score = int(input('Enter their score: '))
return totalScores
while score < 0 or score > 100:
print('Please enter a number between 0 and 100')
score = int(input('Enter their score: '))
return score
# this function will calculate the average
def getAverage(totalScores, averageScores, number):
averageScores = totalScores / number
return averageScores
# this function will display the average
def printAverage(averageScores):
print ('The average test score is: ', averageScores)
# calls main
main()
First suggestion is to change this:
number = int(input('How many students took the test: '))
reason is that, as it is written, this takes the user input and implicitly assumes that it can be cast to an int. What happens if the user enters "hello, world!" as input? It is necessary to take the user input first as a string, and check if it would be valid to convert it:
number = input("enter a number:")
if number.isdecimal():
number = int(number)
Next, the function as a whole has some structural problems:
def getNumber(number):
number = int(input('How many students took the test: '))
return number
while number < 2 or number > 30:
print('Please enter a number between 2 and 30')
number = int(input('How many students took the test: '))
number is passed in as an argument to getNumber. Then the name number is reassigned to the result of reading the user input, and returned... Make sure you understand what the return statement does: once the control flow reaches a return statement, that function terminates, and it sends that value back to the caller. So your while loop never runs.
Maybe this would work better:
def getNumber():
while number := input("enter a number"):
if number.isdecimal() and int(number) in range(0, 31):
return int(number)
print('Please enter a number between 2 and 30')

Categories

Resources