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
Related
I really don't know what I am doing wrong here but whenever I run the code the output doesn't calculate the variable and only sets it to 0.0
total = 0.0
num1 = 0.0
average = 0.0
while True:
input_num = input("Enter a number ")
if input_num == 'done':
break
try:
num = float(input_num)
except ValueError:
print("Invalid Input")
continue
total = total + num
num1 = num1 + 1
average = total / num1
print("total: ", total)
print("count: ", num1)
print("average: ", average)
I got the following after running the code
[Image of code run]: (https://imgur.com/a/lEz6ibh)
Your code isn't indented properly, so the code after continue never gets executed. To get it to work, unindent the lines after continue:
total = 0.0
num1 = 0.0
average = 0.0
while True:
input_num = input("Enter a number ")
if input_num == 'done':
break
try:
num = float(input_num)
except ValueError:
print("Invalid Input")
continue
total = total + num
num1 = num1 + 1
average = total / num1
print("total: ", total)
print("count: ", num1)
print("average: ", average)
This should work.
num_list = []
while True:
input_num = input("Enter a number ")
if input_num == 'done':
total = sum(num_list)
average = total / len(num_list)
break
num_list.append(float(input_num))
print(f"Average: {average}")
print(f"Total: {total}")
print(f"num_list: {num_list}")
total = 0.0
num1 = 0.0
average = 0.0
while True:
input_num = input("Enter a number ")
if input_num == 'done':
break
try:
num = float(input_num)
total = total + num
num1 = num1 + 1
average = total / num1
except ValueError:
print("Invalid Input")
continue
print("total: ", total)
print("count: ", num1)
print("average: ", average)
Your code to calculate values should be inside the try block rather than the except block otherwise they are never executed.
I am trying to create a simple python calculator with inputs as lists and functions defining the operations that can be performed.
I am having trouble getting my functions to return the value after they have returned.
The program is supposed to get numbers in the form of a list and then pass them into the while loop in the main part of the program. The user can perform as many operations as they want before the program quits.
Please let me know what my error is or if I need to add anything.
def display_menu():
print("Please Choose an option")
print("1. Add (+)")
print("2. Subtract (-)")
print("3. Multiply (*)")
print("4. Divide (/)")
print("q to quit")
def addition():
numlist = input("please enter at least 2 numbers to be operated on.").split()
numlist = [float(num) for num in numlist]
num1 = numlist[0]
del numlist[0]
for num in numlist:
num1 = num1 + num
return num1
def subtraction():
numlist = input("please enter at least 2 numbers to be operated on.").split()
numlist = [float(num) for num in numlist]
num1 = numlist[0]
del numlist[0]
for num in numlist:
num1 = num1 - num
return num1
def multiply():
numlist = input("please enter at least 2 numbers to be operated on.").split()
numlist = [float(num) for num in numlist]
num1 = numlist[0]
del numlist[0]
for num in numlist:
num1 = num1 * num
return num1
def division():
numlist = input("please enter at least 2 numbers to be operated on.").split()
numlist = [float(num) for num in numlist]
num1 = numlist[0]
del numlist[0]
for num in numlist:
num1 = num1 * num
return num1
displ_menu()
operator = input("Please enter an operator: ")
while operator != "q":
if operator == "+":
addition()
elif operator == "-":
subtraction()
elif operator == "*":
multiply()
else:
division()
displ_menu()
operator = input("please enter an operator")
print("Closing calculator")
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)
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
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)