How to insert loop counter into my definition - python

number = 7
def magicnumber (guess):
if number<guess:
print ("too high")
elif number>guess:
print ("too low")
elif number == guess:
print ("well done")
return magicnumber
Above is my code for my magic number guessing program. My question is how to insert a loop counter. I did some research on loop counter integration, and many people have said to use the enumerate function, problem is I have no idea how to use such a function and if it is appropriate in my case. Normally, I jus declare a counter variable as 0 then use the += function to add 1 to that variable but in my case this does not work as I cant declare the variable before the def magicnumber (guess) line and if I were to declare it, the counter would revert back to 0 after the return. I am therefore enquiring how to add a loop count as I only want the user to have 5 guesses.
Thanks

counter = 5
while counter > 0:
guess = int(raw_input())
if magicnumber(guess) == number:
break
counter -= 1
Another approach:
for i in range(5):
guess = int(raw_input())
if magicnumber(guess) == number:
break

Try using the answer from here: That's what static variables are for (among other things).
That would result in the following code
number = 7
def magicnumber (guess):
magicnumber.counter += 1
if(magicnumber.counter <= 5):
if number<guess:
print ("too high")
elif number>guess:
print ("too low")
elif number == guess:
print ("well done")
magicnumber.counter = 0#If you want to reset the counter
return
else:
print "Out of trials!"
return
magicnumber.counter = 0

Related

How do i repeat the code multiple times? in python

How do I make the code reapte such that users can guess the answer to the random number only three times, how do I make it stop at a point? Thanks.
This is a random number guessing game, I'm a total beginner to python and can't find anything that helps me on the web (or it may be that I'm just dumb)
import random
print('what difficulty do you want? Type Easy or Hard accordingly')
difficulty = input('')
if difficulty == 'Hard':
print('your going to have a tough time')
hardrandomnum = random.randint(1,100)
def main():
print('try to guess the number')
playerguess = float (input(""))
if playerguess > hardrandomnum:
print ("guess a lower number")
if playerguess < hardrandomnum:
print("guess a higher number")
if playerguess == hardrandomnum:
print("correct")
restart = 4
if restart >4:
main()
if restart == 4:
exit()
main()
Loops and breaks.
For example if you want to run the code three times wrap it in a for loop:
for i in range(3):
[here goes your code]
or you could make a while loop and break:
while(True):
[here goes your code]
if condition is met:
break
you could use a for loop:
for i in range(3):
#your code
the number in range() indicates how many times you visit the code inside
there are also while loops but for your usecase a for loop should do the trick
Use a looping structure as below answer mentions.
Example with while loop
def repeat_user_input(num_tries=3):
tries = 0
result = []
while tries < num_tries:
tries += 1
result.append(float(input()))
return result
print(repeat_user_input())
Example with a list comprehension and range
def repeat_user_input(num_tries=3):
return [float(input()) for _ in range(num_tries)]
I believe you are looking for something like the below?
import random
import sys
guess_counter = 0
random_number = 0
easy_hard = input('Chose your difficulty lever by typing "easy" or "hard" ')
if easy_hard.lower() == 'easy':
print('Your in luck! You are about to have fun')
random_number = random.randint(1,10)
elif easy_hard.lower() == 'hard':
print('Woow this game is not going to be easy')
random_number = random.randint(1,100)
else:
print('You need to type either easy or hard and nothing else')
sys.exit()
while guess_counter < 4:
user_number = int(input('Guess: '))
if user_number < random_number:
print('Try higher number')
guess_counter += 1
elif user_number > random_number:
print('Trye lower number')
guess_counter += 1
else:
print('Congrats! You Won')
break
else:
print('Ooops! Looks like you luck run out.')

Project with a python loop program

My son has this project he has to do in python and is stuck.
He needs to make a number guessing game. The code must generate a random secret number between 0 and 10, then give the user 5 attempts to guess that number, each guess if not correct must indicate if it is higher or lower than the secret random number. After each guess the code needs to display text stating what has happened. The code also needs to store all guesses and display them at the end. Needs to be made using loop, if, elif, else and an array or list code.
The attempt so far is below
print("Hi there, lets play a little guessing game. Guess the number between 0 and 10")
from random import randint
x = [randint(0,10)]
counter = 0
guess = input("Enter guess:")
while counter < 5:
print("You have " + str(counter) + " guesses left")
counter = counter +1
if guess == x:
print("Congrats you got it")
break
elif guess > x:
print("Too high")
elif guess < x:
print("Too low")
else:
print("You lost")
break
Any help to correct my sons code would be appreciated as this project is due soon and he cannot access his tutor
This should do it. What the code does is explained in comments below.
You need to do x=randint(0,10) which will assign the random number to a variable, i.e x=4 rather than `x = [randint(0,10)], which assigns the random number to a list ,x=[4]```
Also you need to ask for a guess in the loop, instead of doing it only one before the loop started.
Also you would need to convert the string to an int for comparison i.e. guess = int(input("Enter guess:"))
print("Hi there, lets play a little guessing game. Guess the number between 0 and 10")
#Create a random number
from random import randint
x = randint(0, 10)
counter = 0
won = False
#Run 5 attempts in a loop
while counter<5:
#Get the guess from the user
guess = int(input("Enter guess:"))
counter = counter+1
#Check if the guess is the same, low or high as the random number
if guess == x:
print("Congrats you got it")
won = True
break
elif guess > x:
print("Too high")
elif guess < x:
print("Too low")
print("You have " + str(5 - counter) + " guesses left")
#If you didn't won, you lost
if not won:
print("The number was ", x)
print("You Lost")
So here are the corrections. So x has been initialized as array rather than an integer. So none of the comparisons with guess will be working. Also the counter logic is wrong. Rather than starting from zero, start from 5 which is the maximum number of chances and go from the reverse rather. Then at each if/elif loop append all the guesses and print it in the end.
Here is the corrected code
from random import randint
x = randint(0,10)
print(x)
counter = 5
guesses=[] #initalize an empty list to store all guesses
while counter != 0:
guess = input("Enter guess:")
if guess == x:
print("Congrats you got it")
guesses.append(guess)
break
elif guess > x:
print("Too high")
guesses.append(guess)
elif guess < x:
print("Too low")
guesses.append(guess)
else:
print("You lost")
break
counter = counter-1
print("You have " + str(counter) + " guesses left")
print(guesses)
Edit:
x = [randint(0,10)] wouldn't work as you are creating a list here instead of single guess
print("You have " + str(counter) + " guesses left") is also incorrect. You might instead set counter to 5 and check for counter > 0 and do counter -= 1, that way message can be fixed
Lastly to store all guesses you would need a variable
from random import randint
if __name__ == "__main__":
number_to_guess = randint(0,10)
guesses = []
for c in range(5,0,-1):
guessed = input("Enter guess:")
guessed = guessed.strip()
assert guessed.isnumeric()
guessed = int(guessed)
guesses.append(guessed)
if guessed == number_to_guess:
print("yes")
break
elif guessed > number_to_guess:
print("more")
else:
print("less")
c -= 1
print("pending guesses", c)
print("Expected - ", number_to_guess)
print("All guesses - ", guesses)

How to stop While Loops in python? (i've tried using break)

This is my first post ever about programming!
Folks, when i execute this algorithm (a guessing game), it doesnt stop asking me for more inputs, even when i write "quit", that was supposed to be the quiting word. The "break" order doesnt work, and i can't find out why. Maybe it works, but when it quits the loop, it executes the "startgame()" at the bottom, but i need this "startgame()" at the bottom to make the game run for the first time, since the game is inside a function and i need to call it to start the game.
import random
def startgame():
a = random.randint (1,10)
cont = 0
while True:
b = input("Guess a number: ")
if b == 'quit':
break
elif int(b) > a:
print("Too high!")
cont += 1
True
elif int(b) < a:
print ("Too low!")
cont += 1
True
elif int(b) == a:
print ("You got it right!")
print ('You needed ',cont,'guesses!')
startgame()
startgame()
Any ideas about how to solve this?
Your code has a few small issues, but it actually works, you just didn't test enough to find your actual problem.
The issues:
the True lines don't do anything, you don't need them for the while loop; the while will evaluate the True right after it and loop forever.
you're mixing single and double quotes for your strings - that gets hard to read and confusing quickly, so you're better off using one style, preferably whatever PEP8 recommends. https://www.python.org/dev/peps/pep-0008/
The problem:
your break works just fine; try running your script and entering 'quit' at the first prompt, it quits as expected.
the reason it appears not to work is because you restart the entire game by calling the startgame function again after winning the game. This causes a new, nested call from within the game (think 'Inception') and when the game breaks, it ends up on the previous level.
A solution would be to remove the call to startgame() and instead wrapping the whole thing in a second while, for example like this:
import random
def startgame():
b = 0
while b != 'quit':
a = random.randint(1, 10)
cont = 0
while True:
b = input('Guess a number: ')
if b == 'quit':
break
elif int(b) > a:
print('Too high!')
cont += 1
elif int(b) < a:
print('Too low!')
cont += 1
elif int(b) == a:
print('You got it right!')
print('You needed ', cont, 'guesses!')
startgame()
For times like these, I usually use a simple control variable and run the loop on it. For ex:
right_guess=False
while not right_guess:
and then just go
if guess=right:
right_guess=True
break
just remove the startgame() from inside the loop and replace it by break
import random
def startgame():
a = random.randint (1,10)
cont = 0
while True:
b = input("Guess a number: ")
if b == 'quit':
break
elif int(b) > a:
print("Too high!")
cont += 1
elif int(b) < a:
print ("Too low!")
cont += 1
elif int(b) == a:
print ("You got it right!")
print ('You needed ',cont,'guesses!')
break # remove this break statement if you want to restart it again after winning
startgame ()

While loop for the script below

I'm currently in the process of creating a game where it loops over and over again until you guess the right number.
The problem I'm having is getting the looping command right. I want to go for a while loop but I can get it to work, for certain parts of the script. If I use a "while true" loop, the if statement's print command is repeated over and over again but if I use any symbols (<, >, <=, >= etc.) I can't seem to get it to work on the elif statements. The code can be found below:
#GAME NUMBER 1: GUESS THE NUMBER
from random import randint
x = randint(1,100)
print(x) #This is just here for testing
name = str(input("Hello there, my name's Jarvis. What's your name?"))
print("Hello there ",name," good to see you!")
num = int(input("I'm thinking of a number between 1 and 100. can you guess which one it is?"))
attempt = 1
while
if num == x:
print("Good job! it took you ",attempt," tries!")
num + 1
elif num >= x:
print("Too high!")
attempt = attempt + 1
elif num <= x:
print("Too low!")
attempt = attempt + 1
else:
print("ERROR MESSAGE!")
Any and all help is appreciated.
You can use a boolean in the while :
from random import randint
x = randint(1,100)
print(x) #This is just here for testing
name = str(input("Hello there, my name's Jarvis. What's your name?"))
print("Hello there ",name," good to see you!")
attempt = 1
not_found = True
while not_found:
num = int(input("I'm thinking of a number between 1 and 100. can you guess which one it is?"))
if num == x:
print("Good job! it took you ",attempt," tries!")
not_found = False
elif num > x: #Don't need the equals
print("Too high!")
elif num < x: #Don't need the equals
print("Too low!")
else:
print("ERROR MESSAGE!")
attempt = attempt + 1
You should put your question in the loop, because you want to repeat asking after each failure to get it right. Then also break the loop when user found it:
attempt = 0
while True:
attempt = attempt + 1
num = int(input("I'm thinking of a number between 1 and 100. can you guess which one it is?"))
if num == x:
print("Good job! it took you ",attempt," tries!")
break
elif num >= x:
print("Too high!")
attempt = attempt + 1
elif num <= x:
print("Too low!")
else:
print("ERROR MESSAGE!")
Your while needs a colon, and a condition
while True:
and if you use a while True: you have to end the loop, you can use a variable for this.
while foo:
#Your Code
if num == x:
foo = False
Also, you could use string format instead of breaking your string. For example,
print("Good job! it took you %s tries!" % attempt)
or
print("Good job! it took you {0} tries!".format(attempt))

While loop Not Printing Correct Word in Guess game

How do I make the loop work so that it will end when you get it right and ask the question again if you get it wrong?
When i guess wrong two or more times it will always say wrong no matter what.
import random;
import sys;
x = random.randint(1, 100);
print(x);
guess = int(input("Guess a number 1 to 100"));
if guess == x:
print("correct");
sys.exit()
while guess != x:
print("wrong");
int(input("Guess a number 1 to 100"));
print(x);
if guess == x:
print("Correct");
sys.exit()
Also what function records the number of times it loops. For example if I guess wrong 10 times then I want to print that I scored a 10.
You have forgotten to assign the second time around to the guess variable
while guess != x:
print("wrong");
guess = int(input("Guess a number 1 to 100")); #look here
print(x);
if guess == x:
print("Correct");
sys.exit()
Missing 'guess=' in the input line in the loop. To record number of times, just increment a variable in the loop.
[ADDENDUM]
import random;
import sys;
x = random.randint(1, 100);
print(x);
count = 1
guess = int(input("Guess a number 1 to 100: "));
while guess != x:
count += 1
guess = int(input("Wrong\nGuess a number 1 to 100: "));
print("Correct - score = "+str(100./count)+"%");
sys.exit(0)
Actually you should change your codes to:
import random
x=random.randint(1,100)
score=0
while True:
guess=int(input("Guess a number 1 to 100: "))
if guess==x:
print ("Correct!")
break
else:
print ("Not correct!")
score+=1
print ("your answers was wrong {} times.".format(score))
Better statements,less codes. Cheers!

Categories