maximum of numbers being strange - python

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)))

Related

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.

Break not Stopping Simple While Loop 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.

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: "

While loop won't terminate

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

Why doesn't the max() function run as it is expected?

numbers = []
first_input = input('Write any number.When you are done just write "done":')
numbers.append(first_input)
while first_input:
input_numb = input("Write next number")
if input_numb == int():
numbers.append(input_numb)
elif input_numb == "done":
print("The largest number is "+max(numbers))
print("The smallest number is "+min(numbers))
break
Can someone look at this code and tell me what I did wrong please? After I put the input numbers I want to print the biggest and smallest number from the list numbers but I don't know why the max function does not return the biggest number, instead it returns the smallest one (just like the min function. Why?
numbers = []
first_input = input('Write any number.When you are done just write "done":')
numbers.append(int(first_input))
while first_input:
input_numb = input("Write next number")
try:
numbers.append(int(input_numb))
except:
if input_numb == "done":
print("The largest number is ", max(numbers))
print("The smallest number is ", min(numbers))
break
else:
print('invalid input!')
out:
Write any number.When you are done just write "done":1
Write next numbera
invalid input!
Write next number2
Write next number3
Write next number6
Write next numberdone
The largest number is 6
The smallest number is 1
int() will return 0:
class int(x, base=10)
Return an integer object constructed from a number or string x, or
return 0 if no arguments are given.If x is a number, return x.__int__(). For floating point numbers, this truncates towards
zero.
In [7]: int() == 0 == False
Out[7]: True
you should use max in a list of number not a list of string, convert string to int before you append it to list
"The largest number is " + max(numbers)
return :
TypeError: Can't convert 'int' object to str implicitly, just use , to concate the string and int.
you should convert your inputs to integers using int(my_input) then add them to the list my_list.append(int(my_input)) and use the max or min functions max(my_list) after getting all the inputs from the user
numbers = []
user_input = input('Write any number.When you are done just write "done": ')
while user_input != "done":
try:
numbers.append(int(user_input))
user_input = input("Write next number : ")
except ValueError:
user_input = input("please enter a valid number : ")
print("The largest number is ", max(numbers))
print("The smallest number is ", min(numbers))

Categories

Resources