While True looping the results of a 'if elif' statement - python-3.x

I'm experimenting with While loops and I encountered this:
CODE:
x = int(input('Guess the number 1-10'))
while True:
if (x == 8):
print('yay!')
break
else:
print('No No')
RESULT:
No No
No No
No No
No No
No No
No No
No No
No No
forever until I stop it...
Some people have suggested to use break, but I don't want to stop it on one try when they get it wrong, I want it to give multple tries until they get the right number. What can I do?

You want to ask the user for input in every iteration:
while True:
x = int(input('Guess the number 1-10'))
if (x == 8):
print('yay!')
break
else:
print('No No')

Related

Is there any way to loop a form in python, while indefinitely store the data?

I'm new in coding and recently I've been practicing Python to use in a script in uni lab.
Basically I'm trying to do a loop over a input loop it self. See:
U_Ant = []
while True:
Sample_ID = input("Sample ID: >>" )
print('Assign the halo diameter according to the previous order, then type "done" when finished')
Ant_Halo = input(">", )
if Ant_Halo == 'done':
break
try:
fAnt_Halo = float(Ant_Halo)
except:
print('Invalid input')
continue
try:
U_Ant.append(int(Ant_Halo))
except:
U_Ant.append(float(Ant_Halo))
But the real thing starts right after that. This single code above allows user to input values for only one sample (halo diameter given to a specific sample), what I want to do is:
print("All fields are correct?")
check_1 = input("Y/N: >")
if check_1 == "Y" or 'y':
pass
else:
return self.mo_antimicrobial()
print("Do you wish to add more samples?")
check_1
if check_1 == "Y" or 'y':
return self.mo_antimicrobial()
else:
pass
And be able to add more samples and inputs without fearing lose them. The point of the whole script is to gather multiple sample data (halo diameters) and plot as a table (where the columns are variable as well), so I must have a way to make every entry unique.
I tried to use dictionaries but I'm not being able to neither add int or str to it. I though of using:
def pilot():
sample_number = int(input("Please, set the number of samples for this experiment:" ))
for i in range(0, sample_number):
while True:
U_Ant = []
Sample_ID = input("Sample ID: >>" )
print('Assign the halo diameter according to the previous order, then type "done" when finished')
Ant_Halo = input(">", )
if Ant_Halo == 'done':
break
try:
fAnt_Halo = float(Ant_Halo)
except:
print('Invalid input')
continue
try:
U_Ant.append(int(Ant_Halo))
except:
U_Ant.append(float(Ant_Halo))
cache_data += {'ID': [Sample_ID], 'Halo': [U_Ant]}
print("Do you wish to add more samples?")
check_1 = input()
if check_1 == "Y" or 'y':
pilot()
else:
pass
but things won't work, since the output is just:
Sample_ID = input("Sample ID: >>" )
print('Assign the halo diameter according to the previous order, then type "done" when finished')
Ant_Halo = input(">", )
Sorry If I was too much vague, it's my first time posting on stack and this is also a reflex of my ignorance in this programming language. Thanks in advance.

python simple help (NameError: name is not defined)

Whenever I run this is get:
Traceback (most recent call last):
File "main.py", line 130, in <module>
while is_playing_cg:
NameError: name 'is_playing_cg' is not defined
I want the user to be able to press 1 or 2 to select which game mode to use and then once pressed it starts. I don't know why it's doing this. Whenever it's fixed it should run through just fine.
New edit
Now it just loops and says 1 or 2 over and over again.
import random
is_playing_cg = False
is_playing_hg = False
def game_select_screen():
#Game Select Screen
print("""
._________________________________.
| |
| ~ Welcome To Guess-A-Number ~ |
| ~~~ |
| ~ Press 1 OR Press 2 ~ |
| You ^ Guess | PC ^ Guess |
|_________________________________|""")
selecting = True
while selecting:
print()
game_mode = input("1 OR 2: ")
try:
int(game_mode)
except ValueError:
print("This is not a Number.")
else:
game_mode = int(game_mode)
if game_mode == 1:
is_playing_hg = True
elif game_mode == 2:
is_playing_cg = True
#Defining Random Number for human guess
def play_human_guess():
num = random.randint (1,10)
print()
print("Im Thinking of a Number 1 Through 10.")
print("You Have 3 Chances.")
chances = 3
game_fisnished = False
#Game is playing (Human Guesses)
while not game_fisnished:
guess = input("> Take A Guess: ")
#Accept only numbers
try:
int(guess)
except ValueError:
print("This is not a Number.")
else:
guess = int(guess)
if guess < num:
chances -=1
if chances == 0:
print()
print("Sorry You Guessed Too Many Times.")
game_fisnished = True
elif chances !=0:
print()
print("You Guessed Too Low. ("+str(chances)+") Chance(s) Remaining.")
elif guess > num:
chances -=1
if chances == 0:
print()
print("Sorry You Guessed Too Many Times.")
game_fisnished = True
elif chances !=0:
print()
print("You Guessed Too High. ("+str(chances)+") Chance(s) Remaining.")
else:
print()
print("Congradulations, You Won!")
game_fisnished = True
#Game Ended
def end():
print()
print("Thanks For Playing!")
#Setting up for computer guess
def play_computer_guess():
print()
print("Pick a Number 1 Through 10")
print("I Have 3 Chances to Guess Your Number.")
chances = 3
game_fisnished = False
#Game is playing (Computer Guess)
while not game_fisnished:
guess1 = input("Is your number 5?")
#Show Game Select Screen
game_select_screen()
while is_playing_cg:
#Start Game
selecting = False
play_computer_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_cg = False
while is_playing_hg:
#Start Game
selecting = False
play_human_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_hg = False
end()
The variable is_playing_cg is only available in the "block" that creates it.
Block is function / loop / if statement / etc.
In your program you need to initialize the variable globally so you can call them in multiple functions.
Good luck!
You are defining is_playing_cg inside of a conditional statement at the top of your code. So if that option is not selected, then when you get to the latter conditional statement, it has never heard of that variable.... and it is not defined in the namespace. So you could either define it at the top and give it a default (False) or more better, because you only have 2 options, just use one variable to control the computer / human.
Here is a toy example:
selection = int(input('enter 1 for human, 2 for computer: '))
if selection == 1:
human_play = True
elif selection == 2:
human_play = False
else:
# make some loop that asks for input again or such...
pass
# later on...
if human_play:
# ask human for input...
else:
# have AI make turn
#if needed, you can also handle special cases like this:
if not human_play:
# do something unique to computer turn ...
Additional info...
So you got bit by the scope of the variables in your update. You are defining these variables inside of a function and when you put the defaults outside of the function, they are not in the same scope, so whatever you do inside the function is lost. So, you need to change your function into something that returns the mode you want, and catch that in the function call like such:
def ... :
# input ...
if game_mode == 1:
human_playing = True
selecting = False
elif game_mode == 2:
human_playing = False
selecting = False
return human_playing # this will return T/F back to the function call
And then later:
#Show Game Select Screen
human_playing = game_select_screen()
while not human_playing:
#Start Game
selecting = False
play_computer_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_cg = False
while human_playing:
#Start Game
This (above) works for me, but there are still other logic errors popping up! :) Have fun
This particular error is probably there because you have not defined is_playing_cg as global before using it in your function game_select_screen. Simply put global is_playing_cg at the start of your game_select_screen function to tell python you want to use the global variable instead of creating a scoped variable.

Proper way of writing recurring function in python

So I'm new to python and I tried making a random number game generator as an exercise. You need to guess the random number in a limited number of tries. Here's my code.
import random
rand_num = random.randint(1,6)
print("\nNUMBER GUESSING GAME")
lives = 5
def guess():
guess = int(input("Input guess: "))
return guess
print(rand_num) #to see the correct answer
x = guess()
if x == rand_num:
print("Good job! YOU WIN.\n")
else:
while x != rand_num:
if x == rand_num:
print("Good job! YOU WIN.\n")
break
lives -= 1
print("Incorrect. Please try again")
guess()
if lives == 0:
print("YOU LOSE.\n")
break
So if your first guess is wrong, and you found the right answer in the subsequent tries, the game won't recognize it.
Thanks in advance.
You were on the right track. In the future, walk yourself through the program thinking what each line is doing and whether the sequence makes logical sense.
There was only one actual error in your code: you didn't collect a new x value in your code when calling guess in the while loop. The other elements were correct, just out of order. Here is a more logical order, with the collecting issue fixed,
import random
rand_num = random.randint(1,6)
print("\nNUMBER GUESSING GAME")
lives = 5
def guess():
guess = int(input("Input guess: "))
return guess
print(rand_num) #to see the correct answer
x = guess()
if x == rand_num:
print("Good job! YOU WIN.\n")
else:
while x != rand_num:
# 1) Notify the user
print("Incorrect. Please try again")
# 2) Decrement remaining guesses
lives -= 1
# 3) Check if maximum number of guesses
# reached - end if yes
if lives == 0:
print("YOU LOSE.\n")
break
# 4) Get a new guess
x = guess()
# 5) Compare
if x == rand_num:
print("Good job! YOU WIN.\n")
You may want to notify your player what are the ranges of numbers to guess. You can also extend this exercise, and code several difficulty levels, each with a different range (e.g. simple level 1-6, medium 1-20, etc.), to be chosen by the player.
As #Stef mentioned in the comment, it is technically cleaner and more common to include the guess number (lives) condition as part of the while loop condition,
import random
rand_num = random.randint(1,6)
print("\nNUMBER GUESSING GAME")
lives = 5
def guess():
guess = int(input("Input guess: "))
return guess
print(rand_num) #to see the correct answer
x = guess()
if x == rand_num:
print("Good job! YOU WIN.\n")
else:
while (x != rand_num) and (lives > 0):
# 1) Notify the user
print("Incorrect. Please try again")
# 2) Decrement remaining guesses
lives -= 1
# 3) Get a new guess
x = guess()
# 4) Compare, enf if correct
if x == rand_num:
print("Good job! YOU WIN.\n")
# If ending because no more guesses left
if lives == 0:
print("YOU LOSE.\n")
I use brackets for each condition, it is not necessary here and a matter of style. I like to separate conditions this way.
Also, the "YOU LOSE.\n" part is now printed at the end, if the all the guesses were exhausted.
One note: with your code as it is now, your player actually gets to guess 6 times, once in the beginning and 5 more times in the while loop.

How to ask for input again after taking input and receiving output in python

x = int(input())
for i in range(2,x):
if(x % i ==0):
print("not Prime")
break
else :
print("Prime")
In this example, I am asking the user to input a value for x. So let's say the user inputs 6 since it is not a prime number, it will say "not Prime." However, I want to ask the user to input another value to check.
x = int(input())
for i in range(2,x):
if(x % i ==0):
print("not Prime")
break
else :
print("Prime")
x = int(input())
Doing this does not work. so what can I do to ask the user to input another value? without having to run it again?
In your second code snippet you are not doing anything after the second input. Perhaps you are forgetting to call the forloop again? This works for me to do what you described.
Does the following work for you? Of course using a function is more elegant for this.
x = int(input())
for i in range(2,x):
if(x % i ==0):
print("not Prime")
break
else :
print("Prime")
x = int(input())
for i in range(2,x):
if(x % i ==0):
print("not Prime")
break
else :
print("Prime")
Here is how it runs in my pycharm
This is exactly what functions are for. Wrap your logic in a function and call it wherever you need:
def check_prime(x):
for i in range(2,x):
if(x % i ==0):
print("not Prime")
break
else :
print("Prime")
x = int(input())
check_prime(x) # first number
x = int(input())
check_prime(x) # another number
Note if you want some n numbers to be entered, using an infinite loop to read input() can avoid repetition.

Closing program with while loop

I'm new to Python v3 and am using a while loop at the end of my program to determine if the user wants to restart/retry the program or finish.
If I select yes and I repeat the program more than once and then select no, I keep returning the "Would you like to search again: (Y/N) > " option for the number of times I re-tried the program e.g. 3 attempts and I have to enter n three times before break takes effect.
Code used is below.
while True:
finish_input = input("Would you like to search again: (Y/N) > ")
if finish_input.lower() == ("y"):
my_project()#restarts the program from the start
continue
elif finish_input.lower() == "n":
print()
print("Thank you for using this service.")
break
else:
print()
print("Invalid entry. Please enter Y or N")
I want the option to restart but only have to input n once to close/break the program and exit. Help would be really appreciated.
What you want is:
def my_project():
#Your other code here
my_project()
#The code that you posted
But you are doing:
def my_project():
#Your other code here
#The code that you posted
The difference is that in the last one, you are looping inside the program: each y is another call to the whole function that later and for each one of those you'll have to put n.
The code would look like this:
def my_project():
#Your other code here
my_project()
while True:
finish_input = input("Would you like to search again: (Y/N) > ")
if finish_input.lower() == "y": my_project()
elif finish_input.lower() == "n":
print("\nThank you for using this service.")
break
else: print("\nInvalid entry. Please enter Y or N")
I think its a bad way to implement this. How about doing something like this.
#program starts
run_prog = True
while run_prog:
#Your original code
finish_input = "a"
while True:
finish_input = input("Would you like to search again: (Y/N) > ")
if finish_input.lower() == ("y"):
run_prog = True
break
elif finish_input.lower() == "n":
run_prog = False
print()
print("Thank you for using this service.")
break
else:
print()
print("Invalid entry. Please enter Y or N")

Resources