If statement syntax error? [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
try:
f = int(factor)
if (factor == 0):
print("No factors present to derive");
elif (factor != int):
print ("Numbers only please!");
elif (factor >> 4):
print("Four maximum factors!");
else:
f = int(factor);
if f == 1:
coefficientone = raw_input("What is the coefficient on the first term?")
try:
coef1 = int(coefficientone)
if (coef1 == 0):
print "No coefficient present, please re-enter polynomial"
elif (coef1 != int)
print "Numbers only please!"
else:
coef1 = int(coefficientone)
This returns a syntax error on the if f == 1: line. Please help! From what I have read on this site and most other sites that line looks to be correct. I would appreciate any help on any other portion of the code, too, for this is my first time working with python. Thanks in advance.

If you're going to add a try block, you have to have a matching except, to handle the exception you're catching.
If you don't know why you're adding the try block, it's best to simply remove it, as to not mask potential errors. It's best to only except specific error types.
Here's the fixed code. The changes are noted with comments.
try:
f = int(factor)
if (factor == 0):
print("No factors present to derive");
elif (factor != int):
print ("Numbers only please!");
elif (factor >> 4):
print("Four maximum factors!");
else:
f = int(factor);
except Exception as e: # Add this
print 'ERROR: {0}'.format(e) #
if f == 1:
coefficientone = raw_input("What is the coefficient on the first term?")
try: # Un-indent this
coef1 = int(coefficientone)
if (coef1 == 0):
print "No coefficient present, please re-enter polynomial"
elif (coef1 != int)
print "Numbers only please!"
else:
coef1 = int(coefficientone)
except Exception as e: # Add this
print 'ERROR: {0}'.format(e) #
Finally, it seems like you're planning on asking the user for as many coefficients as he specifies. For this, you'll probably want to consider using a for loop to handle the input, and a list to store the values. I'll leave the implementation details up to you. There are plenty of resources out there.

#an error that I am seeing is that factor != int should be:
elif type(factor) != int:
#and adding to the try I think that you will also need a except ValueError:

Related

Python exercise using try/except with continue [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I can't figure out why my code doesn't work properly here, it seems to exit the for loop after the except: continue line. What do I do to fix this? (the code executes but the output is always -1 no matter what list/letter combination is fed so nothing is ever being added to the sum_total variable)
sample_list = [
'Black Mirror',
'Breaking Bad', #2
'Stranger Things', #6
'The Leftovers', #2
'How I Met Your Mother' #7 4.25
]
letter = 'e'
def find_average_first_index(input_list, input_letter):
sum_total = 0
for i in input_list:
try:
sum_total += input_list.index(input_letter)
print(sum_total)
**except:
continue**
if sum_total == 0:
return -1
else:
average_value = (sum_total / len(input_list))
return average_value
You are using index on input_list. I think you might want to use it on i.
sum_total += i.index(input_letter)
When you call index method with an element not in the list it will raise ValueError Exception and your code will go to except block and because of the continue there, it will move to next iteration. And because you are using index method on input_list with letter, it will always raise ValueError in this code and that is the reason for the bug in your code.
https://www.w3schools.com/python/ref_string_index.asp
https://www.w3schools.com/python/ref_list_index.asp
Here's fixed code:
def find_average_first_index(input_list, input_letter):
sum_total = 0
for i in input_list:
try:
sum_total += i.index(input_letter)
print(sum_total)
except ValueError as e:
print(e)
print(f"No {input_letter} in {i}")
continue
if sum_total == 0:
return -1
else:
average_value = (sum_total / len(input_list))
return average_value
Your code need to change like this
sample_list = [
'Black Mirror',
'Breaking Bad', #2
'Stranger Things', #6
'The Leftovers', #2
'How I Met Your Mother' #7 4.25
]
letter = 'e'
def find_average_first_index(input_list, input_letter):
sum_total = 0
for i in input_list:
try:
sum_total += input_list.index(input_letter)
print(sum_total)
except:
continue
if sum_total == 0:
return -1
else:
average_value = (sum_total / len(input_list))
return average_value
find_average_first_index(sample_list,letter)
errors:-
You need to add try and except like this (if your code pattern is wrong you can see error messages; see: https://careerkarma.com/blog/python-break-and-continue/)
try:
sum_total += input_list.index(input_letter)
print(sum_total)
except:
continue
find_average_first_index(sample_list,letter)
run the code you need call function. (ref: https://www.w3schools.com/python/python_functions.asp)

It shows the error as 'fact' not defined.why? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
def factorial(n):
if(n == 1):
fact = 1
return fact
else:
fact = a * factorial(n - 1)
return fact
a = int(input("Enter a number to find its factorial: ")
if (a > 0):
print("The factorial of", a, "is:", fact)
else:
print("Enter a positive value to find its factorial")
In the above code it tells me that - NameError name 'fact' is not defined .
Lines starting from a = int... should be outside your function. Once that is done all you need is to add fact = factorial(a).
Find the correct logic below.
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))

I don't understand why this code doesn't work :( [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to not accept the username if it is not between 3 and 9 characters.
print (""+winner+", please input your first name, maximum of 10 characters.")
winnername = str(input())
length = (int(len(winnername)))
if 3 > length > 10:
loop5 = 1
while loop5 == 1:
print ("name is too short")
winnername = input()
length = len(winnername)
if (length) <3 and (length) <10:
break
print ("name accept")
I would expect it to loop and ask the user for another input if the provided input doesn't meet the requirements outlined in the above text.
if 3 > length > 10: is checking to make sure that length is LESS than 3 and Greater than 10, which is impossible.
Therefore the check should be if 2 < length < 10: (this will be true for lengths 3 to 9)
Let me fix your code, elegant and clean:
while True:
# I don't know if `winner` is defined
firstname = input(""+winner+", please input your first name, maximum of 10 characters.")
if 3 < len(firstname) < 10:
break
print("name is too short or too long")
print('name accepted')
The problem is 3 > length > 10 will never be executed because 3 will never be greater > than 10
Regarding your first sentence, as far as I can see form the code you are actually trying to allow maximum number of characters to be 10, not 9.
Below is a possible solution for what you're trying to achieve. The below script will keep asking user until name length is within allowed range.
print ("'+winner+', please input your first name, maximum of 10 characters.")
while True:
winnername = str(input())
if(len(winnername) < 3):
print("Name is too short")
elif(len(winnername) > 10):
print("Name is too long")
else:
break
print ("Name accepted")
You may also consider to perform some validation of winnername first (do not allow spaces or any other special characters).
winner = "Mustermann"
# Build a string called "prompt"
prompt = winner + ", please input your first name, between 3 and and 10 characters."
loopLimit = 5 # Make this a variable, so it's easy to change later
loop = 0 # Start at zero
winnername = "" # Set it less than three to start, so the while loop will pick it up
# Put the while loop here, and use it as the length check
# Use an or to explicitely join them
while True: # Set an infinite loop
loop += 1 # Increment the loop here.
# Add the string to the input command. The "input" will use the prompt
# You don't need the "str()", since input is always a string
winnername = input(prompt)
length = len(winnername)
# Separate the checks, to give a better error message
if (length < 3):
print ("Name is too short!") # Loop will continue
elif (length > 10):
print("Name is too long!") # Loop will continue
else: # This means name is OK. So finish
print("Name accepted!")
break # Will end the loop, and the script, since no code follows the loop
if loop >= loopLimit:
# Raise an error to kill the script
raise RuntimeError("You have reached the allowed number of tries for entering you name!")

Issue with if-else statements [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
This is what I've input:
def greater_less_equal_5(answer):
if 6 > 5:
return 1
elif 4 < 5:
return -1
else:
return 0
print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)
and gave me this note
Oops, try again. It looks like your function output 1 instead of -1
when answer is 3. Make sure you filled in the if and elif statements
correctly!
and this is what came up in the upper right display:
>1
>1
>1
>None
No matter how I change around the numbers and the >/< I've even tried == and != it still outputs 1 1 1 None.
I've searched around for any possible tips and seen others stuck on the same problem as me and when I tried their solves I then get:
def greater_less_equal_5(answer):
if > 5:
return 1
elif < 5:
return -1
else:
return 0
print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)
and the output is:
File "python", line 2
if > 5:
^
SyntaxError: invalid syntax
Is this test rigged to always output a failed result to make me pay for pro and ask for their help?
And the hint given for this is:
Make sure the if and elif statements end with colons :
Your code should look something like:
if EXPRESSION:
do something
elif OTHER EXPRESSION:
do something
else:
do something
Am I just missing something horribly basic?
You are indeed missing something basic - namely, that the output of your function doesn't depend on answer at all. No matter what you feed in as answer, because 6 > 5 is always True, it will always return the result of that case.
What you need is
def greater_less_equal_5(answer):
if answer > 5:
return 1
elif answer < 5:
return -1
elif answer == 5:
return 0
You're missing 'answer' variable for expression, which you pass into your function
def greater_less_equal_5(answer):
if answer > 5:
return 1
elif answer < 5:
return -1
else:
return 0
print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)

Python Try / Except [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
What is the correct way to use Try / Except?
I am pretty new to Python and just trying to learn this new technique so any ideas why this doesn't work?
temp=input("Please choose an option: ")
try:
if temp == ("1"):
fc=input("Fahrenheit: ")
fer(int(fc))
if temp == ("2"):
cf=input("Celsius: ")
cel(int(cf))
except ValueError:
print("It looks like you input a value that wasn't a number!")
If you put a value in "temp" that isn't 1 or 2 than it should print that it isn't a number but it doesn't, any ideas?
"It looks like you input a value that wasn't a number!" will be printed if there is an exception in your try block. What you wanna do is:
temp=input("Please choose an option: ")
try:
if temp == ("1"):
fc=input("Fahrenheit: ")
fer(int(fc))
elif temp == ("2"):
cf=input("Celsius: ")
cel(int(cf))
else:
print("It looks like you input a value that wasn't 1 or 2!")
except ValueError:
print("It looks like you input a value that wasn't a number!")
You MUST keep the try and catch because it is possible that the input is not a number.
temp=input("Please choose an option: ")
try:
if temp == ("1"): # is temp == "1"
fc=input("Fahrenheit: ") # if yes, get number
fer(int(fc)) # convert to int, this can raise an exception
if temp == ("2"): # is temp == "2"
cf=input("Celsius: ") # if yes, get number
cel(int(cf)) # this can raise an exception
except ValueError: # capture all ValueError exceptions
print("It looks like you input a value that wasn't a number!")
The value of temp can never raise an exception in your code (only the parsing of the input can) so it just passes through. You need to add a check by hand to make sure temp is one of the valid entries.
A better way to do this would be (and you could validate temp via an exception):
def handle_f():
fc=input("Fahrenheit: ") # if yes, get number
fer(int(fc)) # convert to int, this can raise an exception
def handle_C():
cf=input("Celsius: ") # if yes, get number
cel(int(cf)) # this can raise an exception
fun_dict = {"1": handle_f, "2": handle_c}
try:
fun_dict[temp]()
except KeyError: # handle temp not being valid
print('not a valid temperature type')
except ValueError:
print("It looks like you input a value that wasn't a number!")
I think it's cleaner to abstract the process of reading an int from the user:
def input_int(prompt):
try:
return int(input(prompt))
except ValueError:
print("It looks like you input a value that wasn't a number!")
temp=input("Please choose an option: ")
if temp == ("1"):
fc=input_int("Fahrenheit: ")
fer(fc)
if temp == ("2"):
cf=input_int("Celsius: ")
cel(cf)

Categories