Question

In: Computer Science

Trying to score a hand of blackjack in this python code but my loop is consistently...

Trying to score a hand of blackjack in this python code but my loop is consistently outputting (13,1) which makes me think that something is wrong with my loop.

Could someone help me with this code?:

import random

cards = [random.randint(1,13) for i in range(0,2)]
#initialize hand with two random cards
def get_card():
#this function will randomly return a card with the value between 1 and 13
return random.randint(1,13)

def score(cards):
stand_on_value = 0
soft_ace = 0

for i in range(len(cards)):
if i == 1:
stand_on_value += 11
soft_ace = 1
# i += 1

if i < 10:
stand_on_value += i
if i >= 10 and i != 1:
stand_on_value += 10
else:
if i == 1:
stand_on_value += 1
return (stand_on_value, soft_ace)

if sum(cards) < 17:
stand_on_soft = False
elif sum(cards) >= 17:
stand_on_soft = True


print(score(cards))

Solutions

Expert Solution

"In for loop of score function" Instead of "i" you have to use "cards[i]

In your code the value of i will either be 0 or 1 [ Nothing else ] So, the output is the same each and every time

you have used random for generating random " cards[i] " [ & not "i" ]

One more error which I think is, You haven't used "stand_on_soft" anywhere in the code. So, what's the meaning of assigning true or false to it???

import random

cards = [random.randint(1, 13) for i in range(0, 2)]

# initialize hand with two random cards

def get_card():

    # this function will randomly return a card with the value between 1 and 13

    return random.randint(1, 13)

def score(cards):

    stand_on_value = 0

    soft_ace = 0

    for i in range(0,len(cards)):

        if cards[i] == 1:

            stand_on_value += 11

            soft_ace = 1

        if cards[i] < 10:

            stand_on_value += i

        if cards[i] >= 10 and i != 1:

            stand_on_value += 10

        else:

            if i == 1:

                stand_on_value += 1

    return (stand_on_value, soft_ace)

if sum(cards) < 17:

    stand_on_soft = False

elif sum(cards) >= 17:

    stand_on_soft = True

print(score(cards))

#PLEASE LIKE IT RAISE YOUR THUMBS UP
#IF YOU ARE HAVING ANY DOUBT FEEL FREE TO ASK IN COMMENT SECTION


Related Solutions

This is my code for python. I am trying to do the fourth command in the...
This is my code for python. I am trying to do the fourth command in the menu which is to add an employee to directory with a new phone number. but I keep getting error saying , "TypeError: unsupported operand type(s) for +: 'dict' and 'dict". Below is my code. What am I doing wrong? from Lab_6.Employee import * def file_to_directory(File): myDirectory={}       with open(File,'r') as f: data=f.read().split('\n')    x=(len(data)) myDirectory = {} for line in range(0,199):      ...
Working with Python. I am trying to make my code go through each subject in my...
Working with Python. I am trying to make my code go through each subject in my sample size and request something about it. For example, I have my code request from the user to input a sample size N. If I said sample size was 5 for example, I want the code to ask the user the following: "Enter age of subject 1" "Enter age of subject 2" "Enter age of subject 3" "Enter age of subject 4" "Enter age...
Write a python code which prints triangle of stars using a loop ( for loop )...
Write a python code which prints triangle of stars using a loop ( for loop ) Remember what 5 * "*" does The number of lines of output should be determined by the user. For example, if the user enters 3, your output should be: * ** *** If the user enters 6, the output should be: * ** *** **** ***** ****** You do NOT need to check for valid input in this program. You may assume the user...
What's wrong with my Python code. We have to find the regularexpression in Python My output...
What's wrong with my Python code. We have to find the regularexpression in Python My output should look like this My IP address 128. 0. 0. 1 My IP address 53. 20. 62. 201 My code ipAddresses = [] ipRegEx = re.compile(r"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}")    result = myRegEx.find all(Search Text)    def Regular_expression(ipAddresses)       for i in ipAddresses:          print(i) ipSearchResult = ipRegEx.search(line)    if ipSearchResult != None and ipSearchResult.group() not in ipAddresses:       ipAddresses.append(ipSearchResult.group()) we have to use loop too.
Code in python Write a while loop code where it always starts form 2. Then it...
Code in python Write a while loop code where it always starts form 2. Then it randomly chooses a number from 1-4. If the number 4 is hit then it will write “TP” if the number 1 is hit then it will write”SL”. It will rerun the program every time the numbers 1 and 5 are hit. The code should also output every single number that is randomly chosen. 2 of the same numbers can't be chosen back to back...
javascript BlackJack i made a blackjack game, the code is below //this method will return a...
javascript BlackJack i made a blackjack game, the code is below //this method will return a shuffled deck function shuffleDeck() { //this will store array fo 52 objects const decks = [] const suits = ['Hearts', 'Clubs', 'Diamonds', 'Spades'] const values = ['Ace', 'King', 'Queen', 'Jack', 'Ten', 'Nine', 'Eight', 'Seven', 'Six', 'Five', 'Four', 'Three', 'Two', 'One'] //run a loop till 52 times for (let i = 0; i < 52; i++) { //push a random item decks.push({ suit: suits[Math.floor(Math.random() *...
Python I want to name my hero and my alien in my code how do I...
Python I want to name my hero and my alien in my code how do I do that: Keep in mind I don't want to change my code except to give the hero and alien a name import random class Hero:     def __init__(self,ammo,health):         self.ammo=ammo         self.health=health     def blast(self):         print("The Hero blasts an Alien!")         if self.ammo>0:             self.ammo-=1             return True         else:             print("Oh no! Hero is out of ammo.")             return False     def...
JAVA: This is my code, but when it runs, for the "Average Score" output, it only...
JAVA: This is my code, but when it runs, for the "Average Score" output, it only gives me NaN. How can I fix that? import java.util.Scanner; public class prog4 { public static void main(String[] args) { Scanner reader = new Scanner(System.in); String name; double score; double minScore = 0; double maxScore = 0; int numberOfRecords = 0; double sum = 0; double average = sum / numberOfRecords; System.out.printf("%-15s %-15s %-15s\n", "Student#", "Name", "Score");           while (reader.hasNext()) { name...
Create a python code that calculates fixed point iteration method using a for loop.
Create a python code that calculates fixed point iteration method using a for loop.
Complete the following in syntactically correct Python code. Write a program, using a for loop, that...
Complete the following in syntactically correct Python code. Write a program, using a for loop, that calculates the amount of money a person would earn over a period of time if his or her salary is 1 penny for the first day, 2 pennies for the second day, 4 pennies for the third day, and continues to double each day. 1.      The program should ask the user for the number of days the employee worked. 2.      Display a table showing the salary...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT