Skip to content

Instantly share code, notes, and snippets.

@macloo
Created February 2, 2014 22:35
Show Gist options
  • Save macloo/8776015 to your computer and use it in GitHub Desktop.
Save macloo/8776015 to your computer and use it in GitHub Desktop.
Example of a while loop for beginners. Also an if-statement to help them figure things out.
# alien example - if-elif-else, and while loop
from random import randint # allows you to generate a random number
# variables for the alien
alive = True
stamina = 10
# this function runs each time you attack the alien
def report(s):
if s > 8:
print "The alien is strong! It resists your pathetic attack!"
elif s > 5:
print "With a loud grunt, the alien stands firm."
elif s > 3:
print "Your attack seems to be having an effect! The alien stumbles!"
elif s > 0:
print "The alien is certain to fall soon! It staggers and reels!"
else:
print "That's it! The alien is finished!"
# main function - accepts your input for fight with the alien
def fight(stam): # stamina
while stam > 0:
response = raw_input("> ")
# fight scene
if "hit" in response or "attack" in response:
less = randint(0, stam)
stam -= less # subtract random int from stamina
report(stam) # see function above
elif "fight" in response:
print "Fight how? You have no weapons, silly space traveler!"
elif "run" in response:
print "Sadly, there is nowhere to run.",
print "The spaceship is not very big."
else:
print "The alien zaps you with its powerful ray gun!"
return True
return False
print "A threatening alien wants to fight you!\n"
# call the function - what it returns will be the value of alive
alive = fight(stamina)
if alive: # means if alive == True
print "\nThe alien lives on, and you, sadly, do not.\n"
else:
print "\nThe alien has been vanquished. Good work!\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment