I want to change the baseball game to a function, is there any other way to use global?

Asked 1 years ago, Updated 1 years ago, 108 views

Below is a baseball game that I have made

import random                           

answer = random.sample(range(1,10),3)    

tr_num = 0 # Variable indicating how many attempts have been made
variable representing the number of st_num = 0 #strike
variable representing the number of bl_num = 0 # balls

print ("Start the game".")
while(st_num < 3):                  
    num = (input ("Enter a number")  
    if(num[0] == num[1] == num[2]):                 
        print("Duplicated numbers". Please re-enter it.")  
        continue
    elif(num[0] == num[1]):
        print("Duplicated numbers". Please re-enter.")
        continue
    elif(num[0] == num[2]):
        print("Duplicated numbers". Please re-enter.")
        continue
    elif(num[1] == num[2]):
        print("Duplicated numbers". Please re-enter.")
        continue
    else:                                           
        pass
    st_num = 0                   
    bl_num = 0

    for i in range(0,3):       
        for j in range(0,3):    
            if(num[i] == str(answer[j]) and i == j):
                st_num += 1               
            elif(num[i] == str(answer[j]) and i != j):
                bl_num += 1    
    print(st_num, "strike", bl_num, "ball")
    tr_num += 1             
print(tr_num,"You succeeded in your first try.")   

Here! (1)It's the part that determines if the same number exists in a three-digit number (2)You want to replace the part that compares the number you enter with the correct answer with a function.

The way I solved (1) is

def same_num():
    global result
    if (num[0] == num[1] == num[2]) or (num[0] == num[1]) or (num[0] == num[2]) or (num[1] == num[2]):
        result = False
    else:
        result = True

In this way, (1) tried to solve by creating a condition (result variable) that indicates the result of determining whether there is the same number.

If there is a duplicate number, the condition result is received as False, and if result = False is continued in the while statement outside the if result F False plane, so that the user receives the number again.

However, as you know, we set result = True outside the function, so no matter how much the result is false or true, the result was not assigned, so we ended up using global to connect it to the external result variable.

By the way, coding using global is very bad coding and should be avoided... Is there any way to solve this problem without using global?

(2) I can't even think of an idea to change the part that compares the number and the answer to a function.

python function global baseball-game

2022-09-22 19:16

1 Answers

Instead of using the global variable, the same_num function should return true/false.


def same_num(num):
    if (num[0] == num[1] == num[2]) or (num[0] == num[1]) or (num[0] == num[2]) or (num[1] == num[2]):
        return True
    else:
        return False   

# ...

while(st_num < 3):                  
    num = (input ("Enter a number")  
    if same_num(num):
        print("Duplicated numbers". Please re-enter.")
        continue

# ...

Like this. There are improvements to the same_num function.

Use len(set(num)) == len(num) to see if there is a duplication in the input value. The set function eliminates redundancy in the useful (such as a list or string of connected data types).

Also, it would be nice if there was a logic to check if only three numbers were entered, right?

ex)

import random


def same_num(nums):
    return not (len(set(nums)) == len(nums) == 3)


answer = random.sample(range(1, 10), 3)

tr_num = 0 # Variable indicating how many attempts have been made
variable representing the number of st_num = 0 #strike
variable representing the number of bl_num = 0 # balls

print ("Start the game".")
while (st_num < 3):
    num = (input ("Enter a number")
    if same_num(num):
        print("Duplicated numbers". Please re-enter.")
        continue
    st_num = 0
    bl_num = 0

    for i in range(0, 3):
        for j in range(0, 3):
            if (num[i] == str(answer[j]) and i == j):
                st_num += 1
            elif (num[i] == str(answer[j]) and i != j):
                bl_num += 1
    print(st_num, "strike", bl_num, "ball")
    tr_num += 1
print(tr_num), "You succeeded in your first attempt.")


2022-09-22 19:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.