Best Python code snippet using ATX
guessing_game.py
Source:guessing_game.py  
...22                raise ValueError23        except ValueError: 24            print("Invalid input. Please enter a whole number.")25            return self.validate_input() # Function is called as many times as is necessary to obtain valid input.26    def select_bounds(self):27        """Enables a player to select lower and upper bounds to guess between."""28        print("Select a lower bound:")29        lower = self.validate_input() 30        print("Select an upper bound:")31        upper = self.validate_input() 32        while lower >= upper: 33            print("The upper bound must be greater than the lower bound. Please enter different bounds.\n")34            print("Select a lower bound:")35            lower = self.validate_input()36            print("Select an upper bound:")37            upper = self.validate_input()38        39        return (lower, upper)40    def select_attempt_number(self, range):41        """Allows the player to select the number of guesses they can have."""42        self.range = range43        print("How many guesses would you like to have?")44        attempts = self.validate_input()45        while attempts < 1 or attempts > self.range:46            if attempts < 1:47                print("You need to have at least 1 guess.")48            elif attempts > self.range:49                print("You cannot have more guesses than possible numbers!") 50            print("Please select a different number of guesses.\n")51            attempts = self.validate_input()52        53        return attempts54    def guess_the_number(self, lower, upper):55        """Allows the player to guess a number in the range until they guess correctly or run out of guesses."""56        self.lower = lower57        self.upper = upper58        59        range = self.upper - self.lower + 1 # Possible numbers that can be guessed.60        attempts = self.select_attempt_number(range) # Player can guess how many guess attempts they would like61        answer = randint(self.lower, self.upper) # Computer chooses random number in the range for the player to guess62        attempt_counter = 063        while attempt_counter < attempts: # The player has not used up all their guesses64            print("Guess a number:")65            guess = self.validate_input()66            if guess < self.lower or guess > self.upper:67                print(f"Please guess a number between {lower} and {upper}!")68            else:69                attempt_counter += 1 # Increment guesses used each time a valid guess is made70                if guess == answer:71                    print("Congratulations! You guessed correctly!\n")72                    break73                else:74                    # Display a helpful message to the player to guide their next guess:75                    direction = "high" if guess > answer else "low"76                    print(f"Incorrect: too {direction}!")77                    remaining = attempts - attempt_counter 78                    if attempts > 1 and attempt_counter != attempts:79                        plural_att = "es" * (attempt_counter > 1) #Plural "es" suffix if the user has made more than one guess.80                        plural_rem = "es" * (remaining == 0 or remaining > 1) #Plural "es" suffix if the user has more than one guess or no guesses left.81                        print(f"You have used {attempt_counter} guess{plural_att}. You have {remaining} guess{plural_rem} remaining.") #Ensures a grammatically correct message.82        if guess != answer and attempt_counter == attempts:           83            print(f"You have used up all your guesses! The correct answer was {answer}.\n") 84    def play_again_or_not(self):85        """Allows the player to decide whether or not they want to play the game again."""86        print("You have finished playing the guessing game.")87        again = input("Would you like to play again?").lower() #Allows case-insensitivity.88        while again != "yes" and again != "no":89            print("Invalid response. Please answer either 'yes' or 'no'.")90            again = input("Would you like to play again?").lower()91        92        return again93if __name__ == "__main__":94    95    new_player = Guessing_Game()96    new_player.show_instructions()97    while True:98        bounds = new_player.select_bounds() # The bounds between which the player is guessing a number.99        lower = bounds[0]100        upper = bounds[1]101        new_player.guess_the_number(lower, upper) # Player tries to guess the number chosen by the computer between the bounds.102        again = new_player.play_again_or_not()103        if again == "no":...cmdloop.py
Source:cmdloop.py  
1# -*- coding: utf-8 -*-2"""3Created on Sat Mar 13 18:11:29 202145@author: Domokos Zoltán6"""78import copy as cp910import view as vw11from equirep import Table121314#Exception for command errors15class InvalidCommand(Exception):1617    pass181920class InvalidTableArgs(Exception):2122    pass232425class CmdLoop:26    27    def __init__(self, table, src_list, dst_list, dims_list, inds):28        29        self.table = table30        31        self.model_signal = self.table.base_signal(src_list, dst_list, dims_list, inds)32        33        self.view_signal = self.table.base_signal(src_list, dst_list, dims_list, inds)3435        #TODO: remove this deprecated class and replace it with final sol.36        self.table_cmd_proc = DmDef() 3738        return39    40    41    def set_table(self, table, src_list, dst_list, dims_list, inds):42        43        self.table = table44        45        self.model_signal = table.base_signal(src_list, dst_list, dims_list, inds)46        47        self.view_signal = table.base_signal(src_list, dst_list, dims_list, inds)48        49        return50    51    52    #TODO: remove this deprecated arg. list and replace it with final sol.53    def table_update(self, val, cmd_new, cmd_fix):54        55        self.table_cmd_proc.set_cmd(self.table, val, cmd_new, cmd_fix)56        57        return58        59    60    def set_model(self, model_signal = None, src_list = None, dst_list = None, dims_list = None, inds = None):61        62        if model_signal is None:63        64            self.model_signal = self.table.base_signal(src_list, dst_list, dims_list, inds)65            66        self.model_signal = self.table.base_change_fc(src_list, 67                                                      dst_list, 68                                                      dims_list, 69                                                      model_signal,70                                                      md = 'fc_fc')71            72        self.view_signal = self.model_signal73        74    75    76    def model_update(self, src_list, dst_list, dims_list):77        #TODO: add condition to select uniform or non-uniform versions78        self.model_signal = self.table.base_change_fc(src_list, 79                                                      dst_list, 80                                                      dims_list, 81                                                      self.model_signal,82                                                      md = 'fc_fc')83        84        self.view_signal = self.model_signal85        86        return87    88    89    def view_update(self, incr, select_bounds, did):90        91        self.view_signal.set_curr(incr, select_bounds, did)92        93        return94    95    96    def show_view(self, seldims, fix_inds, mode = 'surf'):97        98        if 'heat' == mode: 99        100            vw.plot_heatmap2(self.view_signal, seldims, fix_inds)101            102        else:103            104            vw.plot_sigfc2(self.view_signal, seldims, fix_inds)105        106        return107108109    def cmd_loop(self):110        111        #TODO: parse user requests and do what is needed112        113        return114    115116#TODO: review and remove these deprecated classes117class DmDef:    118        119    def __init__(self):120        pass121        122    123    def cmdproc_depr(self, cmd_new, cmd_fix):124        #check the commands125        cmd = None126        cmd_set = {'t', 'f', 'n'}127        128        if (cmd_new is None) or (cmd_fix is None):129            130            raise(InvalidCommand)131        132        elif (cmd_new not in cmd_set) or (cmd_fix not in cmd_set) :133            134            raise(InvalidCommand)135        136        elif cmd_new == cmd_fix:137            138            raise(InvalidCommand)139        140        else:141                #here we have a proper command for sure142                cmd = {'src' : cmd_new, 143                       'fix' : cmd_fix}144                145                for elm in cmd_set:146                    147                    if elm not in cmd.values():148                        149                        cmd['dst'] = elm150                        151                        break 152            153        return cmd154            155    156    def set_cmd(self, table, val, cmd_new, cmd_fix):157        158        159        160        if isinstance(table, Table):161        162            newtable = cp.deepcopy(table)163            cmd = self.cmdproc_depr(cmd_new, cmd_fix)164            newtable.update(val, 0, cmd, True)165        166        else:167            #TODO: raise exception168            pass169        170        return newtable #cp.deepcopy(newtable)171    
...select.py
Source:select.py  
...13    # Detect bounds URL14    stac_bounds_url = []15    for i in range(len(input.stac_ppu.url)):16        url_date_tmp1 = get_all_children(input._session, "child", input.stac_ppu.url[i][0], input.stac_ppu.json[i][0])17        url_date_tmp2 = select_bounds(input._session,url_date_tmp1, bbox, input.proj_params)18        if len(url_date_tmp2) != 0:19            stac_bounds_url.append(url_date_tmp2)2021    # Output22    return stac_bounds_url2324#--------------------------------------------------------------------------------25# select_bounds ï¼ 26#--------------------------------------------------------------------------------27def select_bounds(session,URL,bbox,proj_params):2829    # Detect each COG's lon range30    lonall = [url2lon(URL[i],proj_params) for i in range(len(URL))]3132    # Select child All33    decimals = proj_params.r_dec_pix34    idx = intersect_line(bbox[0::2],lonall,decimals)3536    # Update URL37    url_tmp0 = np.array(URL)[idx]3839    # Check url_tmp040    if len(url_tmp0) == 0:41        return []
...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
