[Tutor] Python help
Steven D'Aprano
steve at pearwood.info
Mon Apr 2 19:56:03 EDT 2018
On Mon, Apr 02, 2018 at 11:44:39PM +0100, Shannon Evans via Tutor wrote:
> Hi, I am trying to write a code with if statements but the code keeps just
> repeating and not carrying on.
> I am trying to get user to input a grade, either A, B, C, D, E or F and
> trying to have an error message if anything but these values are inputted.
> This is what i've wrote so far:
>
> while True:
> try:
> Grade = int(raw_input("Please enter your Grade: "))
Here you convert the user's input into an integer, a number such as 1,
2, 57, 92746 etc. If that *fails*, you run this block:
> except ValueError:
> print("Error, Please enter A, B, C, D, E or F")
> continue
and start again.
If it succeeds, because the user entered (let's say) 99, then you run
another test:
> if Grade <> 'A','B','C','D','E','F':
> print ("Error, Please enter A, B, C, D, E or F")
> continue
That will ALWAYS fail, because you are trying to compare the integer 99
(for example) with the tuple of six characters:
99 <> ('A', 'B','C','D','E','F')
which is always false. So that block will ALWAYS fail, and you always go
back to the start.
--
Steve
More information about the Tutor
mailing list