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()
Related
I am trying to make a simple prime number detector base on user input. These code line down here I have input 2 and 5 and 123. Even though they are prime number but the program seems to print "not prime number" for any number you input
I have tried a lot but most of my code even didn't print anything.
def check_Prime(f):
if(f<2):
return False
can=math.sqrt(f)
for x in range(2,can):
if(f%x==0):
return False
else:
return True
if check_Prime is True:
print("prime number")
else:
print("not prime number")
I expect if you input a prime number then it will print("prime number") and if you didn't input prime number it will print the other one
You aren't calling the function. Your line if check_Prime is True: is checking if the function itself is true. Which it always is.
You would need to actually call the function with a value like so:
if check_Prime(3) is True:
However you will then discover that this can throw
TypeError: 'float' object cannot be interpreted as an integer
When math.sqrt() returns a non-integer.
You don´t call the function because you check only if the function is available. Change
if check_Prime is True:
print("prime number")
else:
print("not prime number")
to
if check_Prime(<YourInput>) is True:
print("prime number")
else:
print("not prime number")
and fix your TypeError because range only work with integers. Take a look at here or here to learn how to deal with float in range.
Here is a quick function. It is slow. Should you want a speedy function, try this prime checking in python
def check_Prime(number):
if number <= 1:
return False
if number == 2 or number == 3:
return True
if number % 2 == 0:
return False
limit = int(math.sqrt(number)) + 1
for test in range(3, limit, 2):
if number % test == 0:
return False
return True
if check_Prime(3) is True:
print("prime number")
else:
print("not prime number")
import math
def checkPrime(f):
flag = True
if f >= 2:
limit = int(math.sqrt(f)) + 1
for x in range(2, limit):
if f % x == 0:
flag = False
else:
flag = False
return flag
if checkPrime(100):
print("prime number")
else:
print("not prime number")
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 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.
Hi guy’s I’m trying to write a python program here and I’m just learning at the moment. what I’m trying to do is get the user to enter a 6 digit number and if they enter a number which is not 6 digits I want an error message to come us stating they must enter a 6 digit number. I have a function called def example_check_message(m): where I have stated that the number must be 6 digits and I have a function called def example_get_number(): when the user enters the number the get number function should call the def example_check_message(m) function to check the number being entered is correct but nothing is happening. I know I’m close to it but just can’t see where I’m going wrong.
def example_check_message(m):
b = False,
try:
if m == int >= '100000' and '<1000000':
b = True
except:
print 'You must enter a number'
return b
def example_get_number():
example_check_message(1)
b = False
while b == False:
num = raw_input('Please enter a 6 digit number:')
if example_check_message(num) == True:
b = True
continue
value = int(num)
return value
if __name__ == '__main__':
example_check_message(1)
example_get_number()
I think you want something like:
def example_check_message(m):
try:
m = int(m)
if m >= 100000 and m < 1000000:
return m # <- return something useful!
except:
print 'You must enter a number'
return False
but there are errors in this - ill give you some hint where. this shouldn't work as-is, you'll still need to do some work and learning.
def example_get_number():
example_check_message(1)
b = False
while b == False: # not b is the right way here
num = raw_input('Please enter a 6 digit number:')
if example_check_message(num) == True: # This could be simpler
b = True
continue # <- no need to continue here, just return
value = int(num) # <- do this already on the input!
return value
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