Trouble ending a multi if statement to catch all - python

I am currently attempting to write my first program/app in Python by creating a tool for my partner to use when we play a card game. I have just started to pick up learning to program seriously, so it maybe a rookie mistake I have missed, but I can't seem to catch "anything else" via input to divert the user a response.
Here is my code:
def counting_up ():
round_total = 0
while True :
global game_level
cards = input("Enter Card: \n")
if cards.upper() == "A" or cards == "2" :
round_total += 20
if cards == "3" :
round_total += 3
if cards == "4":
round_total += 4
if cards == "5" :
round_total += 5
if cards == "6" :
round_total += 6
if cards == "7" :
round_total += 7
if cards == "8" :
round_total += 8
if cards == "9" :
round_total += 9
if cards == "10" or cards.upper() == "J" or cards.upper() == "Q" or cards.upper() == "K" :
round_total += 10
if cards == "0" :
game_level += 1
if cards.upper() == "END" :
game_state = 1
break
else :
print (f"{cards}, is not a valid value, please enter a valid value!")
print ("Your score this round was " + str(round_total))
return round_total
When testing it doesn't seem to go through the prior logic checks before it comes to the conclusion that its an invalid value. NOTE this entire function was working as intended and does if i remove the else: statement at the end. Is there anything in python similar to a case statement in java that would work?
Thanks in advance

With multiple if statements at the same level, python will check each conditional statement. If you want it to ignore subsequent statements when a prior one has been satisfied, use elif:
def counting_up(game_state, game_level, round_total=0):
"""Request and add input card face value to score repeatedly till end."""
while True:
cards = input("Enter Card: \n")
if cards.upper() == "END":
game_state = 1; break
elif cards == "0":
game_level += 1
elif cards.upper() in ("A", "2"):
round_total += 20
elif cards.isnumeric():
round_total += int(cards)
elif cards.upper() in ("J","Q","K"):
round_total += 10
else:
print(f"{cards}, is not a valid value, please enter a valid value!")
print(f"Your score this round was {round_total}.")
return round_total

Only the first 'if' should be an 'if' the rest of the 'if' statements should be replaced by 'elif' (else if) statements.

"else" always checks the most recent "if" and then evaluates. So if you only enter "END" without having the break statement, the program won't go to the else statement. So anything you enter, other than "END", prints the result along with the result of the else statement.
Hence use "elif" for the statements other than the first "if" statement so that it checks the condition. If satisfied, prints the result else it moves on to the next statement

You can use dict
def counting_up ():
round_total = 0
while True :
global game_level
cards = input("Enter Card: \n")
card_dict = {'A':20,'2':20,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}
if cards.upper() in card_dict.keys():
round_total += card_dict[cards.upper()]
elif cards == "0" :
game_level += 1
elif cards.upper() == "END" :
game_state = 1
break
else :
print (f"{cards}, is not a valid value, please enter a valid value!")
print("Your score this round was " + str(round_total))
return round_total

Related

Python score system

I am writing a program were add and subtract numbers from an integer to keep score. The admin and subtracting is working but I am trying to add a feature that if you add number after the word add or subtract it changes by that number, but I can’t get that to work.
cont = True
score = 0
num = False
while cont == True:
q = input("add, subtract, or end: ")
for char in q:
n = q.isnumeric()
if n == True:
num = True
num2 = q
if num == False:
if q.lower() == "add":
score += 1
elif q.lower() == "subtract" or q.lower() == "sub":
score -= 1
elif q.lower() == "end":
cont = False
print(score)
elif num == True:
if "add" in q.lower():
score += num2
elif "subtract" in q.lower() or "sub" in q.lower():
score -= num2
elif q.lower() == "end":
cont = False
print(score)
I expect it to add one if you type add subtract one if you type sub or subtract and end the program if you type end, that works the part that I expected and doesn’t work is that it is supposed to detect if there is a number in the string using the isnumeric() function and add or subtract that number.
Your code simplifies neatly to something like:
score = 0
while True: # Infinite loop; we'll use `break` to end
print("Score:", score)
q = input("add, subtract, or end: ").lower().strip() # lower-case, remove whitespace
words = q.split() # Split entry by spaces
verb = words.pop(0) # Remove first word
if verb == "end":
break
if words and words[0].isnumeric(): # If there is a second word and it's numeric
value = int(words[0])
else: # Otherwise default to 1
value = 1
if verb == "add":
score += value
elif verb == "subtract":
score -= value
else:
print("Unknown verb", verb)

Stuck inside the while loop

I was writing code for Rock Paper Scissors game in Python. This is kinda tournament style (3 rounds)
But it just keeps playing after the 3rd round is over.
def play():
player = input("Please type 'r' for Rock, 'p' for Paper and 's' Scissors: \n").lower()
while (player != 'r') and (player != 'p') and (player != 's'):
player = input("That is not an valid option. Please try again:\n").lower()
computer = random.choice(['r', 'p', 's'])
commands = {
"r" : "Rock",
"p" : "Paper",
"s" : "Scissors"
}
if player == computer:
print("It's a draw! Game Over.")
return("Draw")
elif user_win(player, computer):
print(f"You won! The computer used {commands[computer]} against your {commands[player]} and lost.")
return("Won")
print(f"You lost! The computer used {commands[computer]} against your {commands[player]} and won.")
return("Lost")
def user_win(player, computer):
# r > s, s > p and p > r
if (player == 'r' and computer == 's') or (player == 's' and computer == 'p') or (player == 'p' and computer == 'r'):
return True
print("Hello, Player! Choose your weapon.")
count, user, comp = 0, 0, 0
while count < 3:
count =+ 1
outcome = play()
if outcome == 'Won':
user =+ 1
elif outcome == 'Lost':
comp =+ 1
if user > comp:
print(f"You win. You: {user} Computer: {comp}")
elif comp > user:
print(f"You lost. You: {user} Computer: {comp}")
else:
print(f"Its a draw. You: {user} Computer: {comp}")
This is the full code. Below is the part which have problem (if i understood it right)
while count < 3:
count =+ 1
outcome = play()
if outcome == 'Won':
user =+ 1
elif outcome == 'Lost':
comp =+ 1
Ps: This is my first time posting on stackoverflow so sorry if i posted in wrong way.
The error is count =+ 1. Try count += 1, that should work.
(As a little background: count =+ 1 will simply assign a value of 1 to the variable count. After that, count never chnages, so it can never reach 3, and you're stuck in an infinite loop. The increment you want is count += 1.)
When you do
count =+1, it just assigns the value +1 to variable count, which is less than the required exit value of 3. You can try to log the value of count across iterations for a better understanding.
Fix:
Change the =+ to += for what I suppose is your requirement, ie to increment value by 1 on each iteration. Read through What is the difference between '+=' and '=+'?

Not sure why my if statements to check the first character of varaible state is only running the first statement

I know my code is a little messy, I am going to clean it up once I can figure out why the if statements to check state[0] is only printing the first statement. I tried moving it around the codeblocks and indentations but still only getting the first if statement to print. Any advice/help would be great. Just came back to python, been learning java/SQL, this class is going back to python, so I'm a little off at then moment. Thanks
ballotLoop = input("Hey there, are you here for the voter ballot? Exit to stop.\n")
while ballotLoop != "exit":
lastName = input("Please enter your last name.\n")
firstName = input("Please enter your first name.\n")
age = int(input("Please enter your age.\n"))
usCit = input("Are you a United States Citizen?\n")
if usCit == "yes":
if age >= 18 and age < 80:
print(firstName, lastName +". Great you are over 18 and a US citizen\nYou may proceed with the form.\n")
elif age > 0 and age < 18:
print("I am sorry you are not old enough to complete this voter form.")
elif age > 80:
print("Error age does not make sense.\n")
elif age < -1:
print("Error age does not make sense.\n")
state = input("What state do you currently reside in?\n")
zipcode = input("What is your current zipcode\n")
print("Alright so to make sure everything is correct we have the following.\n"\
+ firstName, lastName + ", you are "+ str(age) + " years old.\nYou marked " + usCit + \
" for being a US citizen.\nYou currently reside in " + state + " and your zipcode is " + zipcode +"\n")
if state[0] == "a" or "c":
print("You should recieve your ballot in 1 week")
elif state[0] == "t" or "d":
print("You should recieve your ballot in 4 weeks")
elif state[0] == "m" or "l":
print("You should recieve your ballot in 2 weeks")
elif usCit == "no":
print("I am sorry but you may not complete this form, I am going to have to ask you to leave.")
ballotLoop = input("Would you like to fill out another ballot? Exit to stop.\n")
if ballotLoop == "exit":
print("Thank you for you vote today, every little bit makes a difference!!")
Solution
state[0] == "a" or state[0] == "c" instead of
state[0] == "a" or "c"
and so on for next two logics.
Explanation
There are two parts per and / or keywords in python. The left part (any boolean expression) to the keyword is compared with the right part (another boolean expression). And you know that boolean expression is either True or False.
Keeping these in mind let's break down your if statement.
if state[0] == "a" or "c":
print('...')
Here, the boolean expressions are:
state[0] == "a"
Possible results: Either True or False
"c" which is always True in python. Check this.
So under the hood your logical operation in the if statement is state[0] == "a" or True
Which will always return True, satisfying the first if statement everytime.
Long story short, explicitly write:
state[0] == "a" or state[0] == "c"

Python while loop won't end

So I have a code that project the user's bill. I put it on a loop so that it keeps repeating itself until the user don't want to continue.
here is my code:
status = True
def kill() :
confirm = input("Again? (Y/N) : ")
if confirm == "n":
status = False
while(status):
plan_option = input("Which plan are using ? (a/b/c/d/e): ").lower()
if plan_option == "a" :
print("Your current bill is : $90")
kill()
else :
data_amount = float(input("How much data have you used? "))
print("===========================")
def plan_b(x) :
if x < 10 :
print("Your current bill is : $60")
elif x > 10 :
total = 60 + x*10
print("Your current bill is : $", total)
def plan_c(x) :
if x < 5 :
print("Your current bill is : $40")
elif x > 5 :
total = 40 + x*12
print("Your current bill is : $", total)
def plan_d(x) :
if x < 2 :
print("Your current bill is : $30")
elif x > 2 :
total = + x*15
print("Your current bill is : $", total)
def plan_e(x) :
total = x*18
print("Your current bill is : $", total)
if plan_option == "b" :
plan_b(data_amount)
elif plan_option == "c" :
plan_c(data_amount)
elif plan_option == "d" :
plan_d(data_amount)
elif plan_option == "e" :
plan_e(data_amount)
kill()
So my questions are :
If I enter "n" when the code prompt me, the script won't stop and kept going back to plan_option.
even though the code stops (eventually), it kept prompting me "Again? (Y/N) : " before it kills itself.
Where did I do wrong?
Also, am I over-engineering here?
You have to declare 'status' as a global variable inorder to update value to
"status = False" in your kill method.
You can do 2 things here:
1. Declare status as global variable
2. Return "status" (which is a local variable) from kill method
You can check the tutorials on how to use global variables. Am not going to provide you the code (for your own good ofcourse).
def kill() :
confirm = input("Again? (Y/N) : ")
if confirm == "n":
status = False
This creates a local variable named status, and sets that. The global variable of the same name is unaffected.
Add global status in the function so that it uses the global one instead:
def kill() :
global status
confirm = input("Again? (Y/N) : ")
if confirm == "n":
status = False
I think that you should use less complicated way:
try this model
===>here your function a()<===
def a():
print("A plan in action")
while True:
===> your loop code <===
your_input = input("> ")
your_input = your_input.upper()
if your_input == 'N':
print("\n** You escaped! **\n")
break
elif your_input == "A":
print("\n** Plan A lunched ! **\n")
a()
===>you can use 'break' to stop the loop here <===
else:
continue
Two revisions:
Use global status in kill()
If you are comparing confirm == "n", then convert n to lower while taking input
Try this:
def kill() :
confirm = input("Again? (Y/N) : ").lower()
if confirm == "n":
global status
status = False

Indent Error with my battleship.py script

I'm trying to create a simple two player game like the classic Battleship. Hence I'm beginning to learn Python and I'm keeping it simple. I have created a 5x5 grid and I want the players (2) to be able to place one ship 1x1 anywhere on the board. Then they take turns guessing where the other person placed their ship.
When I compiled my code I got an indent error on line 61 "else: ". I'm aware that the "H" and "M" for hit and miss will overlap since I'm outputting it to the same playing board.
I guess what I need help with is the while loops in my code.
import sys
#////////////////////////////Setting up board////////////////////////////////////
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
#///////////////////////////Getting input//////////////////////////////////////////
def user_row():
get_row = raw_input("Enter ship row between 1 and 5")
#Not shure if this is the best way of checking that the input is an int
if int(get_row) == False:
print "You must enter an integer between 1 and 5"
get_row = raw_input("Enter ship row...")
if int(get_row) == False:
sys.exit()
def user_col():
get_col = raw_input("Enter ship col between 1 and 5")
if int(get_col) == False:
print "You must enter an integer between 1 and 5"
get_col = raw_input("Enter ship col...")
if int(get_col) == False:
sys.exit()
#/////////////////////////Intro//////////////////////////////////////////////////////
print "Let's play Battleship!"
print "This is your ocean"
print_board(board)
#////////////////////////Placing ships//////////////////////////////////////////////
print "Player 1 your up!"
print "Player 2 look away!"
print "Place your ship..."
#Not shure if this will call the two functions chronologic and store them as index 0 and 1 in my array. That is what I want it to do
user1_ship = [user_row(), user_col()]
print_board(board)
print "Player 2 your up!"
print "Player 1 look away!"
print "Place your ship..."
user_2 = [user_row(), user_col()]
#///////////////////////guesswork?//////////////////////////////////////////////////
#Maybe while loops inside while loops is not the best way of running the code over and over until someone sinks the other persons ship
#What Im expecting is the first inside while loop to break the outer loop if the player hits the other players ship otherwise break itself. Likewise with the second inner loop.
while True:
while True:
print "Player 1 your turn"
user1_guess = [user_row(), user_col()]
if user1_guess == user2_ship:
board[user1_guess[0]][user1_guess[1]] == "H"
print "PLAYER 1 WINS!"
break
else:
board[user1_guess[0]][user1_guess[1]] == "M"
print "You missed"
break
while True:
print "Player 2 your turn"
user2_guess = [user_row(), user_col()]
if user2_guess == user1_ship:
board[user2_guess[0]][user2_guess[1]] == "H"
print "PLAYER 2 WINS!"
break
else:
board[user2_guess[0]][user2_guess[1]] == "M"
print "You missed"
break
Your indentation is incorrect... Look at this:
while True:
while True:
print "Player 1 your turn"
user1_guess = [user_row(), user_col()]
if user1_guess == user2_ship:
board[user1_guess[0]][user1_guess[1]] == "H"
print "PLAYER 1 WINS!"
break
The break statement must have the same indentation as the print statement like this:
while True:
while True:
print "Player 1 your turn"
user1_guess = [user_row(), user_col()]
if user1_guess == user2_ship:
board[user1_guess[0]][user1_guess[1]] == "H"
print "PLAYER 1 WINS!"
break
If you have some time, please read a Python Styleguide to improve the quality of your code.

Categories

Resources