Problems with a Python if-else statement - python

I am doing an assignment for an IT class. Very basic Python projects. I have no experience with it but am able to grasp what is going on most of the time. This project involves making choices involving random integer selections. I can get the options to work the way I want in the if-else format but the else command isn't responding the way I want. The options all load properly but if the choice is 1-3 for some reason the program then prints the "else" statement after printing the "if" statements. This doesn't happen if they choose option 4 or pick an invalid number(the reason for the else statement).
I didn't have this issue in the previous section of the program. I must have missed something, but I can't tell what it is. I should reiterate I am very much a beginner at this and am basically copy-pasting code as the assignment instructed, and then editing it to suit my needs.
interactions = ["Back Away Slowly","Point Towards the Chamber","Attack","Try To Communicate",]
import random
badchoice = random.randint(1,3)
loop = 1
while loop == 1:
choice=menu(interactions, "How do you decide to interact?")
print("")
if choice == 1:
print("You start to slowly back away from the man.")
print("You worry you are giving off the wrong attitude.")
print("")
if choice == badchoice:
loop=0
print("The stranger was already weary of your presence.")
print(interactions[choice-1], "was not the correct decision.")
print("He calls for help. Villagers and guards immediately surround you.")
print("You are thrown back into the chamber. Hitting your head, and getting knocked unconscious in the process.")
print("You are back where you started and the items have been removed.")
print("There is no escape.")
print("Lamashtu's Curse can not be broken.")
print("Game Over.")
else:
print("The stranger looks at you in confusion.")
print("")
# Choices 2 and 3 go here. Same code. Seemed redundant to post all of it.
if choice == 4:
loop=0
print("The stranger is weary of your presence, and can not understand you.")
print("You can see in his eyes that he wants to help,")
print("and he escorts you back to his home for the time being.")
print("He offers you some much needed food and water.")
print("You are no closer to understanding what curse brought you here.")
print("Perhaps tomorrow you will have more time to inspect your surroundings.")
print("In time you may be able to communicate enough with your host to explain your dilemma,")
print("but for now you are trapped 6000 years in the past with no other options.")
print("At least you've made it out alive thus far......")
print("To be continued...")
else:
print("Please choose a number between 1 and 4.")

The else only applies to the most recent if at the same level, ie the one for number 4. The other three if statements are all independent. So after checking each of those, it then goes to check if the choice is 4, and runs the else if it isn't.
You need to make these all part of the same statement, which you do by using elif for every if after the first. Like this:
if choice == 1:
...
elif choice == 2:
...
elif choice == 3:
...
elif choice == 4:
...
else:
...

Your logic is incorrect. Your final if statement directs choice 4 to it's True branch, and everything else to the False branch. Python does exactly what you told it to do. There is no logical reference to the previous blocks.
The logic you need is
if choice == 1:
...
elif choice == 2:
...
elif choice == 3:
...
elif choice == 4:
...
else:
print("Please choose a number between 1 and 4.")

Related

Making a simple menu within a loop to call upon functions, stuck on why it won't work

For a school project me and my group partner made a code, I tested each function in a separate test file to see if they worked and it all looks good, but the menu just isn't working as intended. My brain can't seem to figure out where I went wrong, I would love a second opinion on this.. thank you so much <3 Here is my code!
def mainmenu():
print("Hello! Welcome to The Sprint Project Company! Please choose from 1-5: ")
print("1. Simple IPO Program")
print("2. IFs and Loop sample")
print("3. Strings and dates")
print("4. Data files and Default Values")
print("5. Quit")
while True:
choice = input("Enter choice (1-5): ")
if choice == 1:
ipo()
elif choice == 2:
ifloop()
elif choice == 3:
stringsdates()
elif choice == 4:
datafiles()
else:
break
mainmenu()
Whenever I run this it just automatically ends. I even tested by putting a print section under the else but it just skips straight to ending the code. Thank you so much for looking at my question <3
There are two points on your code.
First, the function "input()" returns a string, hence you are comparing a STRING with an INTEGER, then it evalueates to False.
It is like you are comparing 1 with '1', and they are not the same.
Second, your function mainmenu() must be put inside the loop.
Make this two changes and it will work.
while True:
mainmenu() # Add the function here.
choice = int(input("Enter choice (1-5): ")) # Change here
if choice == 1:

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

How do I add different levels & a quit option to my guess a number game?

So I'm a freshman in high school trying to figure out Python coding, and I need to make a guess a number game.
My first level works fine, but I need to make it so it has 3 different levels, and a quit option. I don't understand these while loops.
I'm really sorry if I posted something wrong or this is an already asked question, but any help would be much appreciated!
Here's my code so far:
import random
print("let's play guess a number!")
myLevel=int(input("would you like to play level 1, 2, 3, or quit?"))
if myLevel == 1:
number1= random.randit(1,10)
guess1=int(input("guess an integer from 1 to ten"))
while number1!=guess1:
print
if guess1<number1:
print("guess is too low")
guess1=int(input("guess again! or would you like to quit?"))
#this is where i want to be able to quit
elif guess1>number1:
print("guess is too high!")
guess1=int(input("guess again! or would you like to quit?"))
#this is where i want to be able to quit
if guess1==number1:
print("you guessed it!")
if myLevel == 2:
nextumber2= random.randint (1,100)
guess2=int(input("guess an integer from 1 to 100"))
while number2!=guess2:
print
if guess2<number2:
print("guess is too low!")
guess2=int(input("guess again!"))
elif guess2>number2:
print("guess is too high!")
guess2=int(input("guess again!"))
print("you guessed it!")
Welcome to Python! Since you're new I'll go over the fundamentals of everything you need to learn to complete this game.
Your code looks good so far. Since your question is mainly about a while loop, you'll need to learn what exactly that does. A while loop is a block of code that first checks the provided condition, then executes the indented code block if the condition evaluates to true. Then, it checks the condition again, and executes the code again if it's still true. This continues until the condition evaluates to false.
x = 0
while x < 5:
print(x)
x += 1
Try this code out. It should print 0 to 4 then stop when x = 5.
What's actually happening:
x = 0
# loop starts here
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #false
# At this point, x is not longer < 5, so the repeating stops and the code continues to run as normal.
Imagine if you wanted to print numbers from 1 to 50. Would you rather have a loop, or do each number by hand like the above? In fact, if you want to print from 1 to x, where you don't know what x will be beforehand, you'll need a loop!
While loops are extremely powerful and are used all over the place. The idea is that you want to do something until some sort of flag or condition occurs, then stop doing the thing. I hope that makes sense.
Secondly, you need to learn about the input function.
x = input()
The input function is just a regular function that returns a string with the user input. If you want to make it into a number, then you have to typecast it to the type of number you want.
x = int(input())
You're already doing this. But what if you want a string?
Let's get back to your code:
myLevel=int(input("would you like to play level 1, 2, 3, or quit?"))
# User inputs "quit"
>> ValueError: invalid literal for int() with base 10: 'quit'
This happens because we already converted our input to an int. However, at no point are we doing any math with MyLevel. Here's a better way:
myLevel = input("would you like to play level 1, 2, 3, or quit?")
if myLevel == "quit":
exit() # this exits a python program entirely.
if myLevel == "1":
#do level 1 stuff
if myLevel == "2":
#do level 2 stuff
if myLevel == "3":
#do level 3 stuff
Our lives are made easier by not converting this variable. However, it's correct to convert the guess-a-number input() results because those need to be compared to other numbers.
Finally, this project is meant to teach you a very valuable lesson! Don't repeat yourself in the code. If you find yourself doing ANYTHING twice (or any number of times more than one), then use a function, loop, or other construct to condense it. We'll use your project as an example. I updated the code to get it working.
if myLevel == 1:
number1= random.randit(1,10)
guess1=int(input("guess an integer from 1 to ten"))
# This whole while loop needs to be within the "if" statement's indented block.
# Why? Because we only want to execute the code *if* we're on level 1.
while number1!=guess1:
print(str(number1) + " isn't correct.") #fixed this
if guess1<number1:
print("guess is too low")
guess1=int(input("guess again! or would you like to quit?"))
elif guess1>number1:
print("guess is too high!")
guess1=int(input("guess again! or would you like to quit?"))
# The last if statement isn't needed so I took it out.
# Why? Because if the loop ends, it's because guess1==number1. So our condition
# always returns true. Therefore, we can just move the print statement outside of the
# while loop.
print("you guessed it!")
This is a fine start and it should be working. Now, what do we do for level 2? The first thing that comes to mind is to copy paste this whole code block... but that would be repeating ourself! We're going to reject that idea straight out because we don't repeat ourselves.
Instead, let's use a function to wrap up the core of the game into a nice little repeatable action. Functions are just repeatable actions.
# define a function with a variable to hold the highest possible guess
def guess(max):
# get a random number based on our max
number = random.randint(1,max)
guess = int(input("guess an integer from 1 to " + str(max)))
while number != guess: # Guess is wrong
if guess < number:
print("guess is too low")
elif guess > number:
print("guess is too high!")
# Since guess is wrong, we can just assume we'll always do this.
# I removed the int() wrapper for the next step
guess = input("guess again! or would you like to quit?")
# Adding "quit" as an option:
if guess == "quit":
exit()
else:
guess = int(guess) # Now we can convert to int for our comparisons.
print("you guessed it!")
With this defined, now we just need to call the function itself at the correct difficulty.
if myLevel == "1":
guess(10)
if myLevel == "2":
guess(100)
if myLevel == "3":
guess(500)
If you're still alive after reading all this, hopefully you noticed a problem here -- we're repeating ourselves with 3 different if statements. We can do better, but that's a lesson for another day!
tl;dr:
1) Input returns a string, so you converted it to an int immediately. However, a string of "quit" is a valid choice and this will give you an error if you convert it to an int. Instead, test for "quit" first, then convert to an int if needed.
2) A while loop is for repeating something until some sort of condition is cleared. Loops and if statements can be nested within other statements. Think about when you want your code to run and honestly just practice a bit to make this more natural.
3) If you're repeating something in your code (copy/pasting similar things over and over again), strongly consider making a function or loop or something similar to do the work for you!
For the quit it's simple. Either use quit(), or, if you don't want to reload the program, put everything in a while loop and have the quit function set it to false, and then true after a while. For the 3 levels, you could either write 3 entirely separate programs or use if statements to change numbers or something. I'm not sure that would work, though.
As for your while problem, just use while some_variable='whatever_you_want': and you're done.

Procedure in if loop not working even though condition is met [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
I have made this code to emulate a rock paper scissors game. I have a procedure which has the main game, and when I run this by itself without the if loop at the end, it works. However, when I try to validate whether or not the user entry is numerical, it does not print the correct message. Here is the full code:
import random
def game(choice):
number = random.randint(1,3)
if choice == 1 and number == 2:
print("You lose.")
if choice == 1 and number ==3:
print("You win.")
if choice == 1 and number == 1:
print("It is a draw")
if choice == 2 and number == 3:
print("You lose.")
if choice == 2 and number ==1:
print("You win.")
if choice == 2 and number == 2:
print("It is a draw")
if choice == 3 and number == 1:
print("You lose.")
if choice == 3 and number ==2:
print("You win.")
if choice == 3 and number == 3:
print("It is a draw")
x = input("Choose 1 (rock), 2 (paper) or 3 (scissors).")
digit = x.isdigit()
if digit == True:
game(x)
By the way, there is no error message, the procedure just does not work!
First of all, there are a few issues with your code. If you wish to ignore, skip to Error Handling for answer to your question. You will find it in there.
Naming Variables
Your variables do not tell a person reading your code what they are. If you showed someone the word number, they would not know that it is what the computer chooses in rock paper scissors. Same with choice (who's choice?) and even more so x. So why don't we name them computer_choice, user_choice and choice respectively. I know these are a bit longer to type, but it is worth sacrificing a few extra keystrokes for a bit more clarity. Also notice that I used snake_case name formatting as per usual Python standards.
Repetitiveness/ game()
Your game function could do with a bit of re-doing. All you need is a general 'formula' for winning and losing. In this case, losing is when (thanks to #Brett Beatty) if computer_choice == (user_choice + 1) % 3, drawing is when computer_choice == user_choice and winning is everything else. Also, when your code is being played, the user only knows if they have won or lost, and not what the computer chose, so to add a bit more clarity, I added a list and another print() line. This feature is also useful to test code. Additionally, use zero-based variable values, such as in the computer_choice and user_choice variables. This is useful when converting values to list indexes. Below is a revised version of your code that i have made which includes all points above (I have also made it a function, as you will see below - I just think it looks better):
import random
def game(user_choice):
user_choice -= 1
rps = ["Rock", "Paper", "Scissors"]
computer_choice = random.randint(0, 2)
print("You: {} Computer: {}".format(rps[user_choice], rps[computer_choice]))
if user_choice == computer_choice:
return 0
elif computer_choice == (user_choice + 1) % 3:
return -1
else:
return 1
Error Handling
To make sure the user enters an integer, you would have to add int() around the input statement. However, this alone would return ValueError if the value entered by the user is not an integer, and this is a problem. However, there is a way to fix this using try: except: else: blocks, as you will see below. This is what you would need to decide if the value is an integer, it also prints the correct message when it is not. I also think this is what you wanted for if digit == True(FYI you would only need if digit if you were to do it that way).
def main():
while True:
try:
value = int(input("Choose 1 (rock), 2 (paper) or 3 (scissors):"))
except ValueError: # If any part of the code in the try block raises a ValueError
print("Not an integer")
else: # If error is not raised
if not 1 <= value <= 3: # If value is not between 1 and 3
print("Must be between 1 and 3")
else:
result = game(value) # sets result to return value from game()
break
if result == 1:
print("You Win")
elif result == -1:
print("You Lose")
else:
print("It's a Draw")
And Finally, the 'if loop'?
Let me just make this clear. There is no such thing as an if loop!!! An if statement runs code **ONCE** if a certain condition is True. I think what you want is a while loop. This runs code **REPEATEDLY** as long as a certain condition is True. In the code below, I created a while True loop, which runs the code each time the user types in "y", and breaks from the loop if not.
Also, use if __name__ == '__main__'. It exists in Python so that Python files can act as either reusable modules, or as standalone programs. It also looks more complex, if you want to look smart.
if __name__ == '__main__':
while True:
main()
if input("Again? Yes(y) No(Anything else): ").lower() != 'y':
break
Example Output (ignore colours):
Choose 1 (rock), 2 (paper) or 3 (scissors):1
You: Rock Computer: Scissors
You Win
Again? Yes(y) No(Anything else): y
Choose 1 (rock), 2 (paper) or 3 (scissors):3
You: Scissors Computer: Scissors
It's a Draw
Again? Yes(y) No(Anything else): y
Choose 1 (rock), 2 (paper) or 3 (scissors):2
You: Paper Computer: Paper
It's a Draw
Again? Yes(y) No(Anything else): n
Process finished with exit code 0
Also, for the OP, if you haven't already, I would recommend downloading Pycharm. It is completely free, and makes coding a lot easier. It also improves presentation too. It picks up on some of the things mentioned above, as well as keeping your code in line with PEP guidelines.

how to loop back to certain code

So I am creating a survival game, and I need to know how to loop back to a certain point in the code. I have wrapped the entire game in a function, but--now when in run it-- it just restarts itself.
import random
def game(choice1):
print "You need to build a fire. the recipe is 5 stick and 3 coal."
choice1 = raw_input("There are trees to your left and rocks to your right. Which way will you go?")
if choice1 == "left" or choice1 == "Left":
choice2a = raw_input("You go to the tree. Would you like to punch it?")
if choice2a == "yes" or choice2a == "Yes":
R = random.randint(1,11)
print "You punched the tree " + str(R) + " times."
if R <= 5:
print "It did not fall down"
elif R > 5:
R2 = random.randint(0, 5)
print"It fell down. It dropped " + str(R2) + " sticks."
elif choice2a == "no" or choice2a == "No":
game(choice1)
if choice1 == "right" or choice1 == "Right":
choice2b = raw_input("You go to the rocks. Would you like to pick up the coal in them?")
return game(choice1)
I imagine you want to loop back to the first raw_input statement, if that is the case, you can use while loops as Celeo has pointed above.
You will have to use an exit condition to escape the while loop once you are done looping.If you want to loop back to different parts of the program then I would recommend you write the code block as functions and call them as necessary.
Try reading about while loops here:
http://www.tutorialspoint.com/python/python_while_loop.htm
A while loop lets you repeat a code depending on a condition (while a condition is met, go back to the start).
To make such a game I would recommend using a (decision) state-machine. If the game is in a certain state, the player is asked the corresponding question and depending on the answer the game is moved to an other state. Each state should be implemented independently from the others, i.e. avoid deeply nested if/else constructs, this avoids errors and helps you to stay on top of things. You can also visualize/draw the game decision plan as a graph, where each node represents a state (or decision to be made) and each decision connects the node to an other state.
For your concrete example, you also need to keep track of what the player has collected so far, which is essentially an other state-system.
To implement such a state-based-game you can (ab-)use the python concept of generators. A generator is basically an object that returns 'items' with yield when queried with next(). A generator can provide a finite or an infinite amount of 'items', it can also return 'items' from an other generator with yield from.
Here an example implementation of your game:
Be aware that this code works only with python3! It should be possible to translate it into python2 (perhaps even automatically), but I feel no strong urge to do so ATM ;)
import random
import collections
def main(backpack):
print("You need to build a fire. the recipe is 5 stick and 3 coal.")
print("You have the following items in your backpack:")
for k,v in backpack.items():
print(' % 3d %s' % (v,k))
#TODO: add check if we have collected enough here
yield from choice1(backpack)
# tree or stone
def choice1(backpack):
answer = input("There are trees to your left and rocks to your right. Which way will you go?")
if answer.lower() in ('l', 'left'):
yield from choice2a(backpack)
elif answer.lower() in ('r', 'right'):
yield from choice2b(backpack)
else:
print('I could not understand you. Answer with either "left" or "right".')
yield from choice1(backpack)
# punch or not
def choice2a(backpack):
answer = input("You go to the tree. Would you like to punch it?")
if answer.lower() in ('y', "yes"):
R = random.randint(1,11)
print( "You punched the tree " + str(R) + " times.")
if R <= 5:
print("It did not fall down")
else:
R2 = random.randint(0, 5)
print("It fell down. It dropped " + str(R2) + " sticks.")
backpack['stick'] += R2
yield from choice2a(backpack)
elif answer.lower() in ('n', "no"):
yield from main(backpack)
else:
print('I could not understand you. Answer with either "yes" or "no".')
yield from choice2a(backpack)
# pick up or not
def choice2b(backpack):
answer = input("You go to the rocks. Would you like to pick up the coal in them?")
# TODO: implement this
yield main(backpack)
if __name__ == '__main__':
backpack=collections.defaultdict(int)
while True:
next(main(backpack))
Each of the functions is a generator-function, i.e. a function that returns a generator. Each of them represents a game-state that requires a decision. The player-state (i.e. what the player has collected so far) is passed along as backpack which is a dictionary that contains the amount per item.
(yield from xyz() could be interpreted as a kind of goto command.)

Categories

Resources