Number guessing Guessing Game [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I made a simple number guessing Game and it works perfectly fine, but I want to add something that says "The Number you have entered is too high/ low", because when I type in 100 as my upper bound it is much too difficult to guess the number.
import random
while True:
flag = True
while flag:
num = input('Enter an upper bound: ')
if num.isdigit():
print("Let's Play!")
num = int(num)
flag = False
else:
print('Invalid input! Try again!')
secret = random.randint(1,num)
guess = None
count = 1
while guess != secret:
guess = input('Please enter a number between 1 and ' + str(num) + ": " )
if guess.isdigit():
guess = int(guess)
if guess == secret:
print('Right! You have won!')
else:
print('Try again!')
count += 1
print('You needed', count, 'guess(es) ')

Alright, I'm not gonna solve it for you, but I'll give you a hint. This seems like a homework problem, so it would be unethical of me to provide you with a solution.
else:
print('Try again!')
count += 1
Look at this else statement here. What is the purpose of this else statement? To tell the user they got the guess wrong.
Think about how you can put an if/else condition inside this else condition, to tell the user if their input is too high, or too low.

Related

how to make if/elif/else more efficient [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
i'm stuck and need a little help.
how can i make this more efficient and reduce the number of if/elif/else.
i thought to make a function that check the range of an input let's say between 1 to 5 and then return the value to print out what i need.
i would love to hear your thoughts on it:
there some code:
while True:
difficulty = input("Please choose difficulty from 1 to 3: ")
if not difficulty.isdigit():
print("Please enter a valid number: ")
else:
break
while True:
if difficulty == "1":
print("Level of difficulty is very easy.")
break
elif difficulty == "2":
print("Level of difficulty is easy.")
break
elif difficulty == "3":
print("Level of difficulty is normal.")
break
else:
difficulty = input("You chose an invalid number, choose between 1 - 3. Try again:")
Ideally, you check the range of the number in the first loop
Other than that, use a list
descriptions = [
"very easy, ok you are scared to loose but let's play.",
"easy, ok let's play."
]
while True:
i = int(difficulty) - 1
if i not in range(5):
# invalid input, get it again
difficulty = input("must be between 1 and 5: ")
continue
lines()
print("Level of difficulty is " + descriptions[i])
break

Three Problems that I can not resolve in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
So I am creating a new simple game to practice my python programming, it is a point/score system that I wanted to implement. I also wanted to make it so it's intelligent by asking the user if it wants to play. So I have three problems at the moment, when I ask the user if it wants to play I wasn't sure what to do if they said no or "n" if they didn't want to play, instead what happens is that it just continues playing then crashes saying "n" is not defined. The second problem that I have is when the user puts the right answer for the random function I put print("You guessed it right!") but it just prints a bunch of them. My third and final problem is the point system, I wasn't sure if it executed after the million printed statements, but I'll see after I fix it.
Here is my game
import random
total_tries = 4
score = 0
print("Welcome to Guess the number game!")
answer = input("Would you like to play? y/n: ")
if answer == "y":
n = (random.randrange(1, 10))
guess = int(input("I am thinking of a number between 1 and 20: "))
while n!= guess:
if guess < n:
total_tries - 1
print("That is too low!")
guess = int(input("Enter a number again: "))
elif guess > n:
print("That is too high")
total_tries - 1
guess = int(input("Enter a number again: "))
else:
break
while n == guess:
score = +1
print("You guessed it right!")
if total_tries == 0:
print("Thank you for playing, you got", score, "questions correct.")
mark = (score/total_tries) * 100
print("Mark:", str(mark) + ""%"")
print("Goodbye")
Error when putting no for playing:
while n!= guess:
NameError: name 'n' is not defined
For question 1 you want the system to exit when the user says no. I would do this by using sys.exit to kill the code.
import sys
...
answer = input("Would you like to play? y/n: ")
if answer == "y":
n = (random.randrange(1, 10))**strong text**
else:
sys.exit('User does not want to play, exiting')
For problem 2 you are getting your print statement a million times because you're failing to exit. In the code below n is always equal to guess because you never change n. You don't need a while statement here because you already know you only left the above section when n started to equal guess. Another issue to think about. How will you make it stop when the number of turns runs out?
while n == guess:
score = +1
print("You guessed it right!")
For the third question, think about what will happen here if the number of turns reaches 0.
if total_tries == 0:
print("Thank you for playing, you got", score, "questions correct.")
mark = (score/total_tries) * 100
In particular, what would happen when you try to calculate mark?
This condition will only trigger when answer is "y"
if answer == "y":
n = (random.randrange(1, 10))
Remove this and the code will run or modify it as such
if answer == "y":
n = (random.randrange(1, 10))
elif answer == "n"
# set n to some other value

Why is my Python code ignoring my if-statement and quitting? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am trying to write a python word puzzle game which may have multiple players and points are given based on the length of the words found.
Here is my function which 'plays' the game, however, it always results in "Game over!" no matter if my answer is right or wrong. So it quits the game every time.
def play_game(players, board , words, answers):
found_words = []
num_remaining = num_words_on_puzzle - len(found_words)
player_num = 0
while num_remaining > 0:
print_headers(players, board, found_words, num_remaining)
guess_input = input("{player}, make a guess: ".format(
player=players[player_num % len(players)][0]))
# Allow player to quit
if guess_input.lower() == 'q' or 'quit':
break
# Determine if the guess is valid
guess = convert_guess(guess_input)
if is_valid_answer(answers, guess):
# Update a players score since answer is valid
update_score(players[player_num % len(players)], matching_answer(answers, guess))
# Add this word to found_words list
found_words.append(matching_answer(answers, guess))
print("Congratulations, you found '%s'." % matching_answer(answers, guess))
print("That's %d points(s)." % word_score(matching_answer(answers, guess)))
else:
print("Sorry, that is incorrect.")
num_remaining = num_words_on_puzzle - len(found_words)
player_num += 1
print("\nGame over!\n")
print("The final scores are: \n")
print_score(players)
print(answers)
I hope someone can help me see where my issue is.
The line:
if guess_input.lower() == 'q' or 'quit':
always evaluates to True, because it goes as
if (uess_input.lower() == 'q') or ('quit') which is (False) or (True) --> True as any String != '' is True
Change
if guess_input.lower() == 'q' or 'quit':
to
if guess_input.lower() in ['q', 'quit']

How to make every 'beginner' shown at random during the run of the program [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Im currently in make of creating a math game that involves: addition, subtraction, multiplication and division. These parts with purple borders around them are the questions that i had created for the addition part when the user chooses to pick addition.
I dont know how to make these question be shown at random. When the user goes to select addition for addition questions everytime he does or goes back to do it again after he is done i want the questions not to be the same each time i want them to be in a different order. So its random each time.
#addition questions
def beginnerquestionsaddition():
os.system('clear')
score = 0
beginner1 = input("2 + 3 = ")
if beginner1 == ("5"):
print("Correct, Well Done!")
score += 1
time.sleep(1)
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
beginner2 = input("6 + 7 = ")
if beginner2 == ("13"):
print("Correct, Well Done!")
score += 1
time.sleep(1)
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
beginner3 = input("2 + 5 = ")
if beginner3 == ("7"):
print("Correct, Well Done!")
score += 1
os.system('clear')
time.sleep(1)
endquestadditionbeginner()
print("your score was: ")
print(score)
time.sleep(3)
introduction()
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
endquestadditionbeginner()
print("your score was: ")
print(score)
time.sleep(3)
introduction()
So this isn't exactly an answer for the specific way you decided to go about this program but this is a much simpler way:
from random import randrange
def beginner_addition():
A = randrange(1,11) # Increase range on harder questions
B = randrange(1,11) # Ex. for intermediate_addition(), randrange would be (10,21) maybe...
C = A + B
ans = input("What's the answer to " + str(A) + "+" + str(B) + "? ")
if ans == str(C):
print('Correct')
else:
print('Incorrect')
while True:
beginner_addition()
Of course, this is just example code. You could easily include your points system and perhaps move up in difficulty when the points hit a certain level. You could also randomize the operation. Sorry if this isn't what you want but I saw your code and I figured there is nothing wrong with simplifying your code...

Break function not working in Python 3.5! i dont know why. i need advise [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Ok, so i tryed making a number guessing game...didnt work so i turned to youtube.
i even tryed COPYING somone elses code! still didnt work for me. this is my code.
import random
import time
print('This is a guessing gamefrom 1-1000.')
num = random.randint(1, 1000)
time = time.time()
guess = int(input('what number do you guess? '))
playing = True
while(playing):
if guess < num:
print('Guess is too low!')
elif guess > num:
print('Guess is too High!')
elif guess == num:
break
print('Nice job!')
time2 = time.time()
totalTime = str(int(time2-time1))
print('you took ' + totalTime + 'seconds to guess the number')
and if i run it and enter a number it repeats either "answer is too high" or "answer is too low" i dont know what to do.
If you don't ask for a new guess, you will either get it right on the first try and break out of the loop, or you will loop forever because that wrong guess will be the same on every iteration. To fix this, reassign guess every time in your while loop:
time = time.time()
playing = True
while(playing):
guess = int(input('what number do you guess? '))
if guess < num:
# etc.

Categories

Resources