This is an exercise from Introduction to CompSci and Programming in Python from OCW MIT. I modified it a little bit. The problem is I want to stop the program when I reached the max wrong answer but it stops if I try two times. Why two times ? How can I fix this ? As a new starter should I ask every question here ? Thanks to all
n = 0
max_guesses = 3
n = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
if n == "left" or "Left":
print("You're out of lost forest")
while n == "right" or n == "Right":
n = input("You are in the Lost Forest\n****************\n****** ***\n :(\n****************\n****************\nGo left or right? ")
n =+ 1
for n in range (max_guesses):
break
print("Game over! You ran out of your lives")
There are a few errors that contribute to your code not working properly
Your variable n is the same as the value you get from the value you input best to separate those into different values to make it easier to avoid hard to detect errors
You need to have a condition that checks if n >= max_guesses.
Welcome to the community, we try to discuss the issues here rather than looking for a whole solution.
I suggest you to first learn the very basics of programming like the decision making, control flows (i.e if statements and loops).
Also, try to attempt the question, multiple numbers of times with different logics and inputs at runtime. it will give you a better understanding of logical analysis.
Here's one of the ways you could have added the logic.
#Maximum allowed guesses
max_guesses = 3
def func1():
#Input string 'left' or 'right'
in_str = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
#Number of attempts made
n = 1
if in_str.lower() == "left":
print("You're out of lost forest")
while in_str.lower() == "right":
in_str = input("You are in the Lost Forest\n****************\n****** ***\n :(\n****************\n****************\nGo left or right? ")
n += 1
if in_str.lower() == "left":
print("You're out of lost forest")
break
if n >= max_guesses:
print("Game over!!!")
break
print("Total attempts made by user: ",n)
func1()
I have attempted to fix your code however, I have had to remove the for loop and change the variable names. Hopefully, it helps.
n = 1
max_guesses = 3
a = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
if a.lower() == "left":
print("You're out of lost forest")
while a.lower() == "right":
if n == 3:
print("Game over! You ran out of your lives")
break
else:
a = input("You are in the Lost Forest\n****************\n****** ***\n :(\n****************\n****************\nGo left or right? ")
n += 1
Related
I have a code that allows a user to choose between 3 options
0- Beginner
1- Intermediate
2: Advanced
The code I have is:
if inp == 0:
out = "Beginner"
elif inp == 1:
out = "Intermediate"
elif inp == 2:
out = "Advanced"
else:
print("Invalid")
However, I'm wanting it so if a number greater than 3 was entered, it won't proceed to the second part.
The second part of the code I have is:
x=float(input("Choose a number between [0,90]"))
if x > 0 and x < 90:
print("Is Latitude in the North or South Hemisphere?")
else:
print ("Invalid")
Can someone provide some insight into how the condition is supposed to be?
Thank you!
You can do it with your code if you test for the existence of out before the second section.
You just need to initialise out before the if
out = ""
if inp == 0:
out = "Beginner"
elif inp == 1:
out = "Intermediate"
elif inp == 2:
out = "Advanced"
else:
print("Invalid")
Now, because out has become a global variable, you can test for whether or not out has been set. If out is not set, this next section is skipped.
if out:
x=float(input("Choose a number between [0,90]"))
if x > 0 and x < 90:
print("Is Latitude in the North or South Hemisphere?")
else:
print ("Invalid")
Realistically though, there's a ton of different ways you can do this. Personally, I'd probably use a function and then a return statement out of it to stop execution, but you can also break out and stop things that way or use some form of loop to wait for the variable you want.
The great thing and the frustrating thing about programming is there's normally more than one way to get it right.
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
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.
import random
from random import randint
print("Welcome to Brandon's Maze Game",
"You have to get 10 shields or find the exit to win",
"Good Luck :D")
counter = 0
shields = 3
fate = randint(1,2)
direction = input("You have come to a stop, do you want to turn Left(L) or Right(R)? ")
if direction == "L":
if fate == 1:
shields += 3
counter += 1
direction = input("You came across a chest, you now have ",shields, "! What way do you want to go next? Left(L) or Right(R)? ")
if fate == 2:
shields -= 1
counter += 1
direction = input("Uh oh, you got attacked and lost a shield, you now have ",shields," shields. Do you want to go Left(L) or Right(R)? ")
if direction == "R":
if fate == 1:
shields += 3
counter += 1
direction = input("You came across a chest, you now have ",shields, "! What way do you want to go next? Left(L) or Right(R)? ")
if fate == 2:
shields -= 1
counter += 1
direction = input("Uh oh, you got attacked and lost a shield, you now have ",shields," shields. Do you want to go Left(L) or Right(R)? ")
if counter == 10:
print("Congratulations, you made it to the end with ",shields," shields.")
I am making a maze game where the user has the option to go Left("L") or Right("R"), then the program makes a choice whether to make the player find a chest or be attacked. When the user finds a chat they get +3 shields, if they are attacked they lose 1 shield.
When I enter "L" or "R" it says: on line 19
TypeError: input expected at most 1 arguments, got 3.
Not sure what's going on as I am only inputting 1 value?,
Any help is appreciated.
You are giving input three arguments (string, int, string). Here's a demo with a function that prints its number of arguments:
>>> shields = 42
>>> def foo(*args):
... print(len(args))
...
>>> foo('fiz', shields, 'buzz')
3
What you want is to give one string to input:
>>> foo('fiz {} buzz'.format(shields))
1
input() is not like print(). The prompt is a single string, so concatenate strings with + (where you have comma). Note that you have to convert non-strings (like int) into a string.
print("Congratulations, you made it to the end with " + str(shields) + " shields.")
or string formatting:
print("Congratulations, you made it to the end with {:d} shields.".format(shields))
or use literal string interpolation if you are on Python 3.6
print(f"Congratulations, you made it to the end with {shields} shields.")
So the problem is that you had more than on parameter in the input function which unlike print you can not do. This can be solved easily using a plus sign to concatenate the strings together instead of a comma, but to do this you have to convert the int shield to a string by just putting str(shield) to convert it. this is what I have written python 2.7 so you might have to change a few things but it should all be there. I also added .upper() to the if statements so it can take both upper and lower case inputs. ps for python 3 you will do input() not raw_input(). sorry for writing in 2.7 i am not the good with 3. If you have any question feel free to ask
import random
from random import randint
print("Welcome to Brandon's Maze Game",
"You have to get 10 shields or find the exit to win",
"Good Luck :D")
counter = 0
shields = 3
fate = randint(1,2)
direction = raw_input("You have come to a stop, do you want to turn Left(L) or Right(R)? ")
if direction.upper() == "L":
if fate == 1:
shields += 3
counter += 1
direction = raw_input("You came across a chest, you now have "+str(shields)+ "! What way do you want to go next? Left(L) or Right(R)? ")
if fate == 2:
shields -= 1
counter += 1
direction = raw_input("Uh oh, you got attacked and lost a shield, you now have "+str(shields)+" shields. Do you want to go Left(L) or Right(R)? ")
if direction.upper() == "R":
if fate == 1:
shields += 3
counter += 1
direction = raw_input("You came across a chest, you now have "+str(shields)+"! What way do you want to go next? Left(L) or Right(R)? ")
if fate == 2:
shields -= 1
counter += 1
direction = raw_input("Uh oh, you got attacked and lost a shield, you now have "+str(shields)+" shields. Do you want to go Left(L) or Right(R)? ")
if counter == 10:
print("Congratulations, you made it to the end with "+str(shields)+" shields.")
from random import randint
random_number = randint(1, 10)
guesses_left = 3
# Start of the game
while guesses_left != 0:
def guess():
guess = int(input("What is your guess?"))
if guess > 10:
print ("Insert value between 1 and 10")
guesses_left += 1
guess()
if guess == random_number:
print ("You win")
break
guesses_left -= 1
else:
print ("You lose")
I am making this game where random numbers are formed and the user guesses the random number to win the game. However, I want to implement a safety that if the guess goes over 10, then it will print "enter value from 1 to 10" (see the code) and also add 1 to the guess left. I made this into a function so that the print message keeps displaying itself until the user puts all his guesses from 1 to 10. I am getting an error in that function itself :(
Also, how can I keep displaying the print message without functions? I know how to do it with while loop but is there a better way to do it?
You don't need the function at all, since you don't call it more than once.
A good way to think about the problem is that the program starts with a state of not knowing what the players guess is. You can represent this as 0. Then the while loop checks to see if the guess is >=1 AND <=20. Since the first time around, it's not, the loop would ask for a guess between 1 and 10.
Several notes here:
1) Remove the definition of the guess function outside of the while loop.
2) Watch the indentation. It's meaningful in Python
3) I merged the guess function with the main code, and it's still pretty readable
4) You can avoid having to increment guesses_left by 1 if you don't decrement it
5) I really hope you're trying to learn programming, and not having us complete your homework for you. Python can be very powerful, please continue to learn about it.
from random import randint
random_number = randint(1, 10)
guesses_left = 3
# Start of the game
win=False
while guesses_left>0:
guess=int(input("What is your guess?"))
if guess==random_number:
win=True
break
elif guess>10:
print("Insert value between 1 and 10")
continue
else:
guesses_left -= 1
if win:
print("You win")
else:
print("You lose")
from random import randint
random_number = 10 # randint(1, 10)
guesses_left = 3
# Start of the game
while guesses_left != 0:
guess = int(input("Guess a number between 1 and 10: "))
if guess > 10:
print "(error: insert a value between 1 and 10)"
guesses_left = guesses_left - 1 #add if you want to dock them a guess for not following instructions :)
else:
if guess is random_number:
print ("You win!")
break
else:
print "Nope!"
guesses_left = guesses_left - 1
if guesses_left is 0:
print "Wah Wah. You lose."
My code is probably more verbose than it needs to be but it does the trick. There are a couple problems with the way you wrote the script.
Like Hack Saw said, I don't think you need the function.
Indentation is off. This matters a lot to python
Good luck in class! :)