Creating a loop of if statments - python

if explication == "y":
print("The game is very simple, the programe generate a random number between 0 and 100 and your" +
" objective is to guess it, if you type a number lower than the generated number i'll tell you" +
" and the same will happen if you type a bigger number and there's a score if you guess wrong" +
" it will decrease and when the score reach 0 you loose, that's all enjoy the game!")
if explication == "n":
print("Great then we'll go straight to having fun!")
if explication != "n" and explication != "y":
explication = input("please choose y or n: ")
So i started learning python and i wanted to do a simple fun program, and here i wanted to ask the user if he needed explication of the game that was simple to do, but i also wanted to make him choose another time if he miss clicked or he just wanted to type other things so i made the 3rd if statement, i also wanted it to repeat so if he keeps typing things other than y and n the program will always send "please choose y or n" until he he types either y or n is there a way to do this?

explication = None
# keep asking until we get "y" or "n"
while explication not in ["y", "n"]:
# retrieve input
explication = input("please choose y or n: ")
# check whether it's y or n
if explication == "y":
print("The game is very simple...")
elif explication == "n":
print("Great then we'll go straight to having fun!")
# if the input is neither y nor n, the program ends up here
# and loops again
Alternative:
# keep looping unconditionally
while True:
# retrieve input
explication = input("please choose y or n: ")
if explication == "y":
# print and break
print("The game is very simple...")
break # <- this gets us out of the while loop
elif explication == "n":
print("Great then we'll go straight to having fun!")
break

Here is a simple way to write the code
explication = None
while(explication != "n" and explication != "y"):
explication = input("please choose y or n: ")
if explication == "y":
print("The game is very simple, the programe generate a random number between 0 and 100 and your" +
" objective is to guess it, if you type a number lower than the generated number i'll tell you" +
" and the same will happen if you type a bigger number and there's a score if you guess wrong" +
" it will decrease and when the score reach 0 you loose, that's all enjoy the game!")
break
if explication == "n":
print("Great then we'll go straight to having fun!")
break
#Code to start the game after this comment
Explanation
We set explication to None as the explication variable has to be initialized first.
The while loop runs while the input is not y or n. If it is y, we explain the game and then leave the loop using break. If it is n, we skip the explication and break from the loop. After you break from the loop you can put the code for the game!

Related

Getting out of a while loop using input

i am preparing a function to user to guess a random number generated by computer.
The output should be the number of guesses, and if the guess is correct, lower or higher than the generated number.
In the end the, the user should be asked if he wants to play again or not.
Everything is working excepts this last part, because i can't break the loop to stop the game.
Here's my code:
#random number guessing game
import random
def generate_random (min,max):
return random.randint (min,max)
#generate_random (1,100)
star_range=1
end_range=100
#targetnumber=generate_random(start_range,end_range)
#print (targetnumber)
def main():
targetnumber=generate_random(star_range,end_range)
number_of_guesses =0 #guarda o numero de tentativas do jogador
print ("Guess a number between 0 e 100.\n")
while True:
number_of_guesses +=1
guess = int(input("Guess #" + str(number_of_guesses) + ": "))
if guess > targetnumber:
print("\t Too High, try again.")
elif guess < targetnumber:
print ("\t Too low, try aain")
else:
print ("\t Correct")
print ("\t Congratulations. you got it in",number_of_guesses,"guesses.")
break
playagain=input("\n whould you like to play again? (y/n): ").lower()
while playagain != "y" or playagain != "n":
print ("Please print y to continue or n to exit")
playagain=input("\n whould you like to play again? (y/n): ").lower()
if playagain == "y":
continue
else:
break
My final output is always this one:
whould you like to play again? (y/n): n
Please print y to continue or n to exit
whould you like to play again? (y/n):
Can you please help me, letting me know what i am doing wrong?
Thank you very much
The condition evaluation is always True, hence you get into the loop again.
while playagain not in ['y', 'n']:
...
would satisfy your input check
Also, your continue/break condition is only evaluated if the while loop condition is met (i.e., the input was not correct)
It looks like you are continuing the second "while" loop and not moving back to your "game" code when you check the equality of the string "y" as the input, thus the question gets asked again. Instead, you should try refactoring the loops so that your game loop is nested inside the retry loop.

What can I do to fix my simple computer-player game code? Syntax Error

I'm new to Python and I wanted to practice doing loops because I’ve been having the most trouble with them. I decided to make a game where the user will pick a number from 0-100 to see if they can win against the computer.
What I have going right now is only the beginning. The code isn’t finished. But trying out the code I got a Syntax error where the arrow pointed at the colon on the elif function.
How do I fix this? What can I do?
I accept any other additional comments on my code to make it better.
Here’s my code:
import random
min = 0
max = 100
roll_again = "yes"
quit = "no"
players_choice = input()
computer = random.randint
while roll_again == "yes":
print("Pick a number between 1-100: ")
print(players_choice)
if players_choice >= 0:
print("Your number of choice was: ")
print(players_choice)
print("Your number is high.")
if computer >= 0:
print("Computers number is: ")
print(computer)
print("Computers number is high.")
if computer >= players_choice:
print("Computer wins.")
print("You lose.")
print("Would you like to play again? ", +roll_again)
elif:
print(quit)
end
Goal:
Fix computer-player game while learning more about python. Providing additional documentation on where to start would be helpful.
The reason you are getting an error pointing to elif is because elif needs a condition to check. You need to use if elif and else like this:
if a == b:
print('A equals B!')
elif a == c:
print('A equals C!')
else:
print('A equals nothing...')
Also, Python relies on indentation to determine what belongs to what, so make sure you are paying attention to your indents (there is no end).
Your code has more errors after you fix the if statements and indentation, but you should be able to look up help to fix those.
There are a lot of problems with your code. Here is a working version, hope it helps you understand some of the concepts.
If not, feel free to ask
import random
# min and max are names for functions in python. It is better to avoid using
# them for variables
min_value = 0
max_value = 100
# This will loop forever uless something 'breaks' the loop
while True:
# input will print the question, wait for an anwer and put it in the
# 'player' variable (as a string, not a number)
player = input("Pick a number between 1-100: ")
# convert input to a number so we can compare it to the computer's value
player = int(player)
# randint is a function (it needs parentheses to work)
computer = random.randint(min_value, max_value)
# print what player and computer chose
print("Your choice: ", player)
print("Computer's choice: ", computer)
# display the results
if computer >= player:
print("Computer wins. You loose")
else:
print("you win.")
# Determine if user wants to continue playing
choice = raw_input("Would you like to play again? (yes/No) ")
if choice != 'yes':
# if not
break
There are a lot of indentiation issues and the if and elif statements are used incorrectly. Also take a look at how while loops work.
Based on the code you provided here is a working solution, but there are many other ways to implement this.
Here is some helpful tutorials for you on if/else statements as well as other beginner topics:
Python IF...ELIF...ELSE Statements
import random
minval = 0
maxval = 100
roll_again = "yes"
quit_string = "no"
while True:
players_choice = int(input("Pick a number between 1-100:\n"))
computer = random.randint(minval,maxval)
#checks if players choice is between 0 and 100
if players_choice >= 0 and players_choice <= 100:
print("Your number of choice was: ")
print(players_choice)
#otherwise it is out of range
else:
print("Number out of range")
#check if computers random number is in range from 0 to 100
if computer >= 0 and computer <= 100:
print("Computers number is: ")
print(computer)
# if computer's number is greater than players number, computer wins
if computer > players_choice:
print("Computer wins.")
print("You lose.")
#otherwise if players number is higher than computers, you win
elif computer < players_choice:
print("You won.")
#if neither condition is true, it is a tie game
else:
print("Tied game")
#ask user if they want to continue
play_choice = input("Would you like to play again? Type yes or no\n")
#checks text for yes or no use lower method to make sure if they type uppercase it matches string from roll_again or quit_string
if play_choice.lower() == roll_again:
#restarts loop
continue
elif play_choice.lower() == quit_string:
#breaks out of loop-game over
break

Im unable to stop the input from taking place & play again loop middle of script

I am making a custom version of hangman for a college assignment using python, but currently I'm having an issue with two parts to my code, its a game of hangman.
I have included the entire code below so that if anyone can answer they have the full information from the code.
The issues I'm having are that this part of the code is not ignoring the input before so it still lets you guess multiple letters.
if len(guess) > 1:
print("Ye can't be cheatin' now, ye be using up ya guesses.")
failed += 1
The second issue I have is that once you win the game it doesn't ask if you want to play again properly (I have tried multiple methods to try to fix this including another while loop inside the if statement.
if failed == 0:
print("Ye be living for now")
print("The word was: " + myword)
print
...
while True:
...
if failed == 0:
print("Ye be living for now")
print("The word was: " + myword)
# Current Bug: Play again here, cannot use same line as end.
print
guess = input("guess a letter: ").lower()
if len(guess) > 1:
print("Ye can't be cheatin' now, ye be using up ya guesses.")
failed += 1
# Current Bug: still takes input into consideration when it shouldn't
guesses += guess
...
play_again = input("If you'd like to play again, please type 'yes' or 'y': ").lower()
if play_again == "yes" or play_again == "y":
continue
else:
play_again != "yes" or play_again != "y"
break
This should solve your problem of taking multiple letters as input
if len(guess) > 1:
print("Ye can't be cheatin' now, ye be using up ya guesses.")
failed += 1
# Current Bug: still takes input into consideration when it shouldn't
else:
guesses += guess
This will only add the input to guesses if its length is less than 1.
And if you want to ask the game to play again, after winning put your code in a while loop. Something like this:
play_again = 'y'
while(play_again == 'y' or play_again='yes'):
win = False
while(!win):
<your code for game, set win = True after winning>
play_again = input("Want to play again y or n: ").lower()
Edit: You can add failed along with win in the while loop as well.

Simulate rolling dice in Python?

first time writing here.. I am writing a "dice rolling" program in python but I am stuck because can't make it to generate each time a random number
this is what i have so far
import random
computer= 0 #Computer Score
player= 0 #Player Score
print("COP 1000 ")
print("Let's play a game of Chicken!")
print("Your score so far is", player)
r= random.randint(1,8)
print("Roll or Quit(r or q)")
now each time that I enter r it will generate the same number over and over again. I just want to change it each time.
I would like it to change the number each time please help
I asked my professor but this is what he told me.. "I guess you have to figure out" I mean i wish i could and i have gone through my notes over and over again but i don't have anything on how to do it :-/
by the way this is how it show me the program
COP 1000
Let's play a game of Chicken!
Your score so far is 0
Roll or Quit(r or q)r
1
r
1
r
1
r
1
I would like to post an image but it won't let me
I just want to say THANK YOU to everyone that respond to my question! every single one of your answer was helpful! **thanks to you guys I will have my project done on time! THANK YOU
Simply use:
import random
dice = [1,2,3,4,5,6] #any sequence so it can be [1,2,3,4,5,6,7,8] etc
print random.choice(dice)
import random
computer= 0 #Computer Score
player= 0 #Player Score
print("COP 1000 ")
print("Let's play a game of Chicken!")
print("Your score so far is", player)
r= random.randint(1,8) # this only gets called once, so r is always one value
print("Roll or Quit(r or q)")
Your code has quite a few errors in it. This will only work once, as it is not in a loop.
The improved code:
from random import randint
computer, player, q, r = 0, 0, 'q', 'r' # multiple assignment
print('COP 1000') # q and r are initialized to avoid user error, see the bottom description
print("Let's play a game of Chicken!")
player_input = '' # this has to be initialized for the loop
while player_input != 'q':
player_input = raw_input("Roll or quit ('r' or 'q')")
if player_input == 'r':
roll = randint(1, 8)
print('Your roll is ' + str(roll))
# Whatever other code you want
# I'm not sure how you are calculating computer/player score, so you can add that in here
The while loop does everything under it (that is indented) until the statement becomes false. So, if the player inputted q, it would stop the loop, and go to the next part of the program. See: Python Loops --- Tutorials Point
The picky part about Python 3 (assuming that's what you are using) is the lack of raw_input. With input, whatever the user inputs gets evaluated as Python code. Therefore, the user HAS to input 'q' or 'r'. However, a way to avoid an user error (if the player inputs simply q or r, without the quotes) is to initialize those variables with such values.
Not sure what type of dice has 8 numbers, I used 6.
One way to do it is to use shuffle.
import random
dice = [1,2,3,4,5,6]
random.shuffle(dice)
print(dice[0])
Each time and it would randomly shuffle the list and take the first one.
This is a python dice roller
It asks for a d(int) and returns a random number between 1 and (d(int)).
It returns the dice without the d, and then prints the random number. It can do 2d6 etc. It breaks if you type q or quit.
import random
import string
import re
from random import randint
def code_gate_3(str1):
if str1.startswith("d") and three == int:
return True
else:
return False
def code_gate_1(str1):
if str1.startswith(one):
return True
else:
return False
def code_gate_2(str2):
pattern = ("[0-9]*[d][0-9]+")
vvhile_loop = re.compile(pattern)
result = vvhile_loop.match(str1)
if result:
print ("correct_formatting")
else:
print ("incorrect_formattiing")
while True:
str1 = input("What dice would you like to roll? (Enter a d)")
one, partition_two, three = str1.partition("d")
pattern = ("[0-9]*[d][0-9]+")
if str1 == "quit" or str1 == "q":
break
elif str1.startswith("d") and three.isdigit():
print (random.randint(1, int(three)))
print (code_gate_2(str1))
elif code_gate_1(str1) and str1.partition("d") and one.isdigit():
for _ in range(int(one)):
print (random.randint(1, int(three)
print (code_gate_2(str1))
elif (str1.isdigit()) != False:
break
else:
print (code_gate_2(str1))
print ("Would you like to roll another dice?")
print ("If not, type 'q' or 'quit'.")
print ("EXITING>>>___")
This is one of the easiest answer.
import random
def rolling_dice():
min_value = 1
max_value = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "Yes" or roll_again == "Y" or roll_again == "y" or roll_again == "YES":
print("Rolling dices...")
print("The values are...")
print(random.randint(min_value, max_value))
print(random.randint(min_value, max_value))
roll_again = input("Roll the dices again? ")
rolling_dice()

How can I make my program return to the beginning in Python?

I'm a really new programmer, just programing for fun. I usually write my programs with a series of while loops to get to different sections of the program at different times. It's probably not the best way, but it's all I know how to do.
For example, I'm working on a little program that runs in a shell meant to solve an equation. Here's part of the program that's supposed to bring you back to the beginning.
while loop==4:
goagain = raw_input("Would you like to do the equation again? (Y/N)")
if goagain == "Y":
#Get values again
loop=2
elif goagain == "N":
print "Bye!"
#End program
loop=0
else:
print"Sorry, that wasn't Y or N. Try again."
I have it set so that while loop==2, it gets the values to put into the equation and while loop==0, nothing happens.
The problem I have, though, is that when my loop changes back to 2, the program just ends there. It doesn't want to back in the code to where I told it what to do while loop==2.
So what I need to know is how to get my program to go back to that section. Should I use a different method than the while loops? Or is there a way to get my program to go back to that section?
Thanks!
A better approach would be to do sometihng like this:
while True:
goagain = raw_input("Would you like to do the equation again? (Y/N)")
if goagain == "Y":
#Get values again
pass #or do whatever
elif goagain == "N":
print "Bye!"
#End program
break
else:
print"Sorry, that wasn't Y or N. Try again."
You will only iterate when loop is equal to 4. So for the example you have given loop=2 and loop=0 will have the same affect.
First of all, the loop condition states:-
while loop == 4:
This means the loop will be executed as long as the value of the variable 'loop' remains 4. But since you assign 2 to loop, the condition is not satisfied, and control goes out of the loop. One solution would be to change condition as:-
while loop == 2:
Or, another solution would be to remove the statement assigning 2 to loop altogether.
But, since you are getting the value Y/N in goagain, a better way would be:-
done = False
while not done:
goagain = raw_input("Would you like to do the equation again? (Y/N)")
if goagain == 'Y':
#Get values
elif goagain == "N":
print "Bye!"
#End program
done = True
else:
print"Sorry, that wasn't Y or N. Try again."
Why are you changing Loop to 2, when the user enters Y? If the user inputs yes, collect the values then execute your equation solver, then loop back.
while loop==4:
goagain = raw_input("Would you like to do the equation again? (Y/N)")
if goagain == "Y":
#Get values again
#Solve your equation here
elif goagain == "N":
print "Bye!"
#End program
loop=0
else:
print"Sorry, that wasn't Y or N. Try again."
You can do it as.. this program will check for a number is it prime and find factorial...
while input('Enter yes to start no to exit...: ') == 'yes':
print('Enter your choice [1] to find prime no. and [2] to calc. factorial.')
choice = int(input('Enter your choice: '))
num = int(input('Enter number: '))
def prime(number):
if number == (1 or 2 or 3 or 5 or 7):
print('%d is a prime number..:)' %number)
else:
for x in range(2,number):
if number%x == 0:
print('%d is not a prime number..' %number)
break
else:
print('%d is a prime number..' %number)
break
def fact(number):
fact = 1
for x in range(1,number+1):
fact = fact*x
print('Factorial of %d is %d' %(number,fact))
switch = { 1:prime , 2:fact}
try:
result = switch[choice]
result(num)
except KeyError:
print("I didn't get that...")
print('Bye...:)')

Categories

Resources