An if else statement is not working python [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
I am making a text adventure game, but it keeps running the 1st variation in the code, even though I specified both scenarios:
print("By Rishi Suresh 2021")
print('')
print('')
print("A S h o r t R i d e")
print('')
print('')
print(" P L A Y ( P )")
print('')
print('')
if input()=="p":
print('')
print('')
print("Your journey begins on a bleak day. It's cloudy, and the windows of your apartment amplify the pitter patter of the soft rain outside. Your clothes are strewn about. You hear the landline ringing. You also see a diary.")
print('')
print('')
if input("What do you do? Do you pick up the diary (A) or answer the landline (B)? ")=="b"or "B":
print("")
print("")
print("You pick up the landline, and hear a voice on the other end. It is scratchy, and tells you to come to the London Underground. You pick up your clothes, a empty whiskey bottle and some glasses, and dress. You head outside. ")
elif input() == "A" or "a":
print("The diary reads:")
print('')
print('')
print("Dear Diary,")
print("Tommorow's the day. We have all the trucks ready, all the Tommy's, all the big men. This stop and shop will be the sucess of the century.")
print("The landline rings again. You pick up the landline, and hear a voice on the other end. It is scratchy, and tells you to come to the London Underground. You pick up your clothes, a empty whiskey bottle and some glasses, and dress. You head outside.")

This clause:
if input("What do you do? Do you pick up the diary (A) or answer the landline (B)? ")=="b"or "B":
will always pass, because "B" (and "A" or any non-empty string, for that matter) is a truthy value:
if "B":
print("Hey!")
if "A":
print("I pass, too!")
if "A really, really, really long string that goes on...":
print("So do I!")
if "":
print("I'll never print.")
This means if <anything> or "B": will always pass (provided evaluation of <anything> doesn't throw an exception or change control flow), because the second part of the or is satisfied. The == operator is binding to input (i.e. input(...) == "b" or "B" is (input(...) == "b") or "B"); you can't express "the result is a member of some set" in this way (i.e. x == 1 or 2 is (x == 1) or 2, not x in (1, 2)).
Assign the result of your input calls to some variable result, and then test result in ("b", "B") or result.lower() == "b" (ditto for the second case).

by asking for another input in the elif you are asking for another user input discarding the user's previous input,plus or "a" would cause the statment to always be true since you are not checking if the input is equal to "a", this would be better:
print("")
print('')
print('')
print("")
print('')
print('')
print(" ")
print('')
print('')
if input()=="p":
print('')
print('')
print("")
print('')
print('')
option=input(" a or b")
if option =="b"or option =="B":
print("")
print("")
print("")
elif option == "A" or option == "a":
print("The diary reads:")
print('')
print('')
print("Dear Diary,")
print("")
print("")

Related

airline reservation def help python

for my homework I am asked to create a airline reservation system. It asks if they would like to either create, cancel, display reservations, or exit the program. I am having trouble figuring out how to add the seats to the dictionary and still have them there when the code runs again. here is the basics of my code so far.
def reservation():
print("Please choose an option: ")
print("1. Reserve a Seat")
print("2. Cancel a Reservation")
print("3. Display Reservations")
print("4. Exit")
plane={}
co=int(input("Enter a choice: "))
#choose an option
if co==1:
seat=row+col
#check if seat has been taken if not reserve
if seat in plane:
plane[seat]=name
print("Seat row col has already been reserved by "+plane[key])
reservation()
else:
plane[seat]=name
print("Seat "+seat+" has been reserved for "+name)
print (seat+" "+plane[seat])
reservation()
elif co==2:
row=input("Row (1-25): ")
seat=row+col
if seat in plane:
del plane[seat]
print("The reservation for seat "+seat+" has been cancelled.")
input("Press enter to continue...")
else:
print("Seat "+seat+" is not currently reserved by anyone.")
input("Press enter to continue...")
elif co==3:
print("Reservations:")
for key in plane:
print(key+"\t"+plane[key])
elif co==4:
exit()
reservation()
In your program, I noticed that you attempt to continue calling your reservation function recursively in order to keep in acting like a loop. As noted in the comments you probably would be better off utilizing a loop for this exercise. Recursive function calls are good for things such as factorials, producing an exploded bill of materials, and such.
Also, I noticed that a few value assignments appeared to be backwards and actually would probably throw an error such as the following line of code.
if seat in plane:
plane[seat]=name
The "name" variable doesn't appear to be defined yet so that probably was cause the program to halt. With that in mind, I took a swing at doing some revisions and additions to the program in order for it to function in the spirit I believe you are after. Following is the sample code.
def reservation():
plane={}
while True:
#Choose an option
print("Please choose an option: ")
print("1. Reserve a Seat")
print("2. Cancel a Reservation")
print("3. Display Reservations")
print("4. Save Reservations")
print("5. Exit")
co=int(input("Enter a choice: "))
if co == 1:
row = int(input("Please enter a row: "))
col = int(input("Please enter a seat number (1 -6)"))
# Since lists start at index 0, the formula will be adjusted to accomodate
seat = (row - 1) * 6 + col - 1
# Check if seat has been taken if not reserve
if seat in plane:
name = plane[seat]
print("Seat", (seat + 1), "has already been reserved by " + plane[seat])
else:
name = input("Please enter your name ")
plane[seat] = name
print("Seat", (seat + 1), "has been reserved for", name)
print ((seat + 1)," ", plane[seat])
elif co == 2:
row = int(input("Row (1-25): "))
col = int(input("Seat# (1 - 6): "))
seat = (row - 1) * 6 + col - 1
if seat in plane:
del plane[seat]
print("The reservation for seat", (seat + 1), "has been cancelled.")
input("Press enter to continue...")
else:
print("Seat", (seat + 1), "is not currently reserved by anyone.")
input("Press enter to continue...")
elif co == 3:
print("Reservations:")
for key in plane:
print((key + 1), "\t", plane[key])
elif co == 4:
with open('plane.txt', 'w') as f:
for line in plane:
record = plane[line] + " " + str(line + 1)
f.write(record)
f.close()
elif co == 5:
break
reservation()
First off, I encapsulated the reservation logic within a "while" loop as suggested in the comments above. That replaces the recursive calls and replaces the "exit()" call with a simple "break" call for option #4. Next, since the plane seats are being treated like a list, I did some sleight of hand calculations to insure that the possible seat list would start at index "0". I subtracted "1" where needed for deriving and index value and added "1" back in for viewing purposes.
Here is just a brief bit of text from my terminal testing out the program.
#Una:~/Python_Programs/Reservations$ python3 Reservations.py
Please choose an option:
1. Reserve a Seat
2. Cancel a Reservation
3. Display Reservations
4. Save Reservations
5. Exit
Enter a choice: 1
Please enter a row: 4
Please enter a seat number (1 -6)2
Please enter your name Craig
Seat 20 has been reserved for Craig
20 Craig
Please choose an option:
1. Reserve a Seat
2. Cancel a Reservation
3. Display Reservations
4. Save Reservations
5. Exit
Enter a choice: 4
Please choose an option:
1. Reserve a Seat
2. Cancel a Reservation
3. Display Reservations
4. Save Reservations
5. Exit
Enter a choice: 5
Also, since you indicated that there was a need to save the reservations, I added a selection to the choices and a simple write to a text file for that. It is over simplified and you probably can find better solutions for that. Plus you will also probably want to add in some functionality to read the data back in. That could be a further embellishment to be worked on.
Anyway, please examine this code. Hopefully this will both clarify things for you plus give you ideas on how you might further embellish the functionality.
Regards.

How to either restart or end a game

I am trying to insert code at the end of my game to either restart or end the game. I'm not quite sure what I'm missing here.
This is where I'm at:
print("NIM: The Python Game")
print("Hello! My name is AI (the clever computer). \nIn this game, 2 other players will play against me and each other. \nThe player to go first will randomly choose between 30 and 50 stones in a pile to start the game.")
print("She\He will also be the first to remove the first stones. \nPlayers will then take turns at removing between 1 and 3 stones from the pile until a player removes the final stone. \nThe player to remove the final stone is the winner.")
player1=str(input("\nPlayer 1, what is your name and MIT ID? "))
print("Hello, " + player1.capitalize())
player2=str(input("\nPlayer 2, what is your name and MIT ID? "))
print("Hello, " + player2.capitalize())
player3="The computer"
howMany=0
stonesNumber=0
while True:
stonesNumber=int(input("\nNEW GAME \nHow many stones do you want to start with (between 30 and 50), " + player1.capitalize() + "? "))
if stonesNumber <30:
print("The number must be between 30 and 50!")
elif stonesNumber >50:
print("The number must be between 30 and 50!")
else:
print("The number of stones is ", stonesNumber)
while True:
print("\nIt's your turn, ",player1.capitalize())
while True:
howMany=int(input("How many stones do you want to remove?(from 1 to 3) "))
if howMany in [1,2,3]:
break
print("Enter a number between 1 and 3.")
while howMany>stonesNumber:
print("The entered number is greater than a number of stones remaining.")
howMany=int(input("How many stones do you want to remove?"))
stonesNumber=stonesNumber-(howMany)
print("Numbers of stones left: " + str(stonesNumber))
if stonesNumber==0:
print(player1.capitalize()," wins.")
break
print("\nIt's your turn, ",player2.capitalize())
while True:
howMany=int(input("How many stones do you want to remove?(from 1 to 3) "))
if howMany in [1,2,3]:
break
print("Enter a number between 1 and 3.")
while howMany>stonesNumber:
print("The entered number is greater than a number of stones remaining.")
howMany=int(input("How many stones do you want to remove?"))
stonesNumber=stonesNumber-(howMany)
if stonesNumber==0:
print(player2.capitalize()," wins.")
break
print("Numbers of stones left: " + str(stonesNumber))
print("\nIt's my turn!")
if stonesNumber % 3==0:
howMany=2
else:
howMany=1
stonesNumber=stonesNumber-(howMany)
if howMany == 1:
print("The computer has taken 1 counter")
if howMany == 2:
print("The computer has taken 2 counters")
if stonesNumber==0:
print(player3," wins.")
break
print("Numbers of stones left: " + str(stonesNumber))
print("\nThe game is over!")
answer=str(input("\nDo you want to play again?(y/n)"))
if answer == "y" or "yes":
print("\nRestarting the game")
else:
break
print("\nThanks for playing the game!")
The condition if answer == "y" or "yes": does NOT check if answer equals "y" or equals "yes". Due to semantics of OR-Operator it "transposes" to a piece of code like if "yes":, which is always true. Therefore it will always restart your game.
You will need to change it to that:
if answer == "y" or answer == "yes":
I am assuming the problem you are having now is that you cannot escape the loop regardless of what you answer at the end of the game.
The reason your game can never escape the while loop is because of this line
if answer == "y" or "yes":
Your above if statement is made up of two parts:
if answer == "y" (Evaluates to true or false depending on answer)
if "yes" (Evaluates to true every time)
Since its an OR case, where either the result will be true/false OR true, you will always end up with if answer == "y" or "yes" as true.
Therefore, you will always be stuck in the loop.
As per felix's answer, your solution would be to evaluate if answer == "y" OR answer == "yes" instead

How do I exit a loop in Python? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
I'm making a text-based adventure game for school, I've made this loop so if you don't give the answers allotted by the program, it will ask you over and over until you give it what it wants. I've made it loop, but I don't know how to exit the loop?
playerchoice =""
while (playerchoice != "wake" or "remain asleep" ):
playerchoice = input("Do you wake, or remain asleep? wake/remain asleep: ")
if playerchoice == "wake":
print ("'Finally! I was starting to think I'd need to call the undertaker. Try not falling asleep in my front yard next time you're feeling tired?'")
elif playerchoice == "remain asleep":
print ("'Are you dead?' they ask again, kicking you in the leg this time. Reluctantly, you sit up. 'Oh, good.'")
else:
print ("Please type a valid answer.")
you should use break to exit loop when desired input is given.
playerchoice =""
while True:
playerchoice = input("Do you wake, or remain asleep? wake/remain asleep: ")
if playerchoice == "wake":
print ("'Finally! I was starting to think I'd need to call the undertaker. Try not falling asleep in my front yard next time you're feeling tired?'")
break
elif playerchoice == "remain asleep":
print ("'Are you dead?' they ask again, kicking you in the leg this time. Reluctantly, you sit up. 'Oh, good.'")
break
else:
print ("Please type a valid answer.")
Another way is the following
choices = {
"wake": "'Finally! I was starting to think I'd need to call the undertaker. Try not falling asleep in my front yard next time you're feeling tired?'",
"remain asleep": "'Are you dead?' they ask again, kicking you in the leg this time. Reluctantly, you sit up. 'Oh, good.'"
}
playerchoice = ""
while (playerchoice not in choices):
playerchoice = input(
"Do you wake, or remain asleep? wake/remain asleep: ")
try:
print(choices[playerchoice])
except KeyError:
print("Please type a valid answer.")
possible choices are in a dictionary,
you simply check your loop for not valid answers.

Creating variable depended on another variable

I started learning python few days ago and im looking to create a simple program that creates conclusion text that shows what have i bought and how much have i paid depended on my inputs. So far i have created the program and technically it works well. But im having a problem with specifying the parts in text that might depend on my input.
Code:
apples = input("How many apples did you buy?: ")
bananas = input("How many bananas did you buy?: ")
dollars = input("How much did you pay: ")
print("")
print("You bought " +apples+ " apples and " +bananas+ " bananas. You paid " +dollars +" dollars.")
print("")
print("")
input("Press ENTER to exit")
input()
So the problem begins when input ends with 1. For example 21, 31 and so on, except 11 as the conclusion text will say "You bought 41 apples and 21 bananas...". Is it even possible to make "apple/s", "banana/s", "dollar/s" as variables that depend on input variables?
Where do i start with creating variable that depends on input variable?
How do i define the criteria for "banana" or "bananas" by the ending of number? And also exclude 11 from criteria as that would be also "bananas" but ends with 1.
It seems like this could be an easy task but i still can't get my head around this as i only recently started learning python. I tried creating IF and Dictionary for variables but failed.
You would want to have an if statement that checks whether the specified input falls above or equal to 1. This is simple to do and requires an if statement.
A simple way of doing this would be:
if apples == '1':
strApples = str(apples, 'apple')
else:
strApples = str(apples, 'apples')
...and so forth for all the other fruits.
You would then print your conclusion with:
print("You bought", strApples, "and", strBananas + ". You paid " +dollars +" dollars.")
Not the best way of displaying this though.
I would go for a line by line conclusion:
print("You bought: ")
if apples == '1':
print("1 apple")
else:
print(apples, "apples")
if bananas == '1':
print("1 banana")
else:
print(bananas, "bananas")
print("You paid", dollars, "dollars")
EDIT:
I think I now understand that you want every number ending in '1', that is not '11' to be displayed as singular.
This can be done using the following:
apples = input("How many apples did you buy?: ")
bananas = input("How many bananas did you buy?: ")
dollars = input("How much did you pay: ")
print("You bought: ")
if int(apples[-1]) == 1 and int(apples) != 11:
print(apples, "apple")
else:
print(apples, "apples")
if int(bananas[-1]) == 1 and int(bananas) != 11:
print(bananas, "banana")
else:
print(bananas, "bananas")
print("You paid", dollars, "dollars")
Looks like you might be interested by functions.
For example:
def pluralize(x):
for i in ["a", "e", "i", "o", "u"]:
# Is vowel
if x.endswith(i):
return x+"s"
# Is consonant
return x
print(pluralize("Hello World"))
Note: you may want to improve this function to handle things like ending with y, ending with x or s and so on.
EDIT:
https://pastebin.com/m2xrUWx9

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

Categories

Resources