logo
Tags down

shadow

Python guessing game (need help getting closest number)


By : Asmat Mahmud
Date : October 16 2020, 06:10 PM
may help you . im trying to have 2 players, both guesses a number between 1-10. script generates a random number from 1-10 and both users guess and i need a algorithm that says which player was the closest to the guess
code :
import random

value = random.choice(range(1,11))

distance = {}

for player in ['p1', 'p2']:
    distance[player] = abs(int(input(player + ' bet:')) - value)

print('Winner: {}'.format(min(distance, key=distance.get)))


Share : facebook icon twitter icon

Number Guessing Game in Python


By : doushichao
Date : March 29 2020, 07:55 AM
This might help you The biggest problem is that you're not saving the conversion to int so you're using the guess as the string the user entered. You need to save it by doing user = int(raw_input('>>>'))
There are other ways you can improve this code, however. You repeat yourself a bit, and you don't need random.choice, you can use random.randrange(1, 10)
code :
import random

def get_user_num(msg='>>> '): 
    """Print the msg parameter as a prompt for the user to enter a number.  If
    they enter an invalid string, reprompt them until they enter a number.

    """
    while True: 
        try: 
            return int(raw_input(msg)) # save the conversion to int
        except ValueError: # only except the error you're actually looking for
            print 'Numbers Only!' 

# 'from 1-9' is probably better than 'between 1-10'
user = get_user_num('Guess The Number\n Pick from 1-9\n>>> ') 
number = random.randrange(1, 10) # <- numbers list is unnecessary
#int(number) # this conversion was never needed, it was already a number

for _ in range(4):  # you don't need (0, 4), 0 is assumed 
    if number == user:
        print 'You Won!' # the correct number has been guessed
        break # exit the loop once the number has been correctly guessed
    elif user > number:
        print 'The number is less than', user
    elif user < number:
        print 'The number is bigger than', user

    # Don't repeat yourself, put this outside the `if`s
    user = get_user_num()
else:
    #only print the answer when it wasn't guessed correctly
    print "The Number was", number

Python - Random number guessing game - Telling user they are close to guessing the number


By : Garbes
Date : March 29 2020, 07:55 AM
Does that help I am going to start by saying my python is rusty and someone please fix it if im off alittle.
All you need to do if use an if statement.
code :
random = 5
guess = 3
if( guess == random ):
    print('your right!')
elif ( abs (guess - random) <= 2 ):
    print('you are close to guessing the number!')
else:
    print('you are not close enough!')

Simple guessing game that allows user to play again after correctly guessing the random number?


By : Splixz
Date : March 29 2020, 07:55 AM
wish helps you since my english is not good, i will give you the code ( modifed from yours).
code :
    #include<stdio.h>
    #include<stdio.h>
    #include<stdlib.h>
    #include<math.h>
    #include<time.h>

    int random_num;

    int guessGame(int guessed_num) {


        if (guessed_num == random_num) {
           printf("Correct! That's the number.\n");
           return 1;
        } else if (guessed_num < random_num) {
              printf("Too low. Guess again.\n");
              return 0;
           } else {
              printf("Too high. Guess again.\n");
             return 0;
        }
    }

    int main() {
    char loop;
    while (1) {
    int guessed_num = 0;
    srand(time(NULL));
    random_num = rand() % 50 + 1;
    printf("I have a number between 1-50.\n");
    printf("Can you guess what it is?\n");
    printf("Enter your initial guess.\n");
    while (1) {
        scanf("%d", &guessed_num);
        int returnValue = guessGame(guessed_num);
        if (returnValue == 1) {
            break;
        }
    }
    printf("You wanna do it again? ");
    getchar();
    scanf("%c", &loop);
    if (loop == 'n') {
        break;
    }
}
return 0;
} 

Number Guessing Game (Python)


By : Artobstrel
Date : March 29 2020, 07:55 AM
should help you out You could set 'userNum' to be 0, and encase all the input in a while loop:
code :
userNum = 0

while (userNum != number):
import random

def main():

    # initialization
    high = 0
    low = 0
    win = 0
    number = random.randint(1, 100)
    userNum = 0

    while (userNum != number):
        # input
        userNum = int(input("Please guess a number between 1 and 100: "))

        # if/else check
        if userNum > number:
            message = "Too high, try again."
            high += 1
        elif userNum == number:


        message = "You got it correct! Congratulations!"
        win += 1
        else:
            message = "Too low, try again."
            low += 1
    print()
    print(message)

    # loop
   # while message != "You got it correct! Congratulations!":

    # display total
    print()
    print("Number of times too high: ", high)
    print("Number of times too low: ", low)
    print("Total number of guesses: ", (high + low + win))


    print("You win")

main()

My Python number guessing game


By : user307757
Date : March 29 2020, 07:55 AM
like below fixes the issue Since you have number2 = int(randint(1,99)) inside your while cycle, then you create a new number each time. Put that line outside the while and the number will remain the same until someone guesses it
Related Posts Related Posts :
  • RegEx for matching specific element of HTML
  • How to initiate widgets through tk/tcl
  • urlparse does not raise exception for an invalid url
  • plot stacked percentage barchart matplotlib
  • How to have the .isupper() and .islower() methods in one line of code?
  • Removing header index from dataframe
  • how to input all data first, then give all output in python?
  • Hot to fix Tensorflow model not running in Eager mode with .fit()?
  • Proxy configuration in Scrapy
  • If/else statement within loop over dataframe
  • I have a code or stop the loop, I do not know how I can do for what stops
  • python pandas : lambda or other method to count NaN values / len(value)<1 along rows
  • Combine two dataframes with same values in several columns
  • Replace Iterations by elegant Pandas code
  • If all elements match requirement not using "if all"
  • Access to 3D array in fragment shader
  • How to normalize the columns of a DataFrame using sklearn.preprocessing.normalize?
  • Validation loss not moving with MLP in Regression
  • ML with imbalanced binary dataset
  • Is there a way to iterate through s3 object content using a SQL expression?
  • Appending lists to a result list keeps replacing the last one appended
  • How can I reuse a function to order different attributes of an object
  • Finding an integer in a list of integers if condition fulfilled
  • Python: Replacing character in for loop
  • Why can I run this command from the terminal but I get an error when my python runs it from the terminal for me?
  • How to create a conda environment from global python environment?
  • PyGame MOUSEBUTTONDOWN event not registering?
  • Pandas - Replace values in column with other values from the same column
  • Why this statement is evaluated to False even it is true?
  • Return an element based on another element in a nested list in python
  • Error ::: ValueError: could not convert string to float: '28,37'
  • How to use for and if together in Python
  • How to call a python method from robot framework
  • Python ThreadPoolExecutor Suppress Exceptions
  • how can solve this problem with dynamic programming?
  • How to convert "tensor" to "numpy" array in tensorflow?
  • Tf 2.0 : RuntimeError: GradientTape.gradient can only be called once on non-persistent tapes
  • Scale and concatenate pandas dataframe into a dask dataframe
  • How to create a URL for templateView?
  • Python : Not getting simple adding result
  • Python hex string encoding
  • Get week start date from week number
  • How to use imports from requirements.txt in python
  • Removing tab indent in ipython shell
  • I need to remove duplicates from a list but add the numeric value in them
  • Delay default arguments being read until function is called
  • Interpolate / fillna with a decay formula in pandas
  • What python package can translate Greek letter to ASCII requivalent?
  • How to get output of OS command from Jupyter notebook?
  • Printing AND writing the RIGHTLY formatted number
  • How do I create a shortcut to import most used python modules?
  • Matplotlib: Show selected date labels on x axis
  • Understanding memoization in Python
  • why does the len function return 2 on some iterations when they are all the same length?
  • Change in preference value does not affect the results of Affinity propagation Clustering
  • returning values inside a function
  • Why cant I use a variable in str slicing?
  • Section divider in Spyder
  • Conditional statement in selenium if element does not exists
  • Pandas : how to select index/row label in dataframe that matches a condition
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk