finding largest and smallest number in python - python-3.x

I am very new to programming, please advise me if my code is correct.
I am trying to write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == 'done':
break
try:
fnum = float(num)
except:
print("Invalid input")
continue
lst = []
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst))

Your code is almost correct, there are just a couple things you need to change:
lst = []
while True:
user_input = input('Enter a number: ')
if user_input == 'done':
break
try:
lst.append(int(user_input))
except ValueError:
print('Invalid input')
if lst:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
Also, since you said you're new to programming, I'll explain what I did, and why.
First, there's no need to set largest and smallest to None at the beginning. I actually never even put those values in variables because we only need them to print them out.
All your code is then identical up to the try/except block. Here, I try to convert the user input into an integer and append it to the list all at once. If any of this fails, print Invalid input. My except section is a little different: it says except ValueError. This means "only run the following code if a ValueError occurs". It is always a good idea to be specific when catching errors because except by itself will catch all errors, including ones we don't expect and will want to see if something goes wrong.
We do not want to use a continue here because continue means "skip the rest of the code and continue to the next loop iteration". We don't want to skip anything here.
Now let's talk about this block of code:
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
From your explanation, there is no need to get more input from the user, so none of this code is needed. It is also always a good idea to put int(input()) in a try/except block because if the user inputs something other than a number, int(input()) will error out.
And lastly, the print statement:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
In python, you can use the "string formatting operator", the percent (%) sign to put data into strings. You can use %d to fill in numbers, %s to fill in strings. Here is the full list of characters to put after the percent if you scroll down a bit. It also does a good job of explaining it, but here are some examples:
print('number %d' % 11)
x = 'world'
print('Hello, %s!' % x)

user_list = []
while True:
user_input = int(input())
if user_input < 0:
break
user_list.append(user_input)
print(min(user_list), max(user_list))

Related

Found error "not all arguments converted during string formatting" in Python

I found an error that says
File "", line 6, in
TypeError: not all arguments converted during string formatting"
while I'm trying to implement a while True loop in Python. I am trying to identify even and odd numbers with Python. Any suggestion for my problem?
Here's my code:
print("Identification Odd/Even number")
while True:
input = input ('Enter The Number ')
if input %2==0:
print("Even")
elif input %1==1:
print("Odd")
next_step = input ('Do you want indetify again? (Yes/No)')
if next_step == 'No' :
break
else:
print('You have input the wrong format')
The first thing you should not do is, that mixing variable names with function names. The line input = input('Enter number here: ') means that in the first pass the function input() will no longer be the function you want it to be, instead it will be string you got back from the first loop-pass.
Also you want to go on with some calculations. input (the function) will return a string, not an integer.
In order to get an integer from a string you should do a cast user_input = int(input('Enter number here: ')).
user_input is a integer and you can go on with you modulos operations.
So all in all I suggest based on your code:
change the variable name input to something else
do a cast after retrieving the user first user-input
for checking if a given number is odd or even there are only two cases to cover, which you can express with if-else-case.
input % 1 == 1 will always be False because there is no integer that is not divisible by 1.
If you want to continue to ask the user if he wants to go on, you probably want the user to give an answer you specified.
This will need another while-loop.
Why?
If the user gives an arbitrary answer, you want to continue to ask as long as the user gives an apropriate answer.
This is an answer you explicitly asked for.
To do that I have done something like this:
next_step = None
allowed_answers = ['No', 'Yes']
while next_step not in allowed_answer:
next_step = input('Want to go on? (Yes/No)')
If you want to give feedback to the user, something like this solved this riddle for me:
allowed_answers = ['No', 'Yes']
while True:
next_step = input('Want to go on? (Yes/No)')
if next_step not in allowed_ansers:
print('You have input the wrong format')
else:
break
All in all I would do something like this:
allowed_answers = ['No', 'Yes']
while True:
user_input = int(input('Enter The Number:'))
if user_input % 2 == 0:
print("Even")
else:
print("Odd")
next_step = None
while next_step not in allowed_answer:
next_step = input('Do you want indetify again? (Yes/No)')
if next_step == 'No' :
break

Making a simple input verifier

what I want is to validate user input in python 3.9 under these conditions:
1-No numbers bigger than 100 allowed.
2-No strings allowed.
3-No floats allowed.
The code seems to work well only with string detection.
Thanks in advance.
import random
name = input("Type in your name, sir.\n")
print("Hi", name, "!")
print(
"\n\n\n##This is a guessing game, where you guess a number that is between zero and the top number that you choose.##")
print("\n\nEnter a top number, and don't exaggerate babe.")
n = input()
verifier = 5
while True:
try:
verifier = int(n)
except ValueError or int(n) > 100:
print("Nope, neither floats nor strings are allowed buddy...Also don't pick a big'ol num like a 100.")
n = input()
continue
Your max check isn't working since int(n) > 100 only runs if it wasn't able to convert the string into an integer.
Move the condition after verifier = int(n) and it should work.
Your code should look something like this:
while True:
try:
verifier = int(n)
if int(n) > 100:
raise ValueError() # Brings us to the except statement
break
except ValueError:
print("Nope, neither floats nor strings are allowed buddy...Also don't pick a big'ol num like a 100.")
n = input()
continue
By the way, you can probably just remove the verifier = int(n) line, assuming you don't use it for anything else.

How can I make my python script determine if a number is an integer or a floating point depending on the mode its set to?

I am trying to create a function that would take a user inputted number and determine if the number is an integer or a floating-point depending on what the mode is set to. I am very new to python and learning the language and I am getting an invalid syntax error and I don't know what to do. So far I am making the integer tester first. Here is the code:
def getNumber(IntF, FloatA, Msg, rsp):
print("What would you like to do?")
print("Option A = Interger")
print("Option B = Floating Point")
Rsp = int(input("What number would like to test as an interger?"))
A = rsp
if rsp == "A":
while True:
try:
userInput = int(input("What number would like to test as an interger"))
except ValueError as ve:
print("Not an integer! Try again.")
continue
else:
return userInput
break
The problem with the code you shared is :
The syntax error you mentioned is probably because the except clause has to be at the same indentation level as try, and same for if and else of the same if/else clause. All the code in the function should be indented 1 level too. Python requires all this to identify blocks of code.
You don't need to give 4 arguments to the getNumber() function if you're not using them. This isn't really a problem, but you'll have to pass it some 4 values each time you call it (for example getNumber(1,2,3,4) etc...) to avoid missing argument errors; and these won't matter because you're not doing anything with the given values inside the function - so it's a little wasted effort. I rewrote it in the example below so that you aren't dealing with more variables than you need - it makes the code clearer/simpler.
You also don't need break after a return statement because the return will exit the enitre function block, including the loop.
Try this and see if it makes sense - I've changed a lot of the code :
def getNumber():
while True:
try:
userInput = int(input("What number would like to test as an integer ? "))
return userInput
except ValueError as ve:
print("Not an integer! Try again.")
continue
print("What would you like to do?")
print("Option A = Interger")
print("Option B = Floating Point")
chosen_option = input()
if chosen_option == 'A':
integer_received = getNumber()
print(integer_received, "was an int !")
else:
print("You did not choose 'A' or 'B'")
To determine whether a number is a float or integer, you can use this approach
float is nothing but the integer with floating-point(.).
to determine this we first need to convert it to string and find does it contain a point or not.
number = input("Enter a numbeer\n")
if number.find(".") == -1:
# find will return -1 when the value is not in string
print("it is integer")
else:
print("it is float")

Python, How do I ignore a string such as 'done' amongst numbers to sum the total from a list

while True:
numbers = input('> ')
if numbers == 'done':
break
total = 0
for number in numbers:
if numbers == int:
total = total + numbers
print(total)
I've had a hard time understanding exactley what u want to do with this code, please use a proper code block next time, with proper indentation. My guess is that u want to get a input number like 345 and add 3+4+5 as a output. If the input is not a int it should break the loop. Ive come up with 2 diffrent solutions, depending on what you need.
This code will simply take the input and check if it is "done", if it is not "done" it will try to add. This is a easy to understand solution but it will produce a error if the input is any diffrent string than "done".
while True:
numbers = input(">")
if numbers == "done":
break
else:
total = 0
for number in numbers:
total += int(number)
print(total)
This approach will test for the "done" string again, but afterwards will also check if the input can be converted into a int. if not the error is captured and it will return "invalid input". If u want the programm to terminate at any string u can just put break in the except section.
while True:
numbers = input(">")
if numbers == "done":
break
else:
try:
testing = int(numbers)
total = 0
for number in numbers:
total += int(number)
except:
total = "invalid input"
print(total)
im a Beginner myself and if a experiencend person can show me a better way to do this i would be very interested
while True:
numbers = input('> ')
if numbers == 'done':
break
total = 0
for number in numbers:
if numbers == int:
total = total + numbers
print(total)
Assuming this as your code:
Here's a solution to your problem-->
numbers=[]
while True:
a=input('>')
if a=='done':
break
else:
numbers.append(a)
total=0
for number in numbers:
total = total + int(number)
print(total)
By default everything gets accepted as string so we convert it to integer to find total.
Also we use list to store all the values we accept.
Another Solution is-->
numbers=[]
while True:
a=input('>')
if a=='done':
break
else:
numbers.append(a)
p=map(int,numbers)
print(sum(p))
Hope you understand the solution :-)
total = 0
average = 0
count = 0
while True:
numbers = input('> ')
if numbers == 'done': break
try:
total = int(numbers) + total
count = count + 1
except:
print('nope')
try:
average = total / count
except:
print('error')
print(total)
print(average)
print(count)
Try this:
total = 0
number_of_inputs = 0
while True:
number_string = input('Enter a number: ')
try:
total += float(number_string)
number_of_inputs += 1
except ValueError:
break # we weren't given a number, so exit the loop
# Now that we're outside of the loop, print out the total:
print('The total is:', total)
if number_of_inputs > 0:
average = total / number_of_inputs
print('The average is:', average)
else:
print('The average cannot be calculated, as no inputs were given.')
Do you see what's happening? The while loop keeps ask for and adding integers to total until a non-integer (like "done") is given. Once it gets that non-integer, the int() function will fail, and the exception it throws will get caught, and the code will immediately break out of the while loop.
And once out of the loop, the total and the average are printed out.
A few things you should be aware of:
If the user gave no inputs (which is possible here), the total will correctly print out as 0, but if you try to calculate the average, you will error, due to diving by number_of_inputs (which is also 0). That is why I check that number_of_inputs is greater than zero before I even attempt to calculate the average.
Originally I used int() to convert the string to a number, but I changed it to use float() instead. I figure that since you want to calculate an average, averages are not necessarily integers (even if all the inputs are), so there's no point in enforcing integer input. That is why I changed the int() to float(), but whether or not you want to use it is up to you.
ValueError isn't a function; it's an Exception. At this point you probably don't know what Exceptions are, so just know that they are special cases that can happen, and they're often used for catching errors, such as bad input values.
In the code I posted above, the loop is always expecting numerical input. But as soon as we have input that can't be converted to a number, the program then says, "Hey, I have an exception to what we're expecting! The exception is that there's an error in the value!" Then the program, instead of continuing to the next line of code (which is number_of_inputs += 1) will then execute the block of code under the except ValueError: section. And in the code above, all it does is call break, which exits the loop.
Once out of the loop, the code prints out the total and the average.
If it weren't for the try: and except ValueError: lines in the code, then the program would abruptly end (with a lengthy error message) once someone gave a non-numerical input. That happens because the call to float() wouldn't know how to convert a value like "done" to a number, so it does nothing more than just quitting.
However, by using try: and except ValueError:, we are anticipating that someone might give non-numerical input. When that happens (which it will, when the user is finished giving inputs) -- instead of quitting -- we want an alternate action to take. And we specify that alternate action to be a simple break out of the loop -- which will allow the program to continue with whatever is after the loop.
I hope this makes sense. If it doesn't, it will make more sense once you start learning about Exceptions in Python.

Why does this code not let me just check for an invalid input

This is not the whole code but the code I am experimenting with to get a solution for the whole code. I also need an answer for dealing with invalid string inputs.
def menu_payment():
burger_count= (input("Please input the number of Racquet Burgers (Cheese Burgers) you would like: "))
if (burger_count !=int) or (burger_count<=0):
print("You must eneter a positive whole number for your order. Please try again.")
menu_payment()
Try doing this:
def menu_payment():
burger_count = input("How many burgers would you like:")
try:
burger_count = int(burger_count)
valid_number = 1
except:
print(burger_count, " is not a valid number")
valid_number = 0
if valid_number == 1 and burger_count > 0:
print ("I will get your burgers right away")
else:
print("Please put a valid number and no negetives")
The issue with checking for a valid string is coming from your if statement. I would suggest first, checking if the value is an int, then check the value for it. That is the easiest and least confusing way to fix that issue.
Input will always convert the user input to string. Therefore, entering "1" is the string of "1", not the integer.
You could try wrapping your input with an int function like:
burger_count = int(input("Please input the number of Racquet Burgers (Cheese Burgers) you would like: "))
However, this would throw a ValueError if anything other than an integer is entered.
Also, I don't think checking the variable type works like that. You can do something like:
if type(burger_count) is not int:
<do something>
Probably super inefficient (pre coffee scripting is bad) but here's how I would handle this:
def menu_payment():
while True:
try:
burger_count = int(input("burgers: "))
except ValueError:
print("You must eneter a number for your order. Please try again.")
continue
else:
if burger_count <= 0:
print("You must eneter a number for your order. Please try again.")
continue
else:
return burger_count

Resources