Break not Stopping Simple While Loop Python - python

Python noob here. I am trying to create a list with numbers a user inputs and then do some simple calculations with the numbers in the list at the end, in a while loop. The While loop is not breaking when 'done' is inputted. It just prints 'Invalid input.'
list = []
while True:
try:
n = int(input('Enter a number: '))
list.append(n)
except:
print('Invalid input')
if n == 'done':
break
print(sum.list())
print(len.list())
print(mean.list())

You will have to separate receiving user input with checking against "done" from conversion to a number and appending to the list. And you will have to check for "done" before converting the input to an integer.
Try something like this:
list_of_numbers = []
while True:
user_input = input("Enter a number or 'done' to end: ")
if user_input == "done":
break
try:
number = int(user_input)
except ValueError:
print("invalid number")
continue
list_of_numbers.append(number)
print(list_of_numbers)
# further processing of the list here

This is because the int() function is trying to convert your input into an integer, but it is raising an error because the string 'done' can not be converted to an integer. Another point is that sum(), mean() and len() are functions, not attributes of lists. Also mean() is not a built in function in python, it must be import with numpy. Try it like this:
from numpy import mean
list = []
while True:
try:
n = input('Enter a number: ')
list.append(int(n))
except:
if n!='done':
print('Invalid input')
if n == 'done':
break
print(sum(list))
print(len(list))
print(mean(list))

You must check if you can turn the input into a integer before appending to your list. You can use use the try/except to catch if the input variable is convertible to a integer. If it's not then you can check for done and exit.
list = []
while True:
n = input('Enter a number: ')
try:
n = int(n)
list.append(n)
except ValueError:
if n == 'done':
break
print('Invalid input')
total = sum(list)
length = len(list)
mean = total/length
print('sum:', total)
print('length:', length)
print('mean:', mean)
Example interaction
Enter a number: 12
Enter a number: 3
Enter a number: 4
Enter a number:
Invalid input
Enter a number: 5
Enter a number:
Invalid input
Enter a number: done
sum: 24
length: 4
mean: 6.0

If the user enters done, you will attempt to convert into an int, which will raise an exception that you then catch.
Instead, perform your check before attempting to convert it to an integer.

Related

How to use the same code but with different variables

I want to make a code that allows me to check if the number I have entered is really a number and not a different character. Also, if it is a number, add its string to the list.
Something like this:
numbers = []
num1 = input("Enter the first number: ")
try:
check = int(num1)
numbers.append(num1)
print("The number {} has been added.".format(num1))
except ValueError:
print("Please, enter a number")
I have to do the same for several numbers, but the variables are different, like here:
num2 = input("Enter the next number: ")
try:
check = int(num2)
numbers.append(num2)
print("The number {} has been added.".format(num2))
except ValueError:
print("Please, enter a number")
Is there any way to create a code that does always the same process, but only changing the variable?
If you are trying to continue adding numbers without copying your code block over and over, try this:
#!/usr/bin/env python3
while len(numbers) < 5: #The five can be changed to any value for however many numbers you want in your list.
num2 = input("Enter the next number: ")
try:
check = int(num2)
numbers.append(num2)
print("The number {} has been added.".format(num2))
except ValueError:
print("Please, enter a number")
Hopefully this is helpful!
Create the list in a function (returning the list). Call the function with the number of integers required.
def get_ints(n):
result = []
while len(result) < n:
try:
v = int(input('Enter a number: '))
result.append(v)
print(f'Number {v} added')
except ValueError:
print('Integers only please')
return result
Thus, if you want a list of 5 numbers then:
list_of_numbers = get_ints(5)

Syntax issue with my for loop and while loop keeps repeating infinitely (python)

I was working on a for loop and while loop for 2 separate programs asking for the same thing. My for loop is giving me syntax issues and won't come out as expected…
Expectations: A python program that takes a positive integer as input, adds up all of the integers from zero to the inputted number, and then prints the sum. If your user enters a negative number, it shows them a message reminding them to input only a positive number.
reality:
i1 = int(input("Please input a positive integer: "))
if i1 >= 0:
value = 0 # a default, starting value
for step in range(0, i1): # step just being the number we're currently at
value1 = value + step
print(value1)
else:
print(i1, "is negative")
And my While loop is printing "insert a number" infinitly…
Here is what my while loop looks like:
while True:
try:
print("Insert a number :")
n=int(input())
if(n<0):
print("Only positive numbers allowed")
else:
print ((n*(n+1))//2)
except ValueError:
print("Please insert an integer")
`Same expections as my for loop but as a while loop
Anyone know anyway I could fix this issue?
You have some indentation issues. This way works:
while True:
try:
print("Insert a number: ")
user_input = input()
if user_input == 'q':
exit()
n = int(user_input)
if n <= 0:
print("Only positive numbers allowed")
else:
print(n * (n+1) // 2)
except ValueError:
print("Please enter an integer")
Output sample:
Enter a number:
>>> 10
55
Enter a number:
>>> 1
1
Enter a number:
>>> -1
Only positive numbers allowed
Enter a number:
>>> asd
Please enter an integer
Enter a number:
See more about indentation in the docs.

Python: Continue if variable is an 'int' and has length >= 5

I have a piece of code that does some calculations with a user input number. I need a way to check if user entry is an integer and that entered number length is equal or more than 5 digits. If either one of conditions are False, return to entry. Here is what i got so far and its not working:
while True:
stringset = raw_input("Enter number: ")
if len(stringset)>=5 and isinstance(stringset, (int, long)):
break
else:
print "Re-enter number: "
If anyone has a solution, I'd appreciate it.
Thanks
This would be my solution
while True:
stringset = raw_input("Enter a number: ")
try:
number = int(stringset)
except ValueError:
print("Not a number")
else:
if len(stringset) >= 5:
break
else:
print("Re-enter number")
something like this would work
while True:
number = input('enter your number: ')
if len(number) >= 5 and number.isdigit():
break
else:
print('re-enter number')
Use this instead of your code
while True:
stringset = raw_input("Enter number: ")
if len(stringset)>=5:
try:
val = int(userInput)
break
except ValueError:
print "Re-enter number:
else:
print "Re-enter number:
Do not use isdigit function if you want negative numbers too.
By default raw_input take string input and input take integer input.In order to get length of input number you can convert the number into string and then get length of it.
while True:
stringset = input("Enter number: ")
if len(str(stringset))>=5 and isinstance(stringset, (int, long)):
break
else:
print "Re-enter number: "

How do I determine input as an integer and the length, simultaneously?

Ok so I'm really new to programming. My program asks the user to enter a '3 digit number'... and I need to determine the length of the number (make sure it is no less and no more than 3 digits) at the same time I test to make sure it is an integer. This is what I have:
while True:
try:
number = int(input("Please enter a (3 digit) number: "))
except:
print('try again')
else:
break
any help is appreciated! :)
You could try something like this in your try/except clause. Modify as necessary.
number_string = input("Please enter a (3 digit) number: ")
number_int = int(number_string)
number_length = len(number_string)
if number_length == 3:
break
You could also use an assert to raise an exception if the length of the number is not 3.
try:
assert number_length == 3
except AssertionError:
print("Number Length not exactly 3")
input() returns you a string. So you can first check the length of that number, and length is not 3 then you can ask the user again. If the length is 3 then you can use that string as a number by int(). len() gives you the length of the string.
while True:
num = input('Enter a 3 digit number.')
if len(num) != 3:
print('Try again')
else:
num = int(num)
break
Keep the input in a variable before casting it into an int to check its length:
my_input = input("Please enter a (3 digit) number: ")
if len(my_input) != 3:
raise ValueError()
number = int(my_input)
Note that except: alone is a bad practice. You should target your exceptions.
while True:
inp = raw_input("Enter : ")
length = len(inp)
if(length!=3):
raise ValueError
num = int(inp)
In case you are using Python 2.x refrain from using input. Always use raw_input.
If you are using Python 3.x it is fine.
Read Here
This should do it:
while True:
try:
string = input("Please enter a (3 digit) number: ")
number = int(string)
if len(string) != 3 or any(not c.isdigit() for c in string):
raise ValueError()
except ValueError:
print('try again')
else:
break

maximum of numbers being strange

numbers=[]
maximum=0
while True:
number =input("Enter a number:")
if number == "0":
break
else:
numbers.append(number)
print ("The largest number entered was:")
print (max(numbers))
This seems to work for numbers below 10 only when I enter these numbers:
Enter a number:10
Enter a number:9
Enter a number:3
Enter a number:4
Enter a number:23
Enter a number:0
The largest number entered was:
9
As you can see, the largest number is actually 23, but it printed 9, what have I done wrong?
You are appending strings, append integers instead:
numbers.append(int(number))
Or better:
while True:
number = int(input("Enter a number:"))
if not number:
break
else:
numbers.append(number)
EDIT: you can wrap the integer conversion with try-except block to make sure user enters only digits:
while True:
nb = input('Enter a number:')
try:
nb = int(nb)
if not nb:
break
else:
numbers.append(nb)
except ValueError:
print('Please Enter Valid Number')
print ("The largest number entered was:")
print (max(numbers))
You are returning the lexicographical maximum, which is 9. This is due to your building the numbers container from string types.
To return the numeric maximum, build your container with integers using append(int(number)).
You could append it as int or print max with map and int to your list:
print (max(map(int, numbers)))

Categories

Resources