Python, compare numbers [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I tried to write code as below to compare a serious of numbers.
largest = None
smallest = None
while True:
nums = numl = input("Enter a number: ")
if numl == "done" : break
if smallest == None:
smallest = nums
elif smallest > nums:
smallest = nums
print(smallest)
if largest == None:
largest = numl
elif largest < numl:
largest = int(numl)
print(largest)
print("Maximum is", largest)
print("Minimum is", smallest)
However, it makes the wrong result or even post error
Can someone help to check it?
Thank you in advance.

First of all I would request you to post the code with the question rather than an image link.
According to your code, you are taking input() which returns string, then you are trying to see if a string is > a int
which won't work
you can compare int with int and str with str

Related

Why the While loop continues and how to calculate the average based on numbers input? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
Hi I'm trying to solve this coding homework:
Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program must then calculate the average of the numbers entered excluding the -1.
I define the while loop to make sure it keeps asking, as:
while n != -1
str(input("enter your number:"))
But whenever I try to input -1, it just keeps on asking to enter the number regardless.
Also, I'm not sure what is the best way to define the average excluding -1, none of the lessons prior to this assignment talked about this. I have Googled about it but none of the examples match this particular assignment, even fumbling around did not help.
Thank you for your help :)
Presumably n is meant to be the user input, but you're never assigning a value to n. Did you mean to do this?
n = str(input("enter your number:"))
Also, you're comparing n to -1, but your input isn't a number; it's a string. You can either convert the input to a number via n = int(input(...)), or compare the input to a string: while n != '-1'.
You could ask for a number the if it is not equal to -1 enter the while loop. So the code would be:
n = float(input("What number?"))
if n != -1:
sum += n
nums_len = 1
while n != -1:
sum += 1
nums_len += 1
n = float(input("What number?"))
print("The average is", str(sum/nums_len))
Thanks everyone, this is the final code with the correct values that gives the average of user inputs
n = float(input("What number?"))
if n != -1:
sum = 0
nums_len = 0
while n != -1:
sum += n
nums_len += 1
n = float(input("What number?"))
print("The average is", float(sum/nums_len))

I am getting a ValueError for the line 4 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Getting value error on code line 4.
n = int(input("enter number of students: "))
list1=[]
for i in range(0,n):
ele=int(input("enter the score of the student: "))
list1.append(ele)
list1.sort()
print("the runner up is: ", list1[-2])
It might have happened because you have accidently provided a character value that cannot be converted to int. So in line 4 you are getting ValueError. Another possible reason is you have used a decimal point number as input. A decimal number of str type cannot be converted to int type. So either use a float or use try and except to handle the issue.
You need to add a validation for your code and so try this:
n = int(input("enter number of students: "))
list1=[]
counter = 0
while counter != n:
try:
ele=int(input("enter the score of the student: "))
list1.append(ele)
counter += 1
except ValueError:
print("Your input should be a number!")
list1.sort()
try:
print("the runner up is: ", list1[-2])
except:
print("You should at least have two scores!")

the correct use of max(), min() function in python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
im strugguling to get a solution for my problem. I keep getting errors with my max(), and min() function.
Im trying to write a code that takes user inputs until a negative value is inputted.Then i need to take the sum, highest, lowest and avarges of the numbers.
the code:
print("Please enter values(negative value to stop)")
g=1
flag=0
list = []
while not flag:
val=float(input("Enter value number "+str(g)+ ": "))
g+=1
if val<0:
flag=1
else:
sum+=val
print("Sum of "+str(g-2)+ " values: "+str(sum))
print("The highest number is: ",min(low_number))
print("The lowest number is: ",min(low_number))
print("The average number is: ",sum/(g-1))
I am no expert but I think it is because you are not entering any of the values inputted into the lists. There is no where that you are appending the given values so there are no numbers in the lists to be checked.
I have not tested this but perhaps try
print("Please enter values(negative value to stop)")
flag=0
number = []
while not flag:
val=float(input("Enter value number :"))
if val<0:
flag=1
else:
number.append(val)
print("Sum of "+str(len(number))+ " values: "sum(number))
print("The highest number is: ",max(number))
print("The lowest number is: ",min(number))
print("The average number is: ",sum(number)/len(number))
EDIT: I made some changes to ensure it all works :)
EDIT 2: I have tested this and this code works entirely
low_number is empty, so min() on an empty list will fail.
Maybe you want to do something like this:
print("Please enter values(negative value to stop)")
flag=0
values=[]
while not flag:
val=float(input("Enter value number : "))
if val < 0:
break
values.append(val)
print("Sum of values: ",sum(values))
print("The highest number is: ",max(values))
print("The lowest number is: ",min(values))
print("The average number is: ",sum(values)/len(values))

As I do so as not to show the -1 in the Python list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Write a function to enter from the keyboard a series of numbers between 1 and 20 and save them in a list.In case of entering an out-of-range value the program will display an error message and ask for a new number.To finish loading you must enter -1.La function does not receive any parameters, and returns the loaded list (or empty, if the user did not enter anything) as the return value.
def funcion():
list = []
num = 0
while num != -1:
num = int(input("Enter a number between 1 and 20: "))
while num > 20 :
num = int(input("Please re-enter the number: "))
list.append(num)
return lista
result = funcion()
print(result)
My question is how I do not show the -1 in the list
It's easier to have an infinite loop and break out of it when the user enters -1:
def funcion():
lista = []
num = 0
while True:
num = int(input("Enter a number between 1 and 20: "))
while num > 20:
num = int(input("Please re-enter the number: "))
if num == -1:
break
else:
lista.append(num)
return lista
result = funcion()
print(result)
The trick is saving the list except the last item like this:
return lista[:-1]
you can read more here:
https://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/
The minimal change to your code would just use the list slicing syntax to return all elements of lista apart from the last one:
return lista[:-1]
See [1] below. This is a pythonic way of writing the slightly more intuitive, but more verbose statement:
return lista[:len(lista)-1]
... which in turn is short for the even longer:
return lista[0:len(lista)-1]
You seem to be new to python. I really recommend looking up "list slicing" and "list comprehensions": if you already know a programming language that doesn't have these, once you learn these, you'll wonder how you ever did without them!
[1] http://knowledgehills.com/python/negative-indexing-slicing-stepping-comparing-lists.htm

Python: Loop Sentinel Value [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm supposed to write a program with a loop that lets the user enter a series of integers, followed by -99 to signal the end of the series. After all the numbers have been entered, the program should display the largest and smallest numbers entered.
This is what I have so far:
def main():
user_input = 1
while user_input != -99:
user_input = int(input("Enter your number or -99 to end."))
bigger = largest(user_input)
tinier = smallest(user_input)
print('The largest number is ', bigger, "and the smallest is ", tinier, ".")
def largest(number):
largest = 0
if number > largest:
largest = number
return largest
def smallest(number):
smallest = 10000
if number < smallest:
smallest = number
return smallest
main()
For some reason the sentinel value (-99) is entering the loop, I have no clue how, and becoming the smallest value. On top of that, the biggest value isn't ever the right one. Help much appreciated!
The quickest change to make to your code to fix this would be
def main():
user_input = 1
while user_input != -99:
user_input = int(input("Enter your number or -99 to end."))
if use_input == -99:
break
bigger = largest(user_input)
tinier = smallest(user_input)
print('The largest number is ', bigger, "and the smallest is ", tinier, ".")
The problem is, if the user enters -99, you complete the rest of the lines for that iteration of the loop. It will not terminate the while loop until the next time around, but it has already performed largest and smallest at that point so it is already overwritten.
Your Indentation is important in python so your smallest value and largest value functions return statement is improperly indent
def largest(number):
largest = 0
if number > largest:
largest = number
return largest
def smallest(number):
smallest = 10000
if number < smallest:
smallest = number
return smallest
Pretty simple if you use a list to store the numbers and rely on max/min functions from the standard library:
def main():
numbers = []
while True:
user_input = int(raw_input("Enter a number"))
if user_input == -99:
break
else:
numbers.append(user_input)
print('Largest is {}, smallest is {}'.format(max(numbers), min(numbers)))
You have two problems as far as I can see: your input is being processed before being checked, and there are issues in your largest() and smallest() functions. When you scan for user input, you immediately go into your functions before verifying. Restructure your loop like this:
input()
while(){
...
...
input()
}
For the second part, your functions aren't working because you initialize the values every time they run. Initialize your functions in the header at the top of your file, then just compare them. So for example, move the line largest=0 to the top of your file right below your import statements. Other than that, I think it should work.

Categories

Resources