Python Tutorial v3.2.5 Lesson 9.2 - Guessing Numbers with If Statements

preview_player
Показать описание
19:00 Click to skip directly to the Lesson 9.2 Challenge Program

Lesson 9.2 continues by providing examples of how to use if statements paired with conditionals to make a very rudimentary Guess the Number game. Three different ways of writing Guess the Number programs are evaluated, along with the strengths and weaknesses of each. Finally, the Lesson 9.2 Challenge Program has programmers design a system in which a player can choose from a list of commands, then have the program realistically react to their choices.

This is an introductory series of Python tutorials. This course, from start to finish, is designed to help someone who has never programmed before learn the basics of coding in Python. As this series continues, we examine more advanced Python techniques, functions, and methods.

Keep in mind this tutorial is using an older version of Python, v3.2.5. You will need to click on the "View Older Releases" button to use this specific version. Using the newer versions will not be an issue at this point, but when the lesson proceeds to basic graphics, the Pygame Module we'll use does not support v3.3+ at this time.
Рекомендации по теме
Комментарии
Автор

Hey i dont know if you are going to respond on this but this serie realy helped me out and learned me a lot and i did the challange and i did some modefications on it.
so here it is

# setting some variables
act_choice= '0'
rabbit_meat= 0
armor= 'no'
sword= 'no'
possibility_armor= 1
possibility_sword= 1
possibility_fallen_tree= 1
possibility_rocks= 1



print('**** Main Menu ****')

while act_choice != 'R':
        act_choice= input('\nMake your selection:\n(P)ick up object.\n(S)earch area.\n(R)un away.\nMAKE YOUR SELECTION\n:')
        #when the user chose to pick up object
        if act_choice == 'P':
            print('\nWhat would you like to pick up?')
           
            pick_choice= YOU SELECTION\n:')
            #when the user chose to pick up a sword
            if pick_choice == 'S':
                if possibility_sword == 0:
                    print('\nYou already picked up a sword.')
                if possibility_sword == 1:
                    print('\nYou picked up a sword. It\'s well balanced and quite sharp.')
                    possibility_sword= 0
                    sword= 1
                
            #when the use chose to pick up Armor
            if pick_choice == 'A':
                if possibility_armor == 0:
                    print('\nYou already picked up a set of armor, ')
                if possibility_armor == 1:
                    print('\nWhile it is a bit rusty, it offers good protection.')
                    possibility_armor= 0
                    armor= 1
                
        #when the user chose to search the area
        if act_choice == 'S':
            print('\nwhere would you like to search?')
           
            search_choice= input('(R)ocks.\n(F)allen tree.\nMAKE YOUR SELECTION\n:')
            
            #when the user chose to search the rocks
            if search_choice == 'R':
                if possibility_rocks == 0:
                    print('\nYou already searched this place.')
                if possibility_rocks == 1:
                    print('\nYou found a body from somebody who fell into the rocks, the body is empty.')
                    possibility_rocks= 0
               
                    
            #when the user chose to search the fallen tree
            if search_choice == 'F':
                if possibility_fallen_tree == 0:
                    print('\nYou already searched this place.')
                if possibility_fallen_tree == 1:
                    print('\nYou find a rabbit, what would you like to do?')
                   
                    rabbit_choice= input('(K)ill the animal.\n(L)eave it.\nMAKE YOUR SELECTION\n:')
                     #when thee user chose to kill the rabbit
                    if rabbit_choice == 'K':
                        print('\nYou kill the rabbit and get 2 pieces of rabbit meat.')
                        possibility_fallen_tree= 0
                        rabbit_meat += 2
                    #when the user chose to leave the rabbit.
                    if rabbit_choice == 'L':
                        print('\nYou leave the rabbit.')
                        possibility_fallen_tree= 0
                
                
print('\nYou get away safely with:')

print('* %s sword' %(sword))     
print('* %s set of armor' %(armor))
print('* %s pieces of rabbit meat' %(rabbit_meat))



                
                

marten
Автор

Thanks for this tutorials, you are a great teacher sir. Well explained and easy to understand.

joeldavila
Автор

Done. Now, lets see if i understood everything so far. Time to whip out a program :)

Noldy__
Автор

You're off to a good start. This first thing I would note is that your while statement and if statements don't have a conditional check. You're storing the users input to your question in the variable 'user'. When you check what the user inputted, you have coded "while P:". That statement will always evaluate to true (similar to what you did with "if s:" and "if a:". Make sure your while and if statements always compare 2 things. If they don't, it probably won't work correctly. For now, I would also change the while statement to an if statement, since right now we're only checking the user's selection once. Start by changing:

while P:            to           if user == 'P'

Now, you're making a more correct check that Python will handle how you'd like. With that change, you'll notice your program now only responds to a user selecting P, but not to any other letters. If they select something else at this point, the program will just end. 

Next, I would probably change your second input call to the 'user' variable to something else. While it may work, you've already used 'user' to store a response for a different question, so renaming it will help fix some confusion. I'm going to call it user2. So next, I'll change these two lines (along with making the 's' and 'a' capital to keep the program more consistent.:

if s:             to         if user2 == 'S'
if a:             to         if user2 == 'A'

With those changes, you can code the (S)earch and (R)un away choices with similar if statements to the one you used above. When you add your check for (S) or (R), it would be fine to use user2 as the variable name to check those secondary questions. If you get that all working, you'll be ready to add your 'while' loop and make the program run continuously.

Once you get to that point, if you have trouble, I'll be happy to keep helping you out. I'll also post the program you sent as I've adjusted it to this post. Keep it up and thanks for your support.

xnavysteve
Автор

Great Tutorial! Can you please help me on the challenge part. So i give the user 3 options P, S, R that the user can choose from, however  i noticed when the user types something else into the input function the program still runs. Also with the if statements they both print both messages even if the user just chooses the letter s or a. So far this is the code i have:
   
print("Make your selection:")

P = "(P)ick up object"
S = "(S)earch the area"
R = "(R)un away"


print (P)
print (S)
print (R)
print ("\n")

user = input("Make your selection\n:")

s = "(s)word"
a = "(a)rmor"

while P:
    print("\n")
    print("What would you like to pick up?")
   
    print(s)
    print(a)
    print("\n")
    user = input("Make your selection\n:")
    if s:
        print("You pick up the sword. It is well balance and quite sharp")
    if a:
        print("You pick up the armor. It can defend you from enemies")
    

JulioHernandez-mxbs
Автор

Hi again, having a similar problem with this one...
print("You walk into a large old room filled with dust, cobwebs and large oak furniture")
choice = input("What do you do? A) examine cobwebs B) search room ")
if choice == "examine cobwebs":
print("A giant spider rises from the cobwebs!")
spider = str(input("What do you do? A) run B) fight "))
if spider == "run":
print("You escape room. GAME OVER")
if spider == "fight":
print("You're eaten alive. GAME OVER")
if choice == "search room":
print("You find a secret door hidden in the back corner")
door = input("What you do? A) open door B) keep looking ")
if door == "open door":
print("Behind the door you find a chamber filled with gold! GAME OVER")
if door == "keep looking":
print("A giant spider rises from the cobwebs!")
spider = input("What do you do? A) run B) fight ")
if spide) == "run":
print("You escape room. GAME OVER")
if spider == "fight":
print("You're eaten alive. GAME OVER")

I didn't follow your exact instructions but the code is similar
it's telling me that spider is invalid despite the fact that it's clearly a variable

mishmeshmonster
Автор

how can i make your code little more..more ...bigger. it is very hard to read for an old man like me. thanks
val p

vphilip
Автор

I added a test in the event the user guesses on first try. This is what I did.
guess = int(input("Enter number between 1-10 \n : "))

numoftries = 0
while guess != 5:
if guess < 5:
print("too low")
numoftries += 1
guess = int(input("Enter number between 1-10 \n : "))
if guess > 5:
print("too high")
numoftries += 1
guess = int(input("Enter number between 1-10 \n : "))
if guess == 5:
numoftries += 1
print("You're correct!")
print("It took you", numoftries, "tries to get the answer" )
if guess == 5 and numoftries == 0:
print("Excellent, you guessed on first try")

Is there another way of doing this?
Thanks

jdr.paradigmabiblico
Автор

Hi Steve. I'm really having a problem. I'm stuck on this after 2 weeks of trials.

Why is this code still looping even when i pick A or B?

# Test While

choose = 0

while choose != 'A' or choose != 'B': # Pick A or B
choose = input("Please enter A or B \n:")

print("Congratulations, you picked %s." % (choose))

Noldy__