Executing one line of code inside a while loop only once - python

How do I make a specific line of code execute only once inside a while loop?
I want the line:
"Hello %s, please enter your guess: " %p1" to run only once and not every time the player guesses wrong.
Is there are command or function I can use or do I have to structure the whole game differently? Is there a simple fix to the program in this form?
import random
number = random.randint(1,9)
p1 = input("Please enter your name: ")
count = 0
guess = 0
while guess != number and guess != "exit":
guess = input("Hello %s, please enter your guess: " % p1)
if guess == "exit":
break
guess = int(guess)
count += 1
if guess == number:
print("Correct! It Took you only", count, "tries. :)")
break
elif guess > number:
print("Too high. Try again.")
elif guess < number:
print("Too low. Try again.")

You can create a flag variable, e. g.
print_username = True
before the while loop. Inside the loop uncheck it after loop's first iteration:
if print_username:
guess = input("Hello %s, please enter your guess: " % p1)
print_username = False
else:
guess = input("Try a new guess:")

You have to ask for a new guess on every iteration - else the code will loop either endlessly (after first wrong guess) or finish immediately.
To change up the message you can use a ternary (aka: inline if statement) inside your print to make it conditional:
# [start identical]
while guess != number and guess != "exit":
guess = input("Hello {}, please enter your guess: ".format(p1) if count == 0
else "Try again: ")
# [rest identical]
See Does Python have a ternary conditional operator?
The ternary checks the count variable that you increment and prints one message if it is 0 and on consecutive runs the other text (because count is no longer 0).
You might want to switch to more modern forms of string formatting as well: str.format - works for 2.7 as well

A way to execute an instruction only x times in a while loop could be to implement a counter, and add an if condition that checks if the counter < x before executing the instruction.

You should ask for the username outside of the loop and request input at the beginning of the loop.
Inside the loop you create output at the end and request input on the next iteration. The same would work for the first iteration: create output (outside of the loop) and then request input (first thing inside the loop)

Related

While loop keeps printing constantly, doesn't allow for user input

I'm trying to complete this assignment asking user for a number and if it's not -1 then it should loop. if it's -1 then to calculate the average of the other numbers.
I'm getting stuck with the actual loop - it endlessly keeps printing the message to user to enter a different number - as in the picture - and doesn't give user a chance to enter a different number. Please help, I've been through so many videos and blogs and can't figure out what's actually wrong.
#creating a list for later calculations:
wrong = []
#asking for input:
input("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\nIf not correct you'll have to guess again ^-^")
num =int(input("number:"))
#looping
while num != -abs(1):
wrong.append(num)
print("Nope, guess again:")
if num == -abs(1):
break
av = sum(wrong) / len(wrong)
print ("You got it! The average of your wrong answers is: ")
print(av)
print("The End")
print("Nope, guess again:")
You need to include the input function in the loop if you want it to work. I corrected the rest of your code as well, you don't need the if condition. More generally you should avoid to use break, it often means you are doing something wrong with your loop condition. Here it is redondant and the code after break is never executed.
wrong = []
input("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\nIf not correct you'll have to guess again ^-^")
num = int(input("Number: "))
while num != -1 :
wrong.append(num)
num = int(input("Nope, guess again: "))
av = sum(wrong) / len(wrong)
print(f"You got it! The average of your wrong answers is: {av}\nThe End")
You are just breaking the loop before printing the results, first print the results, then break the loop.
And a while loop isn't necessary for your program, use if condition wrapped in a function instead:
#creating a list for later calculations:
wrong = []
#asking for input:
input("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\nIf not correct you'll have to guess again ^-^")
#looping
def go():
num =int(input("number:"))
if num != -abs(1):
wrong.append(num)
print("Nope, guess again:")
if num == -abs(1):
av = sum(wrong) / len(wrong)
print ("You got it! The average of your wrong answers is: ")
print(av)
print("The End")
break
print("Nope, guess again:")
go()
There are lots of issues in the code.
If you want to get inputs in while looping, you should include getting input code inside the while loop like below,
while num != -1:
......
num =int(input("number:"))
......
Also you don't have to include 'break' inside the while loop because, when num != 1, the loop will stop.
You should ask for input inside your loop, but you just print "Nope, guess again:".
wrong = []
print("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\n"
"If not correct you'll have to guess again ^-^")
num = int(input("number: "))
# looping
while num != -1:
wrong.append(num)
num = int(input("Nope, guess again: "))
av = sum(wrong) / len(wrong)
print(f"You got it! The average of your wrong answers is: {av}\nThe End")

Infinite While Loop while making a simple logic game "Bagels"

I am using The Big Book of Small Python projects to increase my skills in python, and on the very first project, which is making a simple logic game, On the first try, the code goes all the way however if you get it wrong you it won't run properly.
Here is the code and a description of the game, the while loop with chances is supposed to run for the whole game, until you run out of chances, the second while loop is supposed to run in case user enters below or more than length three for the number
import re
import random
#In Bagels, a deductive logic game, you
#must guess a secret three-digit number
#based on clues. The game offers one of
#the following hints in response to your guess:
#“Pico” when your guess has a correct digit in the
#wrong place, “Fermi” when your guess has a correct
#digit in the correct place, and “Bagels” if your guess
#has no correct digits. You have 10 tries to guess the
#secret number.
choice_of_nums=['123','345','674','887','356','487','916']
random_three_num=random.choices(choice_of_nums)
count_bagel=0
count_fermi=0
Chances=10
while Chances!=0:
guess = input(f'Guess the three digit number! You have {Chances} to guess! ')
while len(guess)!=3:
guess=input('You must choose a three digit number! Try again! ')
for i in range(0,len(random_three_num)):
if guess==random_three_num:
print('YOU WIN! Well done')
break
elif guess[i] not in random_three_num:
count_bagel+=1
if count_bagel==len(random_three_num):
print('Bagels')
Chances=Chances-1
elif guess[i]==random_three_num[i]:
count_fermi+=1
Chances=Chances-1
print('Fermi')
elif guess in random_three_num:
print('Pico')
import random
choice_of_nums = ['123', '345', '674', '887', '356', '487', '916']
random_three_num = random.choice(choice_of_nums)
count_bagel = 0
count_fermi = 0
chances = 10
while chances > 0:
guess = input(f'Guess the three digit number! You have {chances} to guess! ')
while len(guess) != 3:
guess = input('You must choose a three digit number! Try again! ')
while not guess.isdigit():
guess = input('You must choose integer values! ')
number_is_present = any(number in guess for number in random_three_num)
if guess == random_three_num:
print('YOU WIN! Well done')
chances = 1 # combined w/ the last line, chances will become = 0
elif not number_is_present:
print('Bagel')
else:
index_is_right = False
for i in range(len(guess)):
if guess[i] == random_three_num[i]:
index_is_right = True
if index_is_right:
print('Fermi')
else:
print('Pico')
chances -= 1
(06/28/22) added chances = 1 if the guess is right, so to exit the while loop
random.choices returns a list
you don't need the re module
use snake case as suggested in PEP8
The break after print('YOU WIN! Well done') exits the for loop not the while loop. Put Chances = 0 before the break:
if guess==random_three_num:
print('YOU WIN! Well done')
Chances = 0
break
You should never check a while loop with a condition like x != 0. Always use <= or >=. The reason being, that if somehow the number zero is skipped and you end up at -1 then the loop will still exit.
Couldn't your check if guess==random_three_num: be done before the for loop? Then the break statement would actually break the while loop. Now it's only breaking the for loop. This is one reason that could lead to a infinite loop.
Your second to last line elif guess in random_three_num: should probably be elif guess[1] in random_three_num:.
Chances=Chances-1 could probably be outside the for loop also, as the number of chances should decreasing only one per guess. Currently the number of chances decreases up to 3 times during the for loop (every time you hit 'Fermi'). This could lead to issue described in "1."

Why cant i sum up all of my values (user values) problem with while?

I'm new to the coding world. I have a problem with adding up all of the users' input values, as I don't know how many there will be. Any suggestions?
This is how far I've gotten. Don't mind the foreign language.
import math
while(True):
n=input("PERSONS WEIGHT?")
people=0
answer= input( "Do we continue adding people ? y/n")
if answer == "y" :
continue
elif answer == "n" :
break
else:
print("You typed something wrong , add another value ")
people +=1
limit=300
if a > limit :
print("Cant use the lift")
else:
print("Can use the lift")
You don't need to import math library for simple addition. Since you did not mention that what error are you getting, so I guess that you need a solution for your problem. Your code is too lengthy. I have write a code for you. which has just 6 lines. It will solve your problem.
Here is the code.
sum = 0;
while(True):
n = int(input("Enter Number.? Press -1 for Exit: "))
if n == -1:
break
sum = sum+n
print(sum)
Explanation of the Code:
First, I have declared the variable sum. I have write while loop, inside the while loop, I have prompt the user for entering number. If user will enter -1, this will stop the program. This program will keep on taking user input until unless user type "-1". In the end. It will print total sum.
Output of the Code:
Here's something for you to learn from that I think does all that you want:
people = 0
a = 0
while True:
while True:
try:
n = int(input("PERSONS WEIGHT?"))
break
except ValueError as ex:
print("You didn't type a number. Try again")
people += 1
a += int(n)
while True:
answer = input("Do we continue adding people ? y/n")
if answer in ["y", "n"]:
break
print("You typed something wrong , add another value ")
if answer == 'n':
break
limit = 300
if a > limit:
print("Total weight is %d which exceeds %d so the lift is overloaded" % (a, limit))
else:
print("Total weight is %d which does not exceed %d so the lift can be operated" % (a, limit))
The main idea that was added is that you have to have separate loops for each input, and then an outer loop for being able to enter multiple weights.
It was also important to move people = 0 out of the loop so that it didn't keep getting reset back to 0, and to initialize a in the same way.

Why am I get a syntax error here when I am equating a variable containing an integer and a variable containing a numerical input from the user?

I am just learning the basics of Python and created a number guessing game. I want the user to be able to guess the number as many times as possible until they guess correctly. I did this through a while loop but the code, "else guess == a:" near the end is giving me a syntax error. I am confused because the while loop ensures that the input guess is an integer by the if statement,
if guess.isdigit():
guess = int(guess)
Please help
import random
a = random.randint(1,10)
print("this is a number guessing game")
question_one = input("Would you like to play? Yes or No?:")
if question_one == "Yes":
print("Let's go!")
else:
print("That sucks!")
exit()
guess = None
while guess != a:
guess = (input("Alright, guess a number from 1-10"))
if guess.isdigit():
guess = int(guess)
if guess > a:
guess = int(input("Guess lower!"))
elif guess < a:
guess = int(input("Guess higher!"))
else guess == a:
print("you got it!")
else doesn't let you define a condition. else will execute if all other conditionals return false. You should change that last else to elif. Or you can simply leave out the conditional guess == a all together. If it is not greater than or less than, the only other thing it can be is equal to.
If you have the last else, the code inside the else will be executed if any other condition goes false. So I think if you change the last else with an elif we work properly.
An else statement contains the block of code that executes if the conditional expression in all your if or elif statements is false. Hence in your case you're supposed to use the elif statement instead of else. See the following:
elif guess == a:
print("you got it!")

Am I allowing 3 guesses or 2?

I am learning Python on Codecademy, and I am supposed to give the user 3 guesses before showing "you lose". I think my code allows 3 entries, but the website shows "Oops, try again! Did you allow the user 3 guesses, or did you incorrectly detect a correct guess?" unless the user guesses correctly within 3 trials. Can someone tell me what's wrong?
from random import randrange
random_number = randrange(1, 10)
count = 0
# Start your game!
guess= int(raw_input("Please type your number here:"))
while count < 2:
if guess==random_number:
print "You win!"
break
else:
guess=int(raw_input("Please guess again:"))
count+=1
else:
print "You lose!"
print random_number
Your loop will indeed ask the user for three guesses. (As can be trivially seen by running the code—ignore those other answers telling you to change the loop condition, that's the wrong solution.)
The problem with your loop is a more subtle one: because of the way it's structured, the third guess is never tested! You can see this by setting random_number to a constant and guessing wrong twice, then right on the last try; you still lose.
Your best bet is to use a more straightforward loop structure, where the asking and the checking happens in the same iteration of the loop.
for attempt in xrange(3):
guess = int(raw_input("Please enter a number: "))
if guess == random_number:
print "You win!"
break
print "Wrong! Try again."
else:
print "You lose! The number was", random_number
If you want a different prompt on the second and subsequent guesses, try this:
prompt = "Please enter a number"
for attempt in xrange(3):
guess = int(raw_input(prompt + ": "))
if guess == random_number:
print "You win!"
break
prompt = "Wrong! Try again"
else:
print "You lose! The number was", random_number
You need while count <= 2. Your count starts at 0. Then it goes through the body of your loop once. Then it gets incremented to 1. Then it goes through your loop body another time. Finally, once it increments to 2, your while condition evaluates to false, and the loop body doesn't execute a third time.
Be careful with corner cases when you're setting up conditions. :)
The condition should be:
while count < 3:
To make it easier to understand, I suggest you start the counter in count = 1 and write the condition like this:
while count <= 3:
Now it's more clear that exactly 3 repetitions are allowed. But let's see why your code was wrong:
count starts at 0, and it's true that 0 < 2, so we enter the loop
At the first failed attempt, count gets incremented to 1, and it's true that 1 < 2 so we enter the loop once more
At the second failed attempt, count gets incremented to 2, and it's no longer true that 2 < 2 so we exit the loop
So you see, only two attempts were being considered.

Categories