Python Forum
Stop if statement from running
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Stop if statement from running
#1
im knew to python and have started work on a small project

import random
strength = random.randint(1,100)
health = random.randint(1,100)
energy = random.randint(1,100)
Text1= 'Your strength is '
Text2= 'Your health is '
Text3= 'Your energy is '
Text4= 'You took '
Text5= ' damage'
Text6= 'your health is now '
Text7= 'your energy is'
damage = random.randint(1,20)


print (Text1 + (str(strength)))
print (Text2 + (str(health)))
print (Text3 + (str(energy)))
print ('You see a beast before you what are your actions')

action = input ('Fight or Run')


if action =='Fight' or 'fight':
    print ('You Fought')
    print (Text4 + (str(damage)) + Text5)


if action =='Run' or 'run':
    print ('you ran')
    print (Text7 + (str(energy-20)))
but when i run this code it gets to the points where it asks fight or run. If i choose fight it works perfectly fine but if i choose run it still does the fight sequence and then the run sequence and i do not know how to fix this

(i know my code isnt the best but i understand it)
Reply
#2
removed response to avoid confusion..
Reply
#3
The main issue is the conditional:

if action =='Fight' or 'fight':

# Evaluates to
if action == 'Fight' or True:
The string literal will always be True. As a result, the or expression will always be True. To fix it, you need can do one of the following:

if action =='Fight' or action == 'fight':

# Or

if action in ('Fight', 'fight'):

# Or

if action.lower() == 'fight':
Reply
#4
@KieranPage
The if statements don't do as expected because of the or, see the following link
Multiple expressions with "or" keyword

note rather than checking for various case you could just turn the input into lowercase.
action = input('Fight or Run')
action = action.lower()

if action == 'fight':
    ...
@tonytech
That's great that you got the code working but note you have added duplication of code for each outcome
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  If/Else If Statement Not Running new_coder_231013 5 1,650 Dec-10-2021, 10:16 AM
Last Post: new_coder_231013
  May i ask how i can stop my coding running christing 4 2,509 Oct-03-2019, 12:25 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020