I need a function that excepts wrong input and asks to input once more. But after wrong input it returns None instead of new input. What is wrong with my code and how can I solve this?
def start():
def inputNumber(answer):
try:
number = int(input(answer))
if number <= 100 and number >= 0:
print('%%%',number,'%%%')
return number
else:
inputNumber('Number is wrong, please input number from 0 to 100: ')
except (ValueError):
inputNumber('It is not a number, please input number from 0 to 100: ')
def checkInput(number2):
print('$$$',number2,'$$$')
if number < 50:
return number2
else:
return checkInput(inputNumber('Input number from 0 to 100: '))
number = 0
print('###',checkInput(inputNumber('Input number from 0 to 100: ')),'###')
start()
start()
This is the result:
Input number from 0 to 100: 777
Number is wrong, please input number from 0 to 100: sadf
It is not a number, please input number from 0 to 100: 17
%%% 17 %%%
$$$ None $$$
TypeError: unorderable types: NoneType() < int()
You are calling inputNumber recursively but don't return the result of the recursive call. Better use loops instead of recursion:
def inputNumber(prompt):
while True:
try:
number = int(input(prompt))
if 0 <= number <= 100:
print('%%%',number,'%%%')
return number
prompt = 'Number is wrong, please input number from 0 to 100: '
except ValueError:
prompt = 'It is not a number, please input number from 0 to 100: '
Btw: you should also use loops in your other functions, and don't define nested functions.
run this code it will solve your problem. you just need to catch as extra error (NameError)
def start():
def inputNumber(answer):
try:
number = int(input(answer))
if number <= 100 and number >= 0:
print('%%%',number,'%%%')
return number
else:
inputNumber('Number is wrong, please input number from 0 to 100: ')
except (ValueError, NameError) as e:
inputNumber('It is not a number, please input number from 0 to 100: ')
def checkInput(number2):
print('$$$',number2,'$$$')
if number < 50:
return number2
else:
return checkInput(inputNumber('Input number from 0 to 100: '))
number = 0
print('###',checkInput(inputNumber('Input number from 0 to 100: ')),'###')
start()
start()
The problem is that once you fail a check you call inputNumber again, but don't do anything with the answer. You need to return it.
def start():
def inputNumber(answer):
try:
number = int(input(answer))
if number <= 100 and number >= 0:
print('%%%', number, '%%%')
return number
else:
return inputNumber('Number is wrong, please input number from 0 to 100: ')
except (ValueError):
return inputNumber('It is not a number, please input number from 0 to 100: ')
def checkInput(number2):
print('$$$', number2, '$$$')
if number < 50:
return number2
else:
return checkInput(inputNumber('Input number from 0 to 100: '))
number = 0
print('###', checkInput(inputNumber('Input number from 0 to 100: ')), '###')
start()
start()
Related
I have an exercise:
Write code that asks the user for integers, stops loop when 0 is given.
Lastly, adds all the numbers given and prints them.
So far I manage this:
a = None
b = 0
while a != 0:
a = int(input("Enter a number: "))
b = b + a
print("The total sum of the numbers are {}".format(b))
However, the code needs to check the input and give a message incase it is not an integer.
Found that out while searching online but for the life of me I cannot combine the two tasks.
while True:
inp = input("Input integer: ")
try:
num = int(inp)
except ValueError:
print('was not an integer')
continue
else:
total_sum = total_sum + num
print(total_sum)
break
I suspect you need an if somewhere but cannot work it out.
Based on your attempt, you can merge these two tasks like:
a = None
b = 0
while a != 0:
a = input("Enter a number: ")
try:
a = int(a)
except ValueError:
print('was not an integer')
continue
else:
b = b + a
print("The total sum of the numbers are {}".format(b))
If you want to use an If-Statement, you don't need the else: If the number is not 0 it will just start again until it's 0 sometime.
total_sum = 0
while True:
inp = input("Input integer: ")
try:
num = int(inp)
except ValueError:
print('was not an integer')
continue
total_sum = total_sum + num
if num == 0:
print(total_sum)
break
Since input's return is a string one can use isnumeric no see if the given value is a number or not.
If so, one can convert the string to float and check if the given float is integer using, is_integer.
a = None
b = 0
while a != 0:
a = input("Enter a number: ")
if a.isnumeric():
a = float(a)
if a.is_integer():
b += a
else:
print("Number is not an integer")
else:
print("Given value is not a number")
print("The total sum of the numbers are {}".format(b))
I'm trying to solve the scenario with these conditions:
Ask the user to enter a number
Count up from 1 to the number that the user has entered, displaying each number on its own line if it is an odd number. If it is an even number, do not display the number.
If the user enters a number that is 0 or less, display error
My codes are as follows and I can't seem to satisfy the <= 0 print("error) condition:
num=int(input("Enter number: "))
for x in range(num):
if x % 2 == 0:
continue
print(x)
elif x<=0:
print("error")
Your solution will be :
num=int(input("Enter number: "))
if num <= 0:
print("Error")
else:
for i in range(1, num + 1):
if i % 2 == 0:
continue
print(i)
You need to print the error before looping from 1 to num because if the value is less the 0 then the loop won't run. I hope you understand.
You have to check the condition num <= 0 as soon as the user enters the number:
num = int(input("Enter number: "))
if num <= 0:
print("error")
else:
for x in range(num):
if x % 2 == 0:
continue
print(x)
score = int(input("Please enter a bowling score between 0 and 300: "))
while score >= 1 and score <= 300:
scores.append(score)
score = int(input("Please enter a bowling score between 0 and 300: "))
print(scores)
I want the user to enter 10 integers one at a time in a loop and store all ten in a list called scores.
You could do something like this, if you do not need the number entered to be restricted within an interval:
scores = []
for i in range(10):
scores.append(int(input())
This will repeatedly wait for a user input, and store each value in the scores list.
If you want the number to be between 1 and 300, simply place the code you already have in a for loop, or create a counter. You could end up with something like this:
scores = []
for i in range(10):
score = 0
while score >= 1 and score <= 300:
score = int(input("Please enter a bowling score between 0 and 300: "))
scores.append(score)
print(scores)
If you're okay assuming that all of the input will be valid, you can simply do:
scores = [int(input("Please enter a bowling score between 0 and 300: ")) for _ in range(10)]
This will raise a ValueError if the input isn't convertable to an int, though, and it also won't check for it being in the range. If you want to re-prompt them on invalid inputs until you have 10 valid inputs, you could make "get a valid score" its own function and then build the list with 10 calls to that:
def get_score() -> int:
while True:
try:
score = int(input("Please enter a bowling score between 0 and 300: "))
if not (0 <= score <= 300):
raise ValueError(f"{score} isn't between 0 and 300")
return score
except ValueError as e:
print(f"Error: {e}. Please try again.")
scores = [get_score() for _ in range(10)]
If you want for the user to input in different lines then this should work:
inputList = []
for i in range(10):
inputList.append(input("Enter: "))
But if you want the user to input all values in same line then use:
inputList = map(int, input("Enter: ").split())
Let's do a different approach than "try this" as it looks like you're a beginner.
To ask a user for an input you can use the input() function. It'll give you a string. To convert a string to a number you can utilize int(), float() or other functions depending on the properties the number should have (decimal numbers, precision, etc).
To repeat a certain action you need to use a loop. You know while as seen in your code. The loop keyword can be nested i.e. you can have a loop within a loop and you can arrange it so that it's checking for the amount of numbers outside of the number limit condition e.g.:
mylist = []
while len(mylist) < 10:
num = int(input("some text"))
while <your number condition>:
mylist.append(num)
...
...
or you can utilize for loop that will execute the block of code only N-times e.g. with range(10):
mylist = []
for _ in range(10):
num = int(input("some text"))
while <your number condition>:
mylist.append(num)
...
...
With a while loop you need to watch out for cases when it might just infinitely loop because the condition is always true - like in your case:
scores = []
score = < a number between 1 and 300, for example 1>
while score >= 1 and score <= 300: # 1 >= 1 and 1 <= 300 <=> True and True
scores.append(score)
score = int(input("Please enter a bowling score between 0 and 300: "))
print(scores)
which will exit in case you enter a number out of the interval but does not guarantee the N-times (10-times) you want. For that to happen you might want to adjust the loop a bit with break to stop the execution after 10 values are present:
scores = []
score = < a number between 1 and 300, for example 1>
while score >= 1 and score <= 300: # 1 >= 1 and 1 <= 300 <=> True and True
scores.append(score)
score = int(input("Please enter a bowling score between 0 and 300: "))
if len(scores) >= 10:
break # stop the while loop and continue to "print(scores)"
print(scores)
However that doesn't handle cases such as inputting 0 or 1000 let's say as once you choose the number out of the interval, it'll stop the while loop even if the amount of scores is less than 10.
And then there's the obvious ValueError when you simply press Enter / Return without entering a number or supply a non-numeric value such as two which is still a number, but will only crash instead converting to 2 with int().
For the first you'd need to encapsulate the number check in other loop or refactor it into something like this:
mylist = []
while len(mylist) < 10:
num = int(input("some text"))
if num >= 1 and num <= 300:
mylist.append(num)
which handles even wrong numeric input e.g. 1000 and will ask for another number.
To handle non-numeric input there are at least two ways - you either let it fail or you check the value first:
With fail first you pass the invalid value to int() automatically and Python interpreter will generate and raise an Exception.
mylist = []
while len(mylist) < 10:
try:
num = int(input("some text"))
except ValueError as error:
# do something with the error e.g. print(error)
# or let it silently skip to the next attempt with "continue"
continue
if num >= 1 and num <= 300:
mylist.append(num)
With value validating you can use isnumeric() method which is present on any string instance (which for your case is the return value of input() function):
mylist = []
while len(mylist) < 10:
num = input("some text")
if not num.isnumeric():
continue
if num >= 1 and num <= 300:
mylist.append(num)
And to make it more compact, you can chain the comparison, though with one unnecessary int() call when the value is correct assuming most of the values are incorrect. In that case num.isnumeric() evaluates to False first and prevents all int() calls while if the input is numberic you end up calling isnumeric() and 2x int():
mylist = []
while len(mylist) < 10:
num = input("some text")
if num.isnumeric() and 1 <= int(num) <= 300:
mylist.append(int(num))
or the other way around, assuming most of the values are correct you can go for the edge-case of incorrect value with try which would be slower afaik but should be faster than always asking whether a string isnumeric().
mylist = []
while len(mylist) < 10:
try:
num = int(input("some text"))
except ValueError:
continue
if 1 <= num <= 300:
mylist.append(num)
Each of the approaches has its own trade off. You can strive for readability, performance, compactness or any other trait and depending on the trait there will be a way to measure it e.g. for performance you might want to use time.time and for readability a linter such as pylint.
A minor extra, in case you are creating a CLI tool, you might want to handle Ctrl + C (interrupt/kill program, will raise KeyboardInterrupt) and Ctrl + D (end input, will raise EOFError). Both can be handled with try/except.
First, you have to define the list 'scores'.
while score >= 1 and score <= 300: means that if the input value does not between 0 and 300, the loop will be over. Therefore, you may not be able to complete the list of 10 integers. You can check this condition by using if instead of while.
The while loop need to check if the scores list has 10 elements or not.
scores = []
while len(scores) < 10:
score = int(input("Please enter a bowling score between 0 and 300:"))
if (1 <= score <= 300):
scores.append(score)
else:
print("Score must be between 0 and 300")
print(scores)
We have to find out the average of a list of numbers entered through keyboard
n=0
a=''
while n>=0:
a=input("Enter number: ")
n+=1
if int(a)==0:
break
print(sum(int(a.list()))/int(n))
You are not saving the numbers entered. Try :
n = []
while True:
a=input("Enter number: ")
try: #Checks if entered data is an int
a = int(a)
except:
print('Entered data not an int')
continue
if a == 0:
break
n.append(a)
print(sum(n)/len(n))
Where the list n saves the entered digits as a number
You need to have an actual list where you append the entered values:
lst = []
while True:
a = int(input("Enter number: "))
if a == 0:
break
else:
lst.append(a)
print(sum(lst) / len(lst))
This approach still has not (yet) any error management (a user enters float numbers or any nonsense or zero at the first run, etc.). You'd need to implement this as well.
a needs to be list of objects to use sum, in your case its not. That is why a.list doens't work. In your case you need to take inputs as int (Can be done like: a = int(input("Enter a number")); ) and then take the integer user inputs and append to a list (lets say its name is "ListName")(listName.append(a)), Then you can do this to calculate the average:
average = sum(listName) / len(listName);
def calc_avg():
count = 0
sum = 0
while True:
try:
new = int(input("Enter a number: "))
if new < 0:
print(f'average: {sum/count}')
return
sum += new
count += 1
print(f'sum: {sum}, numbers given: {count}')
except ValueError:
print("That was not a number")
calc_avg()
You can loop, listen to input and update both s (sum) and c (count) variables:
s, c = 0, 0
while c >= 0:
a = int(input("Enter number: "))
if a == 0:
break
else:
s += a
c += 1
avg = s/c
print(avg)
Write a program which repeatedly reads numbers until the user enters "done". Once "done" is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.
This is what I have.
total = 0
count = 0
average = 0
while True:
number = input("Enter a number:")
if number == "done":
break
try:
total += numbers
count += 1
average = total / len(number)
except:
print ("Invalid input")
continue
print (total, count, average)
When I run this, I always get invalid input for some reason. My except part must be wrong.
EDIT:
This is what I have now and it works. I do need, however, try and except, for non numbers.
total = 0
count = 0
average = 0
while True:
number = input("Enter a number:")
if number == "done":
break
total += float(number)
count += 1
average = total / count
print (total, count, average)
I think I got it?!?!
total = 0
count = 0
average = 0
while True:
number = input("Enter a number:")
try:
if number == "done":
break
total += float(number)
count += 1
average = total / count
except:
print ("Invalid input")
print ("total:", total, "count:", count, "average:", average)
Should I panic if this took me like an hour?
This isn't my first programming language but it's been a while.
I know this is old, but thought I'd throw my 2-cents in there (since I myself many years later am using the same examples to learn). You could try:
values=[]
while True:
A=input('Please type in a number.\n')
if A == 'done':
break
try:
B=int(A)
values.append(B)
except:
print ('Invalid input')
total=sum(values)
average=total/(len(values))
print (total, len(values), average)
I find this a tad cleaner (and personally easier to follow).
The problem is when you try to use your input:
try:
total += numbers
First, there is no value numbers; your variable is singular, not plural. Second, you have to convert the text input to a number. Try this:
try:
total += int(number)
It's because there is no len(number) when number is an int. len is for finding the length of lists/arrays. you can test this for yourself by commenting out the try/except/continue. I think the code below is more what you are after?
total = 0
count = 0
average = 0
while True:
number = input("Enter a number:")
if number == "done":
break
try:
total += number
count += 1
average = total / count
except:
print ("Invalid input")
continue
print (total, count, average)
note there are still some issues. for example you literally have to type "done" in the input box in order to not get an error, but this fixes your initial problem because you had len(number) instead of count in your average. also note that you had total += numbers. when your variable is number not numbers. be careful with your variable names/usage.
A solution...
total = 0
count = 0
average = 0
while True:
number = input("Enter a number:")
if number == "done":
break
else:
try:
total += int(number)
count += 1
average = total / count
except ValueError as ex:
print ("Invalid input")
print('"%s" cannot be converted to an int: %s' % (number, ex))
print (total, count, average)
Problems with your code:
total+=numbers # numbers don't exist; is number
len(number) # number is a string. for the average you need count
if is not done, else process it
Use try ... except ValueError to catch problem when convert the number to int.
Also, you can use try ... except ValueError as ex to get an error message more comprehensible.
So, after several attempts, I got the solution
num = 0
count = 0
total = 0
average = 0
while True:
num = input('Enter a number: ')
if num == "done":
break
try:
float(num)
except:
continue
total = total + float(num)
count = count + 1
average = total / count
print(total, count, average)
Old problem with Update solutions
num = 0
total = 0.0
while True:
number = input("Enter a number")
if number == 'done':
break
try :
num1 = float(number)
except:
print('Invailed Input')
continue
num = num+1
total = total + num1
print ('all done')
print (total,num,total/num)
Write and Run picture
Covers all error and a few more things. Even rounds the results to two decimal places.
count = 0
total = 0
average = 0
print()
print('Enter integers and type "done" when finished.')
print('Results are rounded to two decimals.')
while True:
inp = input("Enter a number: ")
try:
if count >= 2 and inp == 'done': #only breaks if more than two integers are entered
break
count = count + 1
total += float(inp)
average = total / count
except:
if count <=1 and inp == 'done':
print('Enter at least 2 integers.')
else:
print('Bad input')
count = count - 1
print()
print('Done!')
print('Count: ' , count, 'Total: ' , round(total, 2), 'Average: ' , round(average, 2))