Why does this while loop not execute properly - python

I'm trying to write a basic code that prompts the user for a list of numbers as separate inputs, that then identifies the largest and smallest number. If the user enters anything other than a number the code should return an "invalid input" message. The code seems to run through the two inputs once, but then the while input seems completely broken and I'm not sure where its going wrong.
largest = None
smallest = None
try:
num1 = input("Enter a number: ")
num1 = int(num1)
largest = num1
smallest = num1
while True:
num = input("Enter a number: ")
if num == "done" :
break
if num > largest:
largest = num
if num < smallest:
smallest = num
else: continue
except:
print('Invalid input')
print("Maximum is ", largest)
print("Minimum is ", smallest)

If you check your exit condition of "done" and if the input is not "done" then convert the string to an integer.
Then all the if conditions would correctly and your while loop should run.
largest = None
smallest = None
try:
num1 = input("Enter a number: ")
num1 = int(num1)
largest = num1
smallest = num1
while True:
num = input("Enter a number: ")
if num == "done" :
break
num = int(num)
if num > largest:
largest = num
if num < smallest:
smallest = num
else: continue
except:
print('Invalid input')
print("Maximum is ", largest)
print("Minimum is ", smallest)

heres a simple way to do it:
lst = []
while True:
try:
lst.append(int(input("enter a number: ")))
except:
break
print(f"max is {max(lst)}")
print(f"min is {min(lst)}")
enter a number: 10
enter a number: 22
enter a number: 11
enter a number: 22
enter a number: 4
enter a number: done
max is 22
min is 4

In addition to other corrections:
largest = None
smallest = None
try:
num1 = int(input("Enter a number: "))
largest = num1
smallest = num1
while True:
num = input("Enter a number: ")
if str(num) == "done" :
break
if int(num) > largest:
largest = num
if int(num) < smallest:
smallest = num
else: continue
except:
print('Invalid input')
print("Maximum is ", largest)
print("Minimum is ", smallest)

Related

How to break loop when int input is empty/blank?

I want the loop to break when user inputs empty/blank and cant figure it out.
Just gives me value error.
a = 0
x = 0
while True:
num1 = int(input("Give number: "))
if num1 == "":
break
x += num1
a += 1
print("Numbers Given: ", a)
print("Sum of numbers: ",x)
a = 0
x = 0
while True:
num1 = input("Give number: ")
if num1 == "":
break
x += int(num1)
a += 1
print("Numbers Given: ", a)
print("Sum of numbers: ",x)
You can try this try-except:
a = 0
x = 0
while True:
try:
num1 = int(input("Give number: "))
except ValueError as err:
print("Empty `number`")
break
x += num1
a += 1
print("Numbers Given: ", a)
print("Sum of numbers: ",x)
Output:
Give number: 2
Give number: 3
Give number:
Empty `number`
Numbers Given: 2
Sum of numbers: 5

Making a Calculator which take input from user until user enter 0 but not working correctly

I am a newbie in python and trying to make a calculator but no getting how to make it
I am making a Calculator which will take input from the user until the user enters 0 and then do the operations
but I am stuck here
if anyone can help me doing this work I will be very thankful to him/her.
num = None
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
options = int(input("Enter Your Choice: "))
# For Addition or Option 1
if options == 1:
total = 0
while(num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total + num
print("Your Calculated Number is: {} ".format(total))
# For Subtraction or Option 2
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
print("Your Calculated Value is: {}".format(total))
# Multiplication for Option 3
elif options == 3:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
# Division for Option 4
elif options == 4:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
# When User Wants to Exit
else:
print("Thank You for Using the Calculator")
Here is a better approach using itertools.reduce. Instead of repeating the same code for inputting a number multiple times, put it into a function. This will also help avoid the errors in your code and clarify the logic. A second generator function can be used to get the series of values until the user enters zero.
from functools import reduce
import operator
def input_number():
while True:
try:
return float(input("(Enter '0' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
def input_series():
while True:
n = input_number()
if n == 0:
return
yield n
operations = {
1: operator.add,
2: operator.sub,
3: operator.mul,
4: operator.truediv
}
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
option = int(input("Enter Your Choice: "))
# For Addition or Option 1
if option == 5:
print("Thank You for Using the Calculator")
else:
total = reduce(operations[option], input_series())
print("Your Calculated Value is: {}".format(total))
Instead of
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
use (the changes are only in the 2nd line and in the last one)
elif options == 2:
total = None
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num if total is not None else num
The same method you may use for the elif options == 4: branch.
The problem with subtraction is that the variable total is not initialized.
The problem with multiplication and division is that when the user inputs "0", the variable total is multiplied or divided by zero before it is checked in the while statement. what I would normally do is this:
elif options == 3:
total = 1
while True:
try:
num = float(input("(Enter '0' When Complete.) Enter Number ")) # No need to escape single quotes when your string uses double quotes
if num == 0:
break
except ValueError:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
However, if you wanted a quick fix, you can have the user input 1 instead of 0 for multiplication and division:
elif options == 4:
total = 1
while (num != 1):
try:
num = float(input("(Enter '1' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
Edit: If you want division to work the way you specified, you could do something like this:
elif options == 2:
total = 1
try:
first_number = float(input("(Enter '0' When Complete.) Enter Number "))
if first_number == 0:
print("Your Calculated Value is: 0")
exit()
except ValueError:
print("Error, Enter Valid Number")
continue
total = 1
while True:
try:
num = float(input("(Enter '0' When Complete.) Enter Number "))
if num == 0:
break
except ValueError:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total + first_number))

Restart Python program if user input to 'run again?' is 'y'

while True:
# main program
number = (" ")
total = 0
num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
while True:
answer = raw_input("Run again? (y/n): ")
if answer in y, n:
break
print("Invalid input.")
if answer == 'y':
continue
else:
print 'Goodbye'
break
Essentially I want the program to restart when the user enters 'y' as a response to 'run again?' Any help would be vastly appreciated. Thanks.
As #burhan suggested, simply wrap your main program inside a function. BTW, your code has some bugs which could use some help:
if answer in y, n: - you probably mean if answer not in ('y', 'n'):
number = (" ") is an irrelevant line
while True makes no sense in your main program
print("Invalid input.") is below a break, thus it'll never be executed
So you'll have something like:
def main():
total = 0
num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
while True:
answer = raw_input("Run again? (y/n): ")
if answer not in ('y', 'n'):
print("Invalid input.")
break
if answer == 'y':
main()
else:
print("Goodbye")
break
def main():
total = 0
num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
answer = raw_input("Run again? (y/n): ")
if answer not in ('y', 'n'):
print("Invalid input.")
if answer == 'y':
main()
else:
print 'Goodbye'
if __name__ == '__main__':
main()
You should probably add a few checks to handle cases when users enter non-number input etc.
Your code looks really messed up. Try to write some better(clean) code next time.
while True:
total = 0
num1 = int(input("enter a number"))
num2 = int(input("enter a number"))
num3 = int(input("enter a number"))
total = num1 + num2 + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
con = int(input("Run again? 1/0: "))
if con==0:
break

Python: How to check if a number is in range and if not have the user enter a new number?

I first asked the user to enter a number and then ran a try/except block. I now want to check to see if the number is in a range between 1-9.
If not I want it to check if int and then check if it is in range.
Here is what I have so far:
def getInt(low, high):
start = 0
while start == 0:
try:
num = input("Enter a number for your calculation in range of 1- 9: ")
num = int(num)
start = 1
asdf = 0
while asdf == 0:
if num > 9 or num < 0:
print("Error: Please only enter numbers between 1-9")
else:
asdf = +1
return num
except:
print("Error: Please only enter numbers")
# main
TOTAL_NUMBERS = 2
LOW_NUMBER = 1
HIGH_NUMBER = 9
num1 = getInt(LOW_NUMBER, HIGH_NUMBER )
print(num1)
num2 = getInt(LOW_NUMBER, HIGH_NUMBER )
print(num2)
Maybe you need this:
def getInt(low, high):
while True:
try:
num = int(input("Enter a number for your calculation in range of 1- 9: "))
except ValueError:
print("Error: Please only enter numbers")
continue
if num not in range(1, 10):
print("Error: Please only enter numbers between 1-9")
else:
return num
You could replace
print("Error: Please only enter numbers between 1-9")
with
num = input("Error: Please only enter numbers between 1-9: ")
or move
num = input("Enter a number for your calculation in range of 1- 9: ")
num = int(num)
into the while loop so it gets called again if the user inputs a number outside the range
def getInt(low, high):
while True: # Keep asking until we get a valid number
try:
numStr = raw_input("Enter a number for your calculation in range of {0} - {1}: ".format(low, high) )
if numStr.isdigit():
num = int(numStr)
if num <= high and num >= low:
return num
except: # Field left empty
pass
getInt(1, 9)

Python figuring out the maximum number?

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.
I have this so far but im confused on how to create a way to compare the maximum value? Im new to programming and im just asking for help. Also do I include the try and except block before the while with the try? and then error for the except?
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
print num
print "Maximum", largest
nums = []
while True:
n = raw_input("Enter a number: ")
if n == "done":
break
try:
nums.append(int(n))
except ValueError:
print "Invalid input"
print "Min: %d" % min(nums)
print "Max: %d" % max(nums)
largest = None
smallest = None
first_number = True
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
try:
num = int(num)
if first_number:
largest = num
smallest = num
first_number = False
else:
largest = max(largest, num)
smallest = min(smallest, num)
except Exception, e:
print "Not Valid Input!!!"
continue
print "Maximum", largest
print "Minimum", smallest
numbers =[]
while True:
num = raw_input("Enter a number: ")
if num == "done" :
break
else:
numbers.append(num)
print max(numbers)
print min(numbers)
So, the logic is to add the numbers to a list and use functions max and min. You can write code to handle exceptions yourself.
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done": break
if len(num) < 1 : break
try:
num=int(num)
except:
print "Invalid input"
continue
if num is smallest:
smallest = num
if num > largest:
largest = num
print "Maximum is ", largest
print "Minimum is ", smallest
You can do this with a very small modification of your original program: just keep tabs of the smallest and largest numbers as you consider them.
largest = None
smallest = None
while True:
string = raw_input("Enter a number: ")
if string == "done":
break
try:
num = int(string)
except ValueError:
print "Not a number"
continue
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
largest = None
smallest = None
while True:
num = raw_input('Enter a number: ')
if num == 'done':
print 'Maximum is %s' % largest
print 'Minimum is %s' % smallest
break
try:
num = int(num)
if smallest is None or num <= smallest:
smallest = num
if largest is None or num >= largest:
largest = num
except:
print 'Invalid input'
I am also a python beginning learner, this question I have noticed in 'Python for Everyone' by Charles Russell Severance. My answer is below.
prompt = 'Enter the number: '
initial_value = 0.0
while True:
thing = input(prompt)
if thing == 'done':
break
try:
num = float(thing)
except:
print('Invalid input')
continue
num = float(thing)
if num > initial_value:
max = num
min = initial_value
else:
min = num
print('Max', max)
print('Min', min)
By assigning num to a single value, you are overwriting it through every iteration of the loop. Use a list instead.
num = []
finish = "n"
while finish.lower() == "n"
try:
num.append(int(raw_input("Enter a number: ")))
except ValueError:
print "Not a number"
finish = raw_input("Would you like to add another number? (y/n): ")
print max(num)

Categories

Resources