I'm making a guessing game or computer science in school where the number to guess is seven. I have tried using while loops and if elif else statements but it doesn't seem to want to make a conditional loop My code is as follows:
guess=int(input("Guess a number!"))
var=1
while var==1:
if guess !=7:
print("Try again")
else:
print("Well done")
Any help would be appreciated thanks. I need it in about a week and a half's time.
If you're trying to allow your player to continuously guess the input needs to be at the top of the while loop, before the conditional-branch
while(True):
guess = input("Make a guess: ")
if(guess == 7):
print(guess,"was correct!")
break
else:
print("Nope. Guess again.")
Of course, you could make it more interesting in a variety of ways.
guess=int(input("Guess a number!"))
var=1
while var==1:
if guess !=7:
print("Try again")
guess=int(input("Guess a number!"))
else:
print("Well done")
var=0 #set var to 0, to exit the loop
Try this. You need to exit the loop, and to do that, var needs to be set to 0.
Related
I tried making a rock-paper-scissors game, and to make sure that the user entered a number, I made a while loop. But after the user entered a number, the loop breaks but it won't keep running the game itself after it. How do I fix this?
main_choice = input('Please enter the number that matches your choice:\n')
#Make sure that user enters a number
while True:
try:
int(main_choice)
break
except:
main_choice = input('Please enter a NUMBER:\n')
continue
#Play
if main_choice == 1:
play_game()
I see others have placed the answer in the comments... but I'll place the full example in here. You need to convert your input into an integer to be able to compare it (or the 1 into a str).
The line that needs to change:
if main_choice == 1:
Change to:
if int(main_choice) == 1:
main_choice = input('Please enter the number that matches your choice:\n')
#Make sure that user enters a number
while True:
try:
int(main_choice)
break
except:
main_choice = input('Please enter a NUMBER:\n')
continue
#Play
if int(main_choice) == 1:
print("Game is now being played")
Gives the output:
Please enter the number that matches your choice:
1
Game is now being played
Regarding the code excerpt below, it is asking for input of either "land" the rocket or "orbit" the moon again. There is a dead end in the current code if you choose orbit twice, as the code doesn't go anywhere after that. I need an indefinite loop such that if the gamer enters "orbit," that the code loops back to choice5 and starts the sequence again until either "land" is chosen or any other answer given causes the game to end. Unless there is a better way to think about this... The code runs fine except if you answer "orbit" twice. If I'm on the right track, any ideas?
choice4 = input("> ")
if "FIRE" in choice4:
print("\n")
print("You have entered the Moon's orbit. After one full orbit you can begin landing approach.")
print("You are half way 'round in the dark side of the Moon.")
print("......................")
print("You are approaching the conclusion of the orbit. Are you going to make another orbit or attempt to land?")
print("\n")
else:
print("\n")
print("That is not a valid choice, try again.")
dead()
choice5 = input("> ")
if "orbit" in choice5:
print("\n")
print("Going 'round again...")
print("You are half way 'round in the dark side of the Moon.")
print("......................")
print("You are approaching the conclusion of the orbit. FIRE thrusters to to land, or orbit again.")
print("\n")
elif "land" in choice5:
print("\n")
print("FIRE thrusters when ready to begin descent.")
else:
print("\n")
print("What are you thinking?")
dead()
choice6 = input("> ")
if "FIRE" in choice6:
Okay, trying to make a simple game of Guessing Numbers but I can't find the mistake in this code. Still pretty new to python so probably the reason why but I can't figure out what is wrong with it.
import random
from time import sleep
def start():
print("Welcome To The Guessing Game \n Try to guess the number I'm thinking of \n Good luck!")
selectRandomNumber()
guessCheck(number, numberInput=1)
def restart():
print("Creating new number ...")
sleep(1)
print("OK")
selectRandomNumber()
guessCheck(number,numberInput=1)
def selectRandomNumber():
number = random.randint(0,1000)
tries = 0
return
def tryAgain():
while True:
try:
again = int(input("Do you want to play again? y/n:"))
except ValueError:
print("Couldn't understand what you tried to say")
continue
if again == "y" or "yes":
print("Awesome! Lets go")
restart()
elif again == 'n' or "no":
print("Goodbye!")
break
else:
print("Not a valid option")
continue
def guessCheck(number,numberInput=1):
while True:
try:
numberInput = int(input("What number do you think it is?: "))
except ValueError:
print("Couldn't understand that. Try again")
continue
if numberInput > number:
print("Too high")
tries += 1
continue
elif numberInput < number:
print("Too low")
tries += 1
continue
elif numberInput == number:
print("Congrats! You got my number")
tryAgain()
number = selectRandomNumber()
print(number)
start()
Every time I try to run the program I keep getting the same mistake.
It tells me:
Traceback (most recent call last):
File "python", line 60, in <module>
start()
File "python", line 8, in start
guessCheck(number, numberInput)
NameError: name 'number' is not defined
Don't quite understand what that means.
Some help would be appreciated. Thanks!
* UPDATE *
Was able to fix the part about defining the variable but now new problem happened where when I try to run
Same code as before but added
guessCheck(number,numberInput=1)
and also added the variable number at the end
number = selectRandomNumber()
print(number)
start()
when I run it I get this
None # this is from `print(number)` so instead of getting a number here I'm getting `None`
Welcome To The Guessing Game
Try to guess the number I'm thinking of
Good luck!
What number do you think it is?:
The Traceback is telling you this:
We got to start().
start() called guessCheck().
We tried to pass two pieces of information to guessCheck(): the variable names number and numberInput.
We don't have those variables defined yet! numberInput doesn't get defined until once we've already started guessCheck(), and number isn't actually defined anywhere.
As Manoj pointed out in the comments, you probably want number to hold the output of selectRandomNumber(). So, instead of just calling selectRandomNumber() in start(), try number = selectRandomNumber() instead.
You can add a print(number) on the line right after that to make sure number has a value assigned to it.
Now number has a value, going into your call to guessCheck(). That still leaves numberInput undefined though. You can set a default value for function arguments like this:
guessCheck(number, numberInput=1)
That way, when guessCheck is called but numberInput hasn't been defined yet, it will automatically give it the value 1 until you set it explicitly.
You may encounter other issues with your code the way it is. My advice would be to start really simply - build up your game from each individual piece, and only put the pieces together when you're sure you have each one working. That may seem slower, but trying to go too fast will cause misunderstandings like this one.
I am a beginner programmer. I want to create a game where user input affects the course of the game. I am kind of stuck on the very beginning.
def displayIntro():
print("You wake up in your bed and realize today is the day your are going to your friends house.")
print("You realize you can go back to sleep still and make it ontime.")
def wakeUp():
sleepLimit = 0
choice = input("Do you 1: Go back to sleep or 2: Get up ")
for i in range(3):
if choice == '1':
sleepLimit += 1
print("sleep")
print(sleepLimit)
if sleepLimit == 3:
print("Now you are gonna be late, get up!")
print("After your shower you take the direct route to your friends house.")
elif choice == '2':
print("Woke")
whichWay()
else:
print("Invalid")
def whichWay():
print("After your shower, you decide to plan your route.")
print("Do you take 1: The scenic route or 2: The quick route")
choice = input()
if choice == 1:
print("scenic route")
if choice == 2:
print("quick route")
displayIntro()
wakeUp()
i have a few bugs and I've tried to work them out on my own but I'm struggling.
1) I only want the player to be able to go back to sleep 3 times and on the third i want a message to appear and another function to run (havent made yet).
2) if the player decides to wake up i want whichWay() to run and it does but instead of exiting that for loop it goes right back to that loop and asks if the player wants to wake up again i have no idea how to fix this.
3) is there a better way i can go about making a game like this?
Thank you for your time and hopefully your answers.
The code below should work.
1. I moved the line 'choice = input("Do you 1: Go back to sleep or 2: Get up ")' into the for loop.
2. I added a break statement at the end of the elif block.
def wakeUp():
sleepLimit = 0
for i in range(3):
choice = input("Do you 1: Go back to sleep or 2: Get up ")
if choice == '1':
sleepLimit += 1
print("sleep")
print(sleepLimit)
if sleepLimit == 3:
print("Now you are gonna be late, get up!")
print("After your shower you take the direct route to your friends house.")
elif choice == '2':
print("Woke")
whichWay()
break
else:
print("Invalid")
How do you reset a while True loop. For example this is my code:
x=True
while x==True:
print ("Random Text")
randomtext= input()
if randomtext == "yes":
print ("hi")
x=False
elif randomtext == "no":
print("This is supposed to reset the loop")
#resets loop and prints Random Text again
print ("hi")
if x==True:
print ("placeholder text")
input()
I want it to reset the loop if "randomtext" is equal to yes. I want to reset it it in the middle of the loop. This is a very simple question but this is getting in my programming. Thank you.
I'm assuming that by resetting the loop you mean jumping code until reaching the start of the loop again. This is done with the "continue" keyword.
if randomtext == "yes":
continue
If you actually meant breaking out of the loop, you should instead use the "break" keyword.