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

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

Related

Wondering why this while loop isn't stopping

end_number = -99
num = (input("Enter Nnumber: "))
list_of_numbers = []
list_of_numbers.append(num)
while num != end_number:
num = (input("Enter Nnumber: "))
print("The smallest number was", min(list_of_numbers))
print("The smallest number was", max(list_of_numbers))
I am trying to a have a person enter a bunch of int and stop when they ender -99. Then I'm wanting to print the smallest and largest in they entered.
input() returns a string and end_number is int, either convert the result of input() to int, with
num = int(input("Enter Nnumber: "))
or convert end_number to string, with
end_number = "-99" # Double quotes to represent -99 as a String of characters
end_number = -99
list_of_numbers = []
while True:
num = int(input("Enter Nnumber: "))
if num == end_number:
break
else:
list_of_numbers.append(num)
print("The smallest number was", min(list_of_numbers))
print("The smallest number was", max(list_of_numbers))
Some recaps:
Consider using while True
list_of_numbers.append(num) should be within while loop.
Your input should be int and within while loop.
You should checked whether num is equal to end_number within while
loop.
You need break to stop the loop if num equals end_number
Your loop doesn't stop because num is not an integer when compared to end_number which is int in the beginning. Then it keeps repeating for input because input in while is also a string.
The element in list_of_numbers is a string and it only contains 1 element because it gets appended just once. So you should move your list_of_numbers.append(num) within while loop and convert num to int to get min and max value later.
You might need if and break to stop the loop when num equals end_numbers, otherwise it always gets -99 as min value.
So it goes like this:
while num != end_number:
num = int(input("Enter Nnumber: "))
if num == end_number: break
list_of_numbers.append(num)
The main problem here is data types as input takes default type as string convert it to int to get value.
as "-99"!=-99
end_number = -99
num = int(input("Enter Number: "))
list_of_numbers = []
list_of_numbers.append(num)
while num != end_number:
num = int(input("Enter Number: "))
list_of_numbers.append(num)
print("The smallest number was", min(list_of_numbers))
print("The smallest number was", max(list_of_numbers))
I am trying this
list_of_numbers = []
while (num := int(input("Enter Nnumber: "))) != -99: list_of_numbers.append(num)
print("The smallest number was", min(list_of_numbers))
print("The smallest number was", max(list_of_numbers))
end_number = -99
num = (input("Enter Nnumber: "))
list_of_numbers = []
list_of_numbers.append(num)
while num != end_number:
num = int(input("Enter Nnumber: "))
print("The smallest number was", min(list_of_numbers))
print("The smallest number was", max(list_of_numbers))
Data Types In Python
In python, We have Data Types such as Integers, Strings, Floats and None Types.
Integers are whole numbers such as 5, 1, -234, 100134
Strings are words and sentences such as, "Hello, World!" or "Nice to meet you!"
Floats are decimal numbers, like, 0.342112, 4.98, -12.23
These data types can not be interchanged without the use of certain functions,
For example.
"5" == 5 = False
5 == 5 = True
"5" == str(5) = True.
str() turns a data type into a string.
int() turns a data type into a integer
float() turns a data type into a decimal.
I hope this helps!

How to calculate average and range after input into list?

I need some help regarding calculating averages and ranges. I am using built-in functions such as sum(), len(), etc. and cannot seem to calculate the average or range. I am using it to write a small piece of code for fun but cannot seem to get it to work. any help is much appreciated. Thank you!
x = 1
number_list = []
while x == 1:
input_number = input("PLease input an integer")
if str.isdigit(input_number) == True:
number_list.append(input_number)
else:
print("Please input a valid integer only.")
continueornot = input("Would you like to continue adding data? PLease input 'Yes' to continue, and anything else to quit.")
if continueornot == 'Yes':
x = 1
else:
print("Here is the maximum number:", max(number_list))
print("Here is the minimum number:", min(number_list))
print("Here is the count:", len(number_list))
print("Here is the average:" + sum(number_list) / len(number_list))
print("Here is the range:", range(number_list))
quit()
Change
if str.isdigit(input_number) == True:
number_list.append(input_number)
to
if input_number.isdigit():
number_list.append(int(input_number))
The error is because you're trying to do those operations on a list of strings.
You can also remove the check against True since that is implicitly checking the truthiness and since input_number is already a str, you can call the isdigit() method directly.
The problem is that you are appending strings to the list rather than integers and then you are applying arithmetic operations on it. So first you should convert the input number to int type.
Secondly range function will not give you the range of a list rather then it returns a sequence.
x = 1
number_list = []
while x == 1:
input_number = input("PLease input an integer")
if str.isdigit(input_number) == True:
input_number=int(input_number)
number_list.append(input_number)
else:
print("Please input a valid integer only.")
continueornot = input("Would you like to continue adding data? PLease input 'Yes' to continue, and anything else to quit.")
if continueornot == 'Yes':
x = 1
else:
print("Here is the maximum number:", max(number_list))
print("Here is the minimum number:", min(number_list))
print("Here is the count:", len(number_list))
print("Here is the average:" , sum(number_list) / len(number_list))
print("Here is the range:", max(number_list)-min(number_list))

Verifying if user input is in multiple zero values

How can we check if a user enters the value 0 multiple times in a row?
I have tried below code- here I have tried to define multiple value in list, but if the user enters 000000000 or more, I have to define till 000000000 in list is there any other way to achieve this
list = [0,00,000,0000]
num = int(input("Enter a number: "))
if num in list:
print("Zero")
elif :
print(" None ")
You need to take the input as a string. And you can check if the user has entered a string that will have all zeros in it as follows
def all_zeros(string):
return all(ch == '0' for ch in string)
This worked for me
num = input("Enter: ")
if num.count('0') > 0 and num.startswith('0'):
print("0")
else:
print("none")
Since you asked in this way
How can we check if a user enters the value 0 multiple times in a row?
But, other answers were checking whether more than one 0's are present in the string or not. I assume you want to check continuous zero's only,
num = input("Enter Number: ") # returns string
if "00" in num: #checking substring
print("Found continuous zeros")
else:
print("Entered no continous zeros!")
value = int(num) # convert it to int if needed
It doesn't matter how many zeros in the string, all these [00,000,0000,00000...] belong to the same category.
Output:
>>> num = input("Enter Number: ")
Enter Number: 0008
>>> num
'0008'
>>> "00" in num
True
>>>
num = input("Enter: ")
if num.count("0") > 1 and int(num) == 0:
print("0")
else:
print("none")
don't change num to int it will remove all the trailing zeroes

How to exclude specific type of an input variable in Python?

I created a row of Fibonacci numbers. At the beginning is desired input the number to specify the size of Fibonacci series, in fact the size of the row. The number is required to be an integer number >=2.
The outcome is printing out all Fibonacci number until the last number of the row, with their respective indices within the row! After that it's required to take out a slice of the row, and the outcome is to print out all numbers within the slice with their respective indices.
I successfully mastered to exclude all values that do not fall within range specified, but however I had not succeed to exclude numbers and other inputs of undesired types, example would like to exclude float type of an input variable, and string type of an input variable.
I specified that undesirable types of an input variable are float and string! However it reports me an error! How to overcome that, or by another words how to specify the requirement to exclude a floating variable as well as string variable to not report me an error?
The code:
while True:
n = int(input('Please enter the size of Fibonacci row - positive integer number(N>=2)!'))
if n < 2:
print('This is not valid number! Please enter valid number as specified above!')
continue
elif type(n)==float: # this line is not working!
print('The number has to be an integer type, not float!')
continue
elif type(n)==str: # this line is not working!
print( 'The number has to be an integer type, not string!')
continue
else:
break
def __init__(self, first, last):
self.first = first
self.last = last
def __iter__(self):
return self
def fibonacci_numbers(n):
fibonacci_series = [0,1]
for i in range(2,n):
next_element = fibonacci_series[i-1] + fibonacci_series[i-2]
fibonacci_series.append(next_element)
return fibonacci_series
while True:
S = int(input('Enter starting number of your slice within Fibonacci row (N>=2):'))
if S>n:
print(f'Starting number can not be greater than {n}!')
continue
elif S<2:
print('Starting number can not be less than 2!')
continue
elif type(S)==float: # this line is not working!
print('The number can not be float type! It has to be an integer!')
continue
elif type(S)==str: # this line is not working!
print('Starting number can not be string! It has to be positive integer number greater than or equal to 2!')
continue
else:
break
while True:
E = int(input(f'Enter ending number of your slice within Fibonacci row(E>=2) and (E>={S}):'))
if E<S:
print('Ending number can not be less than starting number!')
continue
elif E>n:
print(f'Ending number can not be greater than {n}')
continue
elif E<2:
print('Ending number can not be greater than 2!')
continue
elif type(E)==float: # this line is not working!
print('Ending number can not be float type! It has to be an integer type!')
continue
elif type(E) ==str: # this line is not working!
print(f'Ending number can not be string! It has to be positive integer number greater than or equal to {S}')
continue
else:
break
print('Fibonacci numbers by index are following:')
for i, item in enumerate(fibonacci_numbers(n),start = 0):
print(i, item)
fibonacci_numbers1 = list(fibonacci_numbers(n))
print('Fibonacci numbers that are within your slice with their respective indices are following:')
for i, item in enumerate(fibonacci_numbers1[S:E], start = S):
print(i, item)
Solved :-) simply add try except block in ur code like the following:
while True:
try:
num = int(input("Enter an integer number: "))
break
except ValueError:
print("Invalid input. Please input integer only")
continue
print("num:", num)
upvote & check :-)
at the first line
n = int(input('Please enter the size of Fibonacci row - positive integer number(N>=2)!'))
you're converting the input to int, so whatever the user provides it will be converted to an int.
if you want your code to be working, replace it with this
n = input('Please enter the size of Fibonacci row - positive integer number(N>=2)!')
Use an try/except/else to test the input. int() raises a ValueError if a string value isn't strictly an integer.
>>> while True:
... s = input('Enter an integer: ')
... try:
... n = int(s)
... except ValueError:
... print('invalid')
... else:
... break
...
Enter an integer: 12a
invalid
Enter an integer: 1.
invalid
Enter an integer: 1.5
invalid
Enter an integer: 1+2j
invalid
Enter an integer: 5
>>>
If you need to check type, isinstance is usually better, e. g.:
if isinstance(var, int) or isinstance(var, str):
pass # do something here

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