0
The problem is on line 94, the loop should break when the user puts in ânâ or âNâ but the loop continues, why and how to fix it?
7 Respostas
+ 2
Lenoname
I think I know what's wrong.
in line 92 onwards, use:
if o=='y' or o=='Y':
pass
elif o == 'n' or o == 'N' :
break
if o == 'y' or 'Y': is wrong.
+ 4
The problem is that:
if o == 'y' or 'Y'
is always true. The part after 'or' is not compared to 'o' - you just compare 'o' to 'y', then OR it to 'Y'. A non-empty string is true.
For you to compare the variable to both values, you should be explicit:
if o == 'y' or o == 'Y'
+ 2
the code is a bit hard to follow, but one thing I could suggest is not to convert the input to int. The program will throw an error if the user inputs n or N. Keep the choices as string and alter the conditions to compare with strings.
change: i = int(input())
to: i = input()
and the conditions to:
if i == "1":
...
elif i == "2":
...
also add default condtions if the user does not input anything at all.
+ 2
Lenoname
better change them anywhere you input a choice. Non-numeric inputs that cannot be converted to int will give you errors.
+ 2
Lenoname ,
in general it would be better to have the control for upper or lower case direct with input:
# instead of using this...:
...
o = input('y for yes and n for no!: ')
if o == 'y' or 'Y' :
pass
elif o == 'n' or 'N' :
pass
...
# it is better to do this...:
...
o = input('y for yes and n for no!: ').lower()
print("input was:", o)
if o == 'y':
pass
elif o == 'n':
pass
...
+ 1
if input("enter a letter").lower() != "n":
#if the lowercase value of input is not "n" run this code.
print("not an n.")
else:
#if the lowercase value of input is "n", run this code.
print("it was an n")
Doing something like the above would make it so that the only time the code doesn't run is if the user enters N or n. No variable is assigned, which helps with memory management and won't use a variable name that might be used elsewhere. However, this isn't really a loop. This will only run one time, and then continue on. If statements will evaluate to true or false, then move along.
If you need a loop that will run forever until the N is pressed, let's make a real loop below.
while input("enter a letter").lower() != "n":
#run this code forever until n is pressed
print("not an n")
0
Bob_Li u mean line 76 and on?