I'm having trouble with input() in a project

I’m making a blackjack program and I’m trying to get my code to deal with an empty input string.

 def hit_me(self):
        self.stand = False
        while self.score < 21 and self.stand == False:
            self.hit = input("Hit or Stand?").lower()
            if self.hit[0] == "h":
                self.player_cards.append([random.choice(cards), random.choice(suit)])
                self.scoring()
                print(self.player_cards, self.score)
            elif self.hit[0] == "s":
                self.stand = True

This returns an index error, I tried adding to the string self.hit = input("Hit or Stand?").lower() + "fail"
I tried a try: statement around my input and the if statements
All I ever get is an IndexError when I don’t enter a letter.

When you utilised a try block, how did you structure it?

def hit_me(self):
        self.stand = False
        while self.score < 21 and self.stand == False:
            self.hit = input("Hit or Stand?").lower()
            try:
                if self.hit[0] == "h":
                    self.player_cards.append([random.choice(cards), random.choice(suit)])
                    self.scoring()
                    print(self.player_cards, self.score)
                elif self.hit[0] == "s":
                    self.stand = True
            except IndexError:
                break

I think that’s what I did, I kept working on it and changed the while if elif statements if len(self.hit) > 0 and self.hit[0] == "h":
I expected that try statement to work though

After using the try block, what is the exact error thrown? Can you post it, please?

1 Like

I wonder, is a try/except needed? You could use an if on self.hit before looking at an index:

if self.hit:
  #code here

An empty string has a boolean value of False, so this would ensure it contains at least the first index.

1 Like

It seems to work fine now, I think I wasn’t saving my code before running it. I’m using the visual studio code program and I was editing code then using up in the built in terminal to try again rather than the play button up top. I guess I just needed to sleep on it, but thanks for the help anyways!