Python can't print the word from the given condition - python

I have this program:
def validateNumber(number):
if (count > 10) :
print('Invalid number')
return -1
elif (count < 10):
print('Invalid number')
return -1
while True:
count = 0
num = int(input('Number:'))
while num > 0:
num = num//10
count = count+1
if (count == 10) :
break
But I can't print the print('Invalid number') and it turn out to be like this:
Number:122344
Number:123442
Number:1234567890
>>>
I want it to print the print('Invalid number') when the number is less or more than 10.
Number:122344
Invalid number
Number:123442088080989098
Invalid number
Number:1234567890
>>>
Help please. Thanks
The return -1 is for if the number is missing or invalid

Firstly, you could condense your if check to one statement. Note that the easiest way to count the number of digits is to convert it to a string and check its length.
def validateNumber(number):
if len(str(number)) != 10:
return -1
Unfortunately, you do not return a legitimate value if the number is valid. Why not return a boolean value instead?
def validateNumber(number):
if len(str(number)):
return True
return False
You can further reduce this to:
def validateNumber(number):
return len(str(number)) == 10
Note that all the validation logic has now been moved to the function. You'll see how this simplifies the loop code.
Next, you have defined two loops. When you break from the inner, the outer will continue, so you come back to the inner, thus restarting the process.
As a fix, I'd recommend doing this with one loop only, like this:
while True:
x = int(input('...'))
if validateNumber(x):
break
else:
print('Invalid Number')
Since validateNumber returns a bool result, simply have the if query the return value, and break if the number is valid, otherwise the loop repeats.
The good thing about having all your validation code inside the function is that you don't have to modify your loop code if your validation logic changes.

Related

Keep asking for numbers and find the average when user enters -1

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)

How to get Python functions to calculate maths operations?

I have this assignment to create a program that asks user to input any positive integer repeatedly or type anything else to end and generate the sum, count and average of the numbers. My teacher wants all the code in these this structure with these three def’s only
This is the code I have, any suggestions on how to get it to work?
def calcAverage(total,count):
sum = 0
count = 0
average = sum / count
def inputNumber(message):
while True:
try:
userInput = int(input(message))
count = count + 1
sum = sum + entry
if userInput < 0:
raise ValueError
except ValueError:
main()
else:
return userInput
break
entry = inputNumber('Type any positive integer, anything else to quit')
def main():
print('Sum')
print(sum)
print('Average')
print(average)
print('Total Numbers')
print(count)
The question is not well explained + we don't really get what the boundaries are. Moreover, you should clearly state what is not working. Now, to give you some hint, this is how I would do it:
input = None
L = list()
while True:
try:
input = int(input('Type any positive integer, anything else to quit: '))
if input < 0:
break
else:
L.append(input)
except:
break
S = sum(L)
I think you don't need to use exceptions here. Condition statements would make it clearer.
I would put the valid inputs in a list until the user make a invalid input. When it happens, just get out of your while loop using a break statement and return the result.

I can't seem to get this function to repeat itself if the while condition is True

My code is supposed to take a user's input for a value of 'n' that must be a positive integer, and if it's not positive or if it's a string rather than a integer than it should repeat the input process. Here's my code:
def input_n():
"""obtains n value from user"""
while True:
print("Input number of terms n (must be > 0):")
n = input("> ")
if not n.isdigit():
print("Not a usuable n value")
return None
continue
else:
n = int(n)
if n < 1:
print("Not a usuable n value")
return None
else:
return n
I've tried it with and without the continue statement at the end of the first if loop. It never seems to repeat itself if a negative number or string is inputed. It moves on to the next part of my code (not shown or necessary). Does anyone know why it's not repeating since the while loop remains True?
The return statement ends the function.
So when you execute return None it cannot repeat itself in the cycle since it's already out of it.
You probably want to use continue instead of return None
Looks like you're returning if n isn't a digit, which exits the function.
def input_n():
"""obtains n value from user"""
print("Input number of terms n (must be > 0):")
while True:
n = input("> ")
if not n.isdigit():
print("Not a usable value - must be a number!")
continue
n = int(n)
if n < 1:
print("Not a usable value - too low!")
continue
return n
Try this
def input_n():
print("Input number of terms n (must be > 0):")
while True:
n = raw_input("> ")
if not n.isdigit() or n < 1:
print("Not a usuable n value")
continue
else:
return n

python: input validation return

I am trying to return the number if it is an INT and between numbers, an error occurs when you enter a letter . also you have to input the correct value twice to get an input:
def get_number():
b = False
while b == False:
try:
n = (input('Please enter a 6 digit number'))
except ValueError:
continue
if n >= 100000 and n <= 1000000:
b = True
break
return n
if __name__ == '__main__':
get_number()
print get_number()
`
Changed input to raw_input , it now work if someone enters a letter. however when i enter the correct input ,it will keep on looping:
def get_number():
b = False
while b == False:
try:
n = (raw_input('Please enter a 6 digit number'))
except ValueError:
continue
if n >= 100000 and n <= 1000000:
b = True
break
return n
if __name__ == '__main__':
get_number()
print get_number()
There are a few problems with your code.
you could just use input to evaluate whatever the unser entered, but that's dangerous; better use raw_input to get a string and try to cast that string to int explicitly
also, if you are using input, then you'd have to catch NameError and SyntaxError (and maybe some more) instead of ValueError
currently, your if condition would allow a 7-digit number (1000000) to be entered; also, you can simplify the condition using comparison chaining
no need for the boolean variable; just break or return from the loop
you call your function twice, and print only the result of the second call
You could try something like this:
def get_number():
while True:
try:
n = int(raw_input('Please enter a 6 digit number '))
if 100000 <= n < 1000000:
return n
except ValueError:
continue
if __name__ == '__main__':
print get_number()

limiting invalid input in python 3

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.

Categories