Python exercise using try/except with continue [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 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)

Related

Basic python tic tac toe: "TypeError: list indices must be integers or slices, not list" [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 1 year ago.
Improve this question
I'm new to this, but I'm trying to make tic-tac-toe in python and following this instructional video (https://www.youtube.com/watch?v=n2o8ckO-lfk&t=1777s). I've tried to make sense of it and checked with the source code for some time now and can't figure out what I'm doing wrong. It isn't finished yet, but there shouldn't be an error coming out in the terminal right now if I was doing it right. The error says "TypeError: list indices must be integers or slices, not list." I've put arrows by the lines that Replit is saying is causing it. Thanks!!
board = [
["-", "-", "-"],
["-", "-", "-"],
["-", "-", "-"]
]
def print_board(board):
for row in board:
for slot in row:
print(f"{slot} ", end = "")
print()
def quit(user_input):
if user_input.lower() == "q":
print("Thanks for playing!")
return True
else: return False
def check_input(user_input):
#check if it's a number
if not isnum(user_input): return False
user_input = int(user_input)
#check if it's 1 - 9
if not bounds(user_input): return False
return True
def isnum(user_input):
if not user_input.isnumeric():
print("This is not a valid number")
return False
else: return True
def bounds(user_input):
if user_input > 9 or user_input < 1:
print("This number is not 1 - 9.")
return False
else: return True
def istaken(coords,board):
row = coords[0]
col = [1]
if board[row][col] != "-": <------------
print("Something's already there.")
return True
else: return False
def coordinates(user_input):
row = int(user_input / 3)
col = user_input
if col > 2: col = int(col % 3)
return (row,col)
def add_to_board(coords, board):
row = coords[0]
col = coords[1]
board[row][col] = "x"
while True:
print_board(board)
user_input = input("Please enter a position 1-9 or enter \"q\" to quit:")
if quit(user_input): break
if not check_input(user_input):
print("Please try again.")
continue
user_input = int(user_input) - 1
coords = coordinates(user_input)
if istaken(coords,board): <------------
print("Please try again.")
continue
Welcome!
Line 43. You are assigning in your namespace the variable col to reference value [1]. In other words col points to a data structure that is a list with one element: integer 1.
Line 44. You use this list to pass it as an index to the 2D list. Indices for lists have to be integers (aka 0, 1, 2 in your case). Hence, the exception TypeError: list indices must be integers or slices, not list"
What you're looking to do is:
col = coords[1] for line 43
I tested it and it works. However you have other issues you have to debug beyond that point. Good luck! :)
Change
col = [1]
to
col = coords[1]

In Python, iteration doesn't work as I intended [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
i of iteration "for" do not grow. Although the i do not grow, the plain is infinitely adhered to the '#'
program : This is find width and height as close to the square as possible. So If length of string is prime number, string += "#" and re-calculate.
def build_size(plain: str, length: int, length_name: int):
def size_control(plain, length): return plain + "#", length + 1
print(f"length : {length} | length_name {length_name} \n plain : {plain}") #debug
input("continue? : ") #debug
while True:
try:
print(f"plain : {plain}") #debug
aliquot = list()
for i in range(int(length // 2) + 1):
print(f"i : {i}") #debug
if length % i == 0:
aliquot.append(i)
if len(aliquot) < 2 or aliquot[-1] <= length_name: raise NotImplementedError
break
except: plain, length = size_control(plain, length)
return plain, aliquot[-1] , length // aliquot[-1]
if __name__ == "__main__":
name = input("name : ")
plain = input("plain : ")
build_size(plain, len(plain), len(name))
How can I do? Please help me.
I believe the reason i does not grow is that your while loop always raises an error on the first pass of the for loop. So the for loop ends, the while loop advances, and i gets set back to 0.
Speaking of 0, I think that's your problem. When you call range() with only one argument, the starting point defaults to 0, not 1. Anything modulo 0 is undefined, so length % i always throws a ZeroDivisionError, which your bare except: clause always catches.
Edit: To fix this bug, I suggest two things. First, start your range at 1 instead of zero, replacing that line with something like:
for i in range(1, int(length // 2) + 1):
Second, try to avoid bare except: clauses. If you had used except NotImplementedError: instead, then it wouldn't have caught the ZeroDivisionError, and you would have seen the normal error message and been able to figure out the problem much more easily.

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)

If statement syntax error? [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
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:

Categories