1

I´m still new to python and trying to convert a string user input to an integer. My code looks like that:

var_input = input("Please input XX for a or YY for b:")

while True:
    
    try:
        
        if var_input == "XX":
            var_v = 1
            
        elif var_input == "YY":
            var_v = 0
        
        break;
    except ValueError:
        print("Invalid Input")

I´m always ending up with var_v = 0

I´m sure there is a really simple way but i don´t get there.

Thankful for any help!

  • What input do you type? – Guimoute Jul 24 '21 at 10:56
  • i type two inputs like "GG" for "XX" or "PP" for "YY" – stickfrosch95 Jul 24 '21 at 10:58
  • It is not ```break;```. It is ```break``` –  Jul 24 '21 at 10:59
  • I can get `var_v = 1` when I enter `XX`. – quamrana Jul 24 '21 at 10:59
  • What is `"GG"` or `"PP"`? You didn't mention that in your post. – quamrana Jul 24 '21 at 10:59
  • ```ValueError``` won't be raised on entering wrong input –  Jul 24 '21 at 11:01
  • GG und PP are just example strings. I want to input two different strings and if the input is not one of these strings i want to get into the exception. – stickfrosch95 Jul 24 '21 at 11:04
  • Wait, is the question about the value stored in `var_v` or about raising an exception? – quamrana Jul 24 '21 at 11:05
  • I try it again to explain: There are two correct string user inputs. The first is for example "girl" and the second is "boy". Now if the user types "girl" in the input, the variable var_v should store the integer = 1 and if the user types "boy" the variable var_v should store the integer = 0. Everything else should end in the exception with a print("Invalid input") – stickfrosch95 Jul 24 '21 at 11:09
  • Do you really need to have an exception? Could you instead just have the `print("Invalid input")`? – quamrana Jul 24 '21 at 11:11
  • I need that if the input is not correct the user should have the option to do the input again – stickfrosch95 Jul 24 '21 at 11:14
  • Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – quamrana Jul 24 '21 at 11:15
  • Not really because i have to check the if statements before the exception – stickfrosch95 Jul 24 '21 at 11:21

1 Answers1

0

I can change your code like this:

while True:
    var_input = input("Please input XX for a or YY for b:")

    if var_input == "XX":
        var_v = 1
        
    elif var_input == "YY":
        var_v = 0
    else:
        print("Invalid Input")
        continue
    break

print(var_v)
print('Done')

I think this is what you want, but I don't see how it is different to the duplicate.

quamrana
  • 37,849
  • 12
  • 53
  • 71