I need to limit the number of invalid inputs allowed so that after the given amount of tries the program exits.
Invalid is defined by the input being less than zero.
The number of attempts let say is 3.
def number():
number = float(input('please enter a number (must be greater thatn zero): '))
if number >= 0 :
print ('you choose number:', number)
else:
print ('invalid input')
return
number()
How would I limit the number of invalid input attempts and make it so that the code would return to asking the question again and prompt for input but still keep track of previous attempts?
You have to use a loop, in this case a while loop will be convinient. You have to declare a variable invalid_attempts to keep the count of how many invalid inputs the user has given.
The condition to finish the loop will be when invalid_attempts, which is increased when you get an invalid input, is greater or equal to 3. You may want to change 3 to fit your requirements:
def get_input():
invalid_attempts = 0
while invalid_attempts < 3:
number = float(input('please enter a number (must be greater thatn zero): '))
if number >= 0 :
print ('you choose number:', number)
return number # so you can call the method as 'some_variable = get_input()'
else:
print ('invalid input')
invalid_attempts += 1
Note: Since number is the name of the method, you shouldn't call a variable inside with the same name (because if you do, you won't be able to use that function inside, if it's necessary), in this case I'm calling the method get_input.
Use whilie loop before number = ..., for instance:
count = 0
while count < 3:
# do rest of the stuffs
count += 1
Actually, I think a for loop looks nicer:
for retry in range(5): # number of retries
try:
choice = float(input('please enter a number (must be greater thatn zero): '))
except ValueError:
print('Please enter an actual number')
continue
if choice >= 0:
print('You chose ', choice)
break
else:
print('Number must be >= 0')
continue
else:
print('Too many failures: be more cooperative')
(This is called a for-else construct; the else runs only if the for loop did not break).
You can also do it slightly more elegantly using recursion:
def get_number(max_tries, count = 0)
if count < max_tries:
valid_input = False
number = 0
try:
number = float(input('Please enter a number > 0'))
if number > 0:
valid_input = True
except:
pass
if valid_input:
return number
else:
return get_numbers(max_tries, count+1)
else:
print('Sorry, Too many Tries!)
return None
Whether you use a while loop or recursion is usually a matter of taste. They're functionally equivalent in many situations, of which this is on. This example also accounts for what happens if the user enters something that isn't a number, which will cause the float cast to throw.
Update:
To clarify a question asked by the OP:
def get_numbers(max_tries, count = 0)
Defines a function get_numbers, which takes two inputs, max_tries and count. count is given a default value, count = 0, which means if you call the function without specifying the count parameter, it will automatically assign it to be 0. max_tries is left without a default value, meaning you need to specify it every time you call the function or python will throw an error. If you usually have the same number of maximum tries, you could also assign this a default value, which would allow you to simply do number = get_numbers() and have it work as expected.
Recursion, to over-simplify, is basically when a function calls itself during its execution. Let's assume we did the following:
number = get_number(10)
And the user enters -1, which will cause the code to reach:
else:
return get_numbers(max_tries, count+1)
Since we said get_numbers(10), max_tries = 10, and count = 0, so this line becomes:
else:
return get_numbers(10, 1)
This causes the function to return the result of calling get_numbers again. Eventually the user will either enter valid input, or count > max_tries, which will cause the function to finally return a value.
Read the wiki I liked to, recursion is hard to explain without drawing it, but hopefully that helps.
Related
number = 0
number_list = []
while number != -1:
number = int(input('Enter a number'))
number_list.append(number)
else:
print(sum(number_list)/ len(number_list))
EDIT: Have found a simpler way to get the average of the list but if for example I enter '2' '3' '4' my program calculates the average to be 2 not 3. Unsure of where it's going wrong! Sorry for the confusion
Trying out your code, I did a bit of simplification and also utilized an if statement to break out of the while loop in order to give a timely average. Following is the snippet of code for your evaluation.
number_list = []
def average(mylist):
return sum(mylist)/len(mylist)
while True:
number = int(input('Enter a number: '))
if number == -1:
break
number_list.append(number)
print(average(number_list));
Some points to note.
Instead of associating the else statement with the while loop, I revised the while loop utilizing the Boolean constant "True" and then tested for the value of "-1" in order to break out of the loop.
In the average function, I renamed the list variable to "mylist" so as to not confuse anyone who might analyze the code as list is a word that has significance in Python.
Finally, the return of the average was added to the end of the function. If a return statement is not included in a function, a value of "None" will be returned by a function, which is most likely why you received the error.
Following was a test run from the terminal.
#Dev:~/Python_Programs/Average$ python3 Average.py
Enter a number: 10
Enter a number: 22
Enter a number: 40
Enter a number: -1
24.0
Give that a try and see if it meets the spirit of your project.
converts the resulting list to Type: None
No, it doesn't. You get a ValueError with int() when it cannot parse what is passed.
You can try-except that. And you can just use while True.
Also, your average function doesn't output anything, but if it did, you need to call it with a parameter, not only print the function object...
ex.
from statistics import fmean
def average(data):
return fmean(data)
number_list = []
while True:
x = input('Enter a number')
try:
val = int(x)
if val == -1:
break
number_list.append(val)
except:
break
print(average(number_list))
edit
my program calculates the average to be 2 not 3
Your calculation includes the -1 appended to the list , so you are running 8 / 4 == 2
You don't need to save all the numbers themselves, just save the sum and count.
You should check if the input is a number before trying to convert it to int
total_sum = 0
count = 0
while True:
number = input("Enter a number: ")
if number == '-1':
break
elif not number.isnumeric() and not (number[0] == "-" and number[1:].isnumeric()):
print("Please enter numbers only")
continue
total_sum += int(number)
count += 1
print(total_sum / count)
I'm doing a project whereby a user has to input the value. The loop should end if the user key in the value of more than 300 for 3 times. If the user key in a value lesser than 300, a warning message should be prompted. And another criteria is that I need to allow the user to get out of the loop if the user do not meet the condition above. For now, I tried to do by using the list but my code doesn't seem to count the number of inputs.
list1 = list()
counter = 1
while counter <= 3:
ask = float(input("Please enter each of the value: "))
while ask != "":
list1.append(str(ask))
ask = float(input("Please enter each of the value: "))
if ask >= 50:
counter += 1
else:
print("Value must be more than 300. If you do not meet the criteria, please press 'enter'. ")
print(list1)
The following code is my original code which doesn't take into account of the minimum input value.
counter = 1
while counter <= 3:
ask = float(input("Please enter each of the value: "))
if ask >= 50:
counter += 1
else:
print("Value must be more than 300 ")
I would appreciate if anyone of you can help me out.
The problem is your inner while loop can't exit since ' "" ' (your exit signal) cannot be converted to float. Instead it will raise a ValueError.
One possible solution to this would be to try converting input to float and except the ValueError. It could look something like this.
list1 = list()
counter = 1
while counter <= 3:
try:
ask = float(input("Please enter each of the value: "))
except ValueError:
break
list1.append(str(ask))
if ask >= 50:
counter += 1
else:
print("Value must be more than 300. If you do not meet the criteria, please press 'enter'. ")
print(list1)
I think the program doesn't work as you want because you made two while loops:
the first while's condition is while counter<=3, ok but then you made another while which condition is ask !="", so the program will run inside this second while loop until the condition is no more true and the first while does not "see" the counter's changes.
By the way, I think you can simply use only one while loop(the first one), and write an if condition that verify the value(>300).
When you try to cast a string element into a float type it will throw an error if the value could not be casted to that type, you could use a try-except block.
while counter < 3:
try:
ask = float(input("xxxxx")
if ask >= 50:
counter += 1
else:
print("xxxxx")
except ValueError:
break
print(list1)
My assignment requires me to take in an input, determine how many digits are in said input, then spit it back out. we are not allowed to use string conversion in order to determine the length of the input. I've managed to get that to work properly. My issue is that I'm supposed to have it repeat in a loop until a sentinel is reached. Here's my code so far.
print("This program determines the number of digits in a number.")
print("Enter a number, or 0 to quit.")
count = 0
num = 1
final = 0
num = int(input("Enter a number: "))
while num != 0:
num = num //10
count += 1
print("There are", count, "digits in", num)
I'm also seeming to have trouble with having my input integer print properly, but it might just be my ignorance there. I've cut out what my attempts at looping it were, as they all seemed to just break the code even more. Any help is welcome, even criticism! Thank you in advance!
Firstly, that is a strange way to get the digits in the number. There's no need to modify the actual number. Just cast the int back to a string and get the length (don't just keep the original string, it could have spaces or something in it which would throw off the count). That is the number of digits.
Secondly, you can do all the work in the loop. There's no need for setup variables, incrementing, a second loop, or anything like that. The key insight is the loop should run forever until you break out of it, so you can just use "while True:" for the loop, and break if the user inputs "0".
print("This program determines the number of digits in a number.")
print("Enter a number, or 0 to quit.")
def find_digits(num):
count = 0
while num != 0:
num = num //10
count += 1
return count
count += 1
# loop forever
while True:
# hang onto the original input
text_input = input("Enter a number: ")
# cast to int - this will throw an exception if the input isn't int-able
# you may want to catch that
num = int(text_input)
# the number of digits is the length of the int as a string
num_digits = find_digits(num)
if num == 0:
print("Goodbye.")
# "break" manually ends the loop
break
# if we got to this point, they didn't input 0 and the input was a number, so
# print our response
print(f"There are {num_digits} digits in {num}.")
The problem with printing the input integer correctly is, that you first save it in the num variable and then constantly change it in your while loop. So the original input is lost of course and in the end it always prints the 0, that ends up in num after the while loop finishes.
You can easily fix it, by saving the input value to another variable, that you don't touch in the loop.
print("This program determines the number of digits in a number.")
print("Enter a number, or 0 to quit.")
count = 0
num = int(input("Enter a number: "))
numcopy = num
while numcopy != 0:
numcopy = numcopy // 10
count += 1
print("There are", count, "digits in", num)
Counting is better done with Python builtin functions.
len(str(num))
will give you number of digits in your number.
I am working on a program that requires the user to enter a number and will continue to loop until a positive number is given. When a positive number is given, it will alert the user and present them with the sum of the digits of their number. However, I thought I had written my code correctly, but it is giving me an incorrect answer. What have I done wrong and how can I fix this?
user_input = float(int(input("Please Enter Your Number:")))
s = 0
while user_input < 0:
float(int(input("Please Enter Another Number: ")))
if user_input > 0:
s += user_input%10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
Four things:
Not sure why you storing the input as float, int should suffice.
If you give a negative input, it will enter the while loop. However, in the while loop, you are not actually assigning the new input to user_input. Fix this by adding user_input =
The while loop guarantees user_input is >= 0, so if user_input > 0: is unnecessary.
Probably the most important, to calculate the sum of digits, you need to repeatedly divide and sum, not just do it once. So, add a while loop.
Final code:
user_input = int(input("Please Enter Your Number: "))
s = 0
while user_input < 0:
user_input = int(input("Please Enter Another Number: "))
while user_input:
s += user_input % 10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
The if statement is generally used to decide if something should be done once.
If you want to keep going until user_input becomes zero, you'll need a while.
Also, I'm not entirely certain why you're storing the number as a float, especially when you make that from an int anyway. It may as well just be an int.
Additionally, you're loop to re-enter the value if it was negative doesn't actually assign the new value to the variable.
And you probably also want to outdent the print statement lest it be done on every iteration of the loop you're about to add.
Of course, some may suggest a more Pythonic way of summing the digits of a positive number is a simple:
sum([int(ch) for ch in str(x)])
That works just as well, without having to worry about explicit loops.
Another way to solve this is using assert and a function:
def sum_num():
# try get user input
try:
user_in = input('Enter Number: ')
assert int(user_in) > 0
except AssertionError:
# we got invalid input
sum_num()
else:
s_d = sum([int(i) for i in user_in])
print('You\'ve entered a positive number! The sum of the digits is: ', s_d)
#run the function
sum_num()
So this will asked user input, if it is not greater than zero it will throw assertion error, which we catch and return the user to inputting the number by calling the function again. If all is well, we split the input into character and add them up. as list('12') gives ['1','2']. We convert to int and add them. :)
The awesome thing about this is you can add more too the asset to capture other issue as floats, character as invalid inputs. E.g.
Assuming literal_eval is important( from ast import literal_eval)
assert isinstance(literal_eval(user_in),int) and int(user_in)>0
Check if user_in is integer and it is greater than 0. So you won’t get issues when user inputs floats or characters.
I am having issues regarding python. My issue is that my code always prints the first if statements return even if the user inputs a valid integer. I genuinely do not know the issue. I have to allow the user to input a value that is restricted to 1-10 and I have to be able to output either, "Please input an integer between 1-10" or "That's not even a number silly!". Could someone please help me and do more than just write the code, but explain it too?
value = input("Please input an integer: ")
def numValue(value):
for value in range(-1000, 1000):
if (value < 1, value > 10):
return "Please input a number between 1-10."
elif (value >= 1, value <= 10):
return "Great choice!"
print (numValue(value))
First you need to tell python that you are expecting an integer. This is done by wrapping int(..) around input
You have an unnecessary for loop with range. It is not needed
The syntax to check if a number is between a range is start < num < end or (<=) if you want the range to be inclusive
You don't to add the inverse check in elif, using else will automatically fallback if original condition fails
value = int(input("Please input an integer: "))
def numValue(value):
if 1 <= value <= 10:
return "Great choice!"
else:
return "Please input a number between 1-10."
print (numValue(value))