I am the most beginner of the beginners and I'm getting a syntax error message for the semicolon after 'elif' why is that? Also, should the code work otherwise?
#a - this program uses function valid(x) to determine if the user's input is a positive, non-zero number while imposing a limit of 3 attempts
def valid(x):
return (x > 0)
n = int(input('Please input a positive non-zero number: '))
if(valid(n)== True):
print(n,'is valid')
elif:
print(u = int(input('error please input a positive non-zero number: ')))
if(valid(u)== True):
print(u,'is valid')
elif:
print(m = int(input('error please input a positive non-zero number: ')))
if(valid(m)== True):
print(m,'is valid')
The following is a proper syntax for if..else condition in python. Are you following this?
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE. In your code snippet, there is no expression to be executed in the elif statement!
I believe you need something like as follows.
# This program uses function valid(x) to determine if the user's input is positive, non-zero number while imposing a limit of 3 attempts
def valid(x):
return (x > 0)
n = int(input('Please input a positive non-zero number: '))
if(valid(n)== True):
print(n,'is valid')
else:
n = int(input('error please input a positive non-zero number: '))
if(valid(n)== True):
print(n,'is valid')
else:
n = int(input('error please input a positive non-zero number: '))
if(valid(n)== True):
print(n,'is valid')
Your syntax is invalid because elif is short for else if and you don't have a condition to test. Try just using else: for that.
Also, don't compare against True. Just let the expression stand alone. And this isn't C or Java, so no parens around conditionals:
if(valid(n)== True):
print(n,'is valid')
Becomes:
if valid(n):
print(n, 'is valid')
Just offering a more concise solution (and pythonic). elifs need a condition. You can use a for loop to check the password three times. And if the password is correct, the loop ends.
def valid(x):
return x > 0
for i in range(3):
n = input('Please input a positive non-zero number: ')
if valid(n):
print(n, 'is valid')
break
Related
Below is my code. I am trying to loop this while code input, so if someone gives anything other than a numeric then it has to respond with the below message and then ask for the number again. But i am stuck it tried many variations of whiel try blocks.. but the output seem to be if the number is valid, then it gives the response[ prime or not] along with the secondary print value about the non numeric and if the input is non numeric, it gives an error for it being non numeric.... any help or suggestions pls
def prime_checker(number) :
is_prime = True
for i in range(2, number) :
if number % i == 0 :
is_prime = False
if is_prime :
print("It's a prime number")
else :
print("Its not a prime number")
should_continue = True
num = int(input("Check this number: "))
prime_checker(number=num)
while not num == int():
result = input("You have entered a non numeric value, please enter a number to continue else enter 'no' to exit. '.\n")
if result == "no":
should_continue = False
print("Goodbye")
You should check for the type of the variable and not the variable itself:
...
while not isinstance(num, int):
....
You cannot have while not num == int() You can have while num.isdigit() == False. Remember when you are using input you are receiving a string. And you need a try: except: block to handle the int(num) check or use num.isdigit(). You are not using your should_continue variable anywhere meaningful. You need to use a break command to exit the while loop.
Changed your code to make it more sensible
question:
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 it.
Input:
7 ,2 , bob, 10, 4, done.
Desired output:
Invalid input
Maximum is 10
Minimum is 2
Actual output:
Invalid input
Invalid input
Maximum is 10
Minimum is 2
Code:
largest=-1
smallest=None
while True:
num =input("Enter a number: ")
try:
if num == "done" :
break
elif smallest is None:
smallest=int(num)
elif int(num)<smallest:
smallest=int(num)
elif int(num)>largest:
largest=int(num)
else:
raise ValueError()
except ValueError:
print("Invalid input")
print("Maximum is",largest)
print("Minimum is",smallest)
I think there's a more Pythonic way of doing this. Try this:
inputList = []
while True:
num = input("Enter a number:")
try:
num = int(num)
inputList.append(num)
except:
if num == "done":
break
else:
print ("Invalid input. Ignoring...")
print ("Maximum is:",max(inputList))
print ("Minimum is:",min(inputList))
Edit: This code works with Python3. For Python2, you might want to use raw_input() instead of input()
You are already capturing the ValueError in Exception,
So inside, try, you are raising ValueError there you leave the scope for this error.
When you accept input, and it accepts 4 as input, which is neither larger than largest (i.e. 10) nor smaller than the smallest (i.e. 2). So it lands in else part and raises ValueError (as per your code). Hence prints Invalid input twice in your case. So this part is unnecessary as well as makes your solution bogus.
Again, from efficiency point of view -
1 - You are checking smallest == None for every input, which takes O(1) time and is unnecessary if you take it any integer
Here is the solution you are looking for :-
largest=None
smallest=None
while True:
try:
num = input("Enter a number: ")
num = int(num)
if smallest is None:
smallest = num
if largest is None:
largest = num
if num < smallest:
smallest = num
elif num > largest:
largest = num
except ValueError:
if num == 'done':
break
else:
print("Invalid input")
continue
print("Maximum is",largest)
print("Minimum is",smallest)
I'm building my first calculator. Trying to implement While loop to get a number through user input. I want the While to break once user put a number.
num1 = raw_input("Add mumber one: " )
try:
input = int(num1)
except ValueError:
print "This is not a number"
attempt = 0
while type(num1) != int and attempt < 5:
num1 = raw_input("Add Number one again: " )
attempt += 1
break
print "You are not putting number. So, goodbuy"
operation = raw_input("Add Operator: ")
Try this:
for _ in range(5):
num1 = unicode(raw_input("Add number one: "))
if num1.isnumeric():
break
Another method you can try is to have num1 and do the following in the while loop:
if type(num1) is int:
break
What this does is check the type of the variable num1. If it is an integer, int, then it breaks out of the while loop.
I want the While to break once user put a number.
You already are doing that in the condition for your while loop by having type(num) != int so your while loop should stop after the user enters an integer.
You have several errors here:
while type(num1) != int and attempt < 5:
num1 = raw_input("Add Number one again: " )
attempt += 1
break
The break statement shoud be inside the loop, but the indentation is wrong. As you write, it is after the loop (hence useless). Also, when you read from standard input, you always get a string even if it is a number. So when you check type(num1) != int this is always false. You must convert num1 with int() each time you read from standard input, not only the first time:
while True:
num1 = raw_input("Add Number one again: " )
try:
input = int(num1)
break
except ValueError:
print "This is not a number"
if attempt == 5:
break
attempt += 1
Here I try to convert to an integer the string read from stdin. If it works, I break the loop immediately. If it does not work (the except clause) I check how many attempts have been done, and break the loop if the attempts are equal to 5.
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.
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