简体   繁体   中英

How do I set a limit for a variable in Python?

import random

dealer = random.randint(10, 21)
begin = random.randint(1, 14)
card = random.randint(1, 14)
limit = int(21)
print(begin)
i = input('Hit or Stay?').lower()

while i == "hit":
    begin += random.randint(1, 14)
    print(begin)
    i = input('Hit or Stay?').lower()

if begin == 21:
    print('Wow, you win!')
elif i == "stay":
    if dealer >= begin:
        print('You lose')
        print(dealer)
    else:
        print('You win')
        print(dealer)
elif begin >= limit:
    print('You lose')

I'm currently trying to make a 21 blackjack game(my own twist ofc). However, I've come across a problem. The rules in blackjack is that if your hand goes over the number 21, you lose. I'm having trouble doing that. Currently, python only prints "you lose." when the player goes over the number 21 and then stays his hand: Current Output when Reaching 21/Winning:

Starting Hand: 13
Hit or Stay?hit
Current Hand: 15
Hit or Stay?hit
Current Hand: 21
Hit or Stay?stay
Wow, you win!

Expected Output:

Starting Hand: 13
Hit or Stay?hit
Current Hand: 21 
You Win!!!

Current Output for Going Past 21:

Starting Hand:  4
Hit or Stay?hit
Current Hand:  13
Hit or Stay?hit
Current Hand:  24
Hit or Stay?stay
You lose because you went over 21 haha

Expected Output:

Starting Hand: 20
Hit or Stay?hit
Current Hand: 25
You lose because you went over 21 hahaha

I hope someone will be able to fix my code:<

import random

def check(begin):
    is_end = True
    if begin == 21:
        print('Wow, you win!')
    elif i == "stay":
        if dealer >= begin:
            print('You lose')
            print(dealer)
        else:
            print('You win')
            print(dealer)
    elif begin >= limit:
        print('You lose')
    else:
        is_end=False
    return is_end

dealer = random.randint(10, 21)
begin = random.randint(1, 14)
card = random.randint(1, 14)
limit = int(21)
print(begin)
i = input('Hit or Stay?').lower()

while i == "hit":
    begin += random.randint(1, 14)
    print(begin)
    if check(begin):
        break
    i = input('Hit or Stay?').lower()
import random

dealer = random.randint(10, 21)
begin = random.randint(1, 14)
card = random.randint(1, 14)
limit = int(21)
print(begin)

i = input('Hit or Stay?').lower()

while begin < limit:
    begin += random.randint(1, 14)
    print(begin)
    i = input('Hit or Stay?').lower()

    if begin == limit:
      print('You win')
    else:
      print('You lose')
      break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM