logo
down
shadow

Python making a counter


Python making a counter

By : Henry Mendez
Date : November 22 2020, 03:01 PM
Any of those help I would suggest a simplified "architecture". Your functions to get the user and computer choices should return values that can be compared.
code :
import random

CHOICES = ('rock', 'paper', 'scissors')

def get_user_choice():
    choice = input('Rock, paper, or scissors? ')
    choice = choice.lower().strip()
    if choice not in CHOICES:
        print('Please select one of rock, paper, or scissors')
        choice = get_user_choice()
    return choice

def get_computer_choice():
    return random.choice(CHOICES)

def play_round():
    user_choice = get_user_choice()
    computer_choice = get_computer_choice()
    print('You selected', user_choice)
    print('Computer selected', computer_choice)
    # Compare choices here
    # Return value indicating win, loss, or draw

def play():
    wins = 0
    losses = 0
    draws = 0
    result = play_round()
    # Update wins, losses, or draws according to the result
    # Prompt user to play again or quit
    return wins, losses, draws

if __name__ == '__main__':
    wins, losses, draws = play()
    # Report wins, losses, and draws


Share : facebook icon twitter icon
Making a craps game in python using a counter, but it won't count past 1

Making a craps game in python using a counter, but it won't count past 1


By : suganya narayanan
Date : March 29 2020, 07:55 AM
this one helps. I edited this down. What testCraps(number) does is that it calls a function called quietCraps() that returns a 1 for a win and a 0 for a loss. testCraps(number) is supposed to run quietCraps() a number of times equal to (number), adding 1 to winCoutner if a 1 is returned and adding 1 to lossCounter if a 0 is returned.
code :
for test in range(number): 
    testGame = quietCraps(value1 = 1)
    if str(test) == "1":
        winCounter = winCounter + 1
    elif str(test) == "0":
        lossCounter = lossCounter + 1
def quietCraps():
    crapsTotal = craps(2) 
    return crapsTotal
for test in range(number): 
    testGame = quietCraps(value1 = 1)
    if testGame == 1:
        winCounter = winCounter + 1
    elif testGame == 0:
        lossCounter = lossCounter + 1
if value1 == 1 == True:
Python append Counter to Counter, like Python dictionary update

Python append Counter to Counter, like Python dictionary update


By : Jednoduchy John
Date : March 29 2020, 07:55 AM
With these it helps Counter is a dict subclass, so you can explicitly invoke dict.update (rather than Counter.update) and pass two counters as the arguments:
code :
a = Counter(a=4, b=0, c=1)
b = Counter(z=1, b=2, c=3)

dict.update(a, b)

print(a)
# Counter({'a': 4, 'c': 3, 'b': 2, 'z': 1})
Python Discord ChatBot: Making a mood counter

Python Discord ChatBot: Making a mood counter


By : jaminyah
Date : March 29 2020, 07:55 AM
This might help you I want to make a mood counter for my discord ChatBot. This variable should influence responses to the user. I made two dictionaries in python so far, one called responses and one called insults. The responses are straightforward, with the bot replying if the user sent a message that was in the dictionary. The insult dictionary subtracts a set amount from the variable mood every time you insult the bot. I wrote an if statement trying to subtract the mood by a little bit but whenever I try actually insulting the bot, the bot doesn't say anything to me. Please help. Keep in mind this is not all the code and I am willing to provide a more in-depth explanation as to what problem I have. , Strange code you have, because you set mood=2 all the time in line 4.
code :
@client.event
async def on_message(message) :
    content = message.content.upper()

    mood = 2 # you hard-code your mood here!

    if content in responses: # might enter here

        if mood <= 0: # mood = 2, so won't enter here
            await client.send_message(message.channel, responses[content]["RANG"])

        if mood == 1: # mood = 2, so won't enter here
            await client.send_message(message.channel, responses[content]["ANG"])

        if mood == 2: # mood = 2, so ALWAYS here!
            await client.send_message(message.channel, responses[content]["NEU"])

        if mood == 3: # mood = 2, so won't enter here
            await client.send_message(message.channel, responses[content]["HAP"])

        if mood == 4: # mood = 2, so won't enter here
            await client.send_message(message.channel, responses[content]["RHAP"])

    if content in insults: # might enter here
        mood = mood - 0.25 # mood was 2, not it is 1.75

        if mood <= 0: # mood = 1.75, so won't enter here
            await client.send_message(message.channel, insults[content]["RANG"])

        if mood == 1: # mood = 1.75, so won't enter here
            await client.send_message(message.channel, insults[content]["ANG"])

        if mood == 2: # mood = 1.75, so won't enter here
            await client.send_message(message.channel, insults[content]["NEU"])

        if mood == 3: # mood = 1.75, so won't enter here
            await client.send_message(message.channel, insults[content]["HAP"])

        if mood == 4: # mood = 1.75, so won't enter here
            await client.send_message(message.channel, insults[content]["RHAP"])
    if content in insults: # might enter here
        mood = mood - 0.25 # mood was 2, now it is 1.75

        if mood <= 0: # mood = 1.75, so won't enter here
            await client.send_message(message.channel, insults[content]["RANG"])

        elif mood <= 1: # mood = 1.75, so won't enter here
            await client.send_message(message.channel, insults[content]["ANG"])

        elif mood <= 2: # mood = 1.75, so ENTER HERE
            await client.send_message(message.channel, insults[content]["NEU"])

        elif mood <= 3: # elif, so skipped
            await client.send_message(message.channel, insults[content]["HAP"])

        elif mood <= 4: # elif, so skipped
            await client.send_message(message.channel, insults[content]["RHAP"])
mood = 2
@client.event
async def on_message(message) :
    content = message.content.upper()

    global mood

    if content in responses:
        .
        .
        .
Accumulating collections Counter in Python becomes slower as accumulated counter increases in size

Accumulating collections Counter in Python becomes slower as accumulated counter increases in size


By : mohammad tabatabaey
Date : March 29 2020, 07:55 AM
To fix this issue Counter.__iadd__ includes a linear scan of the self Counter to remove items with nonpositive counts. From cpython/blob/master/Lib/collections/__init__.py
code :
def _keep_positive(self):
    '''Internal method to strip elements with a negative or zero count'''
    nonpositive = [elem for elem, count in self.items() if not count > 0]
    for elem in nonpositive:
        del self[elem]
    return self

def __iadd__(self, other):
    '''Inplace add from another counter, keeping only positive counts.
    >>> c = Counter('abbb')
    >>> c += Counter('bcc')
    >>> c
    Counter({'b': 4, 'c': 2, 'a': 1})
    '''
    for elem, count in other.items():
        self[elem] += count
    return self._keep_positive()
# Instead of cnt += Counter(...)
cnt.update(Counter(txt_f.read().lower().replace('\n', ' ').split(' ')))
cnt.update(txt_f.read().lower().replace('\n', ' ').split(' '))
Making a counter bot with Discord.py rewrite- local variable 'counter' referenced before assignment error

Making a counter bot with Discord.py rewrite- local variable 'counter' referenced before assignment error


By : user2314364
Date : March 29 2020, 07:55 AM
this will help I am attempting to make a counter in a discord bot that takes a number from the user and adds it to the current total. However I get either a " local variable 'counter' referenced before assignment" error or a "name counter is not defined" error. , In variation 2 you have to define counter:
code :
counter = 0

@bot.command()
async def bid(ctx,number):
    global counter
    counter += 1
    print(str(counter)) 
Related Posts Related Posts :
  • How to use an API that requires user's entry (Sentiment Analysis)
  • Django first app
  • Why is this regex code not working
  • Beautifulsoup - findAll not finding string when link is also in container
  • Python: any() to check if attribute in List of Objects matches a list
  • How do I "enrich" every record in a Pandas dataframe with an hour column?
  • Failing to open an Excel file with Python
  • Python function to modify string
  • Pandas DataFrame seems not to have "factorize" method
  • Row column operations in CSV
  • How to decrypt RSA encrypted file (via PHP and OpenSSL) with pyopenssl?
  • How can we use pandas to generate min, max, mean, median, ...as new columns for the dataframe?
  • Cython: creating an array throws "not allowed in a constant expression"
  • Different thing is shown in html
  • sublimetext3 event for program exit
  • Join contigous tokens if the token includes "@" char
  • transparent background in gif using Python Imageio
  • Enable autologin into flask app using active directory
  • Make a NxN array of 1x3 arrays of random numbers (python)
  • django how to use Max and Count on the same field in back-to-back annotations
  • Using the OR operator seems to only take the first of two conditions when used with np.where filter
  • Elegant Dataframe Operations in Pandas
  • Change metadata of pdf file with pypdf2
  • How can I animate a set of points with matplotlib?
  • error: (-215) count >= 0 && (depth == CV_32F || depth == CV_32S) in function arcLength
  • OpenStack KeyStone SSL Exception When Creating an Instance of KeyStone
  • pyspark: The system cannot find the path specified
  • How can I set path to load data from CSV file into PostgreSQL database in Docker container?
  • Summation in python dictionary
  • DRF 3.7.0 removed handling None in fields and broke my foreign key source fields. Is there a way around it?
  • Error with Padlen in signal.filtfilt in Python
  • Abstract matrix multiplication with variables
  • Reading binary data on bit level
  • How to replace multiple instances of a sub strings in a string using a for loop (in a function)?
  • py2neo cypher create several relations to central node in for loop
  • [python-3]TypeError: must be str, not int
  • How to exit/terminate a job earlier and handle the raised exception in apscheduler?
  • python, print intermediate values while loop
  • python to loop over yaml config
  • D3.js is not recognized by PyCharm
  • Access the regularization paths obtained from ElasticNetCV in sklearn
  • Pattern table to Pandas DataFrame
  • Get the earliest date from a column (Python Pandas) after csv.reader
  • Get SystemError: Parent module '' not loaded, cannot perform relative import when trying to import numpy in a Cython Ext
  • Bash or Python : Append and prepend a string recursively in all .tex files
  • Changing a certain index of boolean list of lists change others, too
  • complex dataframe filtering request on the last occurence of a value in Panda/Python [EDIT]
  • How to repeatedly get the contents of a Text widget every loop with tkinter?
  • How to call the tornado.queues message externally
  • How can I use regex in python so that characters not included are disallowed?
  • Discarding randmly scattered empty spaces in pandas data frame
  • Get sums grouped by date by same column filtered by 2 conditions
  • Element disappears when I add an {% include %} tag inside my for loop
  • Django Rest Framework with either a slug or a pk lookup field for the DetailAPIView
  • Flask doesn't stream on Lambda
  • Generate all permutations of fixed length where the elements come from two different sets
  • Making function for calculating distance
  • How to handle multiprocessing based on the limit of CPU's
  • Django - static files is not working
  • Remove x axis and y axis black lines with matplotlib
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org