Help me figure out this code, whoever could help! APPRECIATED!

python
practice

#1

I am trying to run this code based on what I learned. Basically does not matter if I give any number beyond my range, but it still does not run through "else", even if I give 200 to go over 100 range! how to get it run up to or through else and to get printed????

Please HELP! Thanks, much appreciated!!!!

for x in range(100):
    x = int(input("Enter age:    "))
    if x >= 21:
        print("you can buy that beer")
    elif x < 21:
        print("No beer for you!")
    else:
        print("you typed wrong option!")

#2

@orouge

Look at this

Need any more help?


#3

@orouge u should be using error handling concepts.. if u wanna stick with for loop u should tweak ur code a bit and also raw_input() is better when you compare input()

for x in range(100):
try:
x = int(raw_input("Enter age: "))
if x >= 21:
print("you can buy that beer")
elif x < 21:
print("No beer for you!")
except ValueError:
print("you typed wrong option!")


#4

you mean the name? looping? how does that help ? I am probably not seeing it yet. sorry! thanks in advance for further help :wink:


#5

it is still the same problem

thanks by the way for looking into it further.

I am copying the error it is giving me.

/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Users/orujgadimov/PycharmProjects/1STPROJECT/OrujFirstPyCharm.py
Traceback (most recent call last):
File "/Users/orujgadimov/PycharmProjects/1STPROJECT/OrujFirstPyCharm.py", line 2, in
x = int(raw_input("Enter your age: "))
NameError: name 'raw_input' is not defined

for x in range(100):
x = int(raw_input("Enter your age: "))
if x>= 21:
print("buy that")
elif x<21:
print("nope")
else:
print("wrong option")

Process finished with exit code 1


#6

Hi @orouge,

The error message gives a big clue: you're using Python 3.x.

Not sure if you are aware, but codecademy actually teaches Python for Python version 2.x, and this means that some stuff are not entirely transferable. In order for your code to work, you must first change x = int(raw_input("Enter your age: ")) to x = int(input("Enter your age:")) :slight_smile:

Oh, and also, your thing doesn't run the else statement because you effectively covered all possible integer cases!

For integers larger than or equal to 21:

For integers smaller than 21:

Let's say your input is 100. That will fall under the if statement, so the else statement will not run. Let's say your input is 1. That will then fall under the elif statement, so the else statement will also not run. And this is why the else statement is never executed.

If you really want it to work, change one of your cases, or allow input to be anything (ie. remove int) so that if an alphabet etc is keyed in, your else statement will run.

Hope this helps :slight_smile:


#7

Thanks umopapsidn

I initially started without raw_input;however changed it later. But it is good to know the reason and different between python versions.

Let me ask my initial question that is not addressed yet.

1)Why my code checks if and elif but never get to else: even though I type "hahahaha" for instance so it checks it as else but it doesn't!!!

2) given my range is 100, range(100): when I give 200 which is beyond that range - why does it not see or check as else since it falls under else: ?!

Thanks for capturing my question this fast

looking forward to your answer!

for x in range(100):
x = int(input("Enter your age: "))
if x>= 21:
print("buy that")
elif x<21:
print("nope")
else:
print("wrong option")


#8

@orouge

Your name of your variable was x.

As you were looping you were assigning x the variable a differnt value than what the loop was assigning it and causing a bug.

As @umopapsidn also said you have a name error because of the use of a python 2.7 method in 3.*

There are many ways to go about solving your problem, at your current skill level you should use a while loop that is always true and will loop forever until your condition is set to true. This then will cause the loop to break and continue to other code.

Python Code:

while True:
    if int(input("What is your age")) > 20:
        break

The above code will run forever until your age meets the requirement. If you want something else to happen if the person is under 21 you just put that into the else statement. You can import sys and use the exit method from it to end the script as follows,

Python sys Example:

from sys import exit
while True:
    if int(input("What is your age")) > 20:
        break
    else:
        exit("Now Exiting Program")

In the above case it should be noted that the loop is worthless.

In your case you want to ensure that a valid input is entered and that is how you should structure your code as well. Again as @umopapsidn mentioned you can use a try statement for this.

Python Code:

while True:
    try:
        if int(input("What is your age")) > 20:
            break
    except TypeError as e:
        print("You failed to enter a valid input")
    except ValueError as e:
        print("You failed to enter a valid input")

The above will ask your age until you pass the test, again you can change it to suite your needs.


#9

On this one it is an order of operations. If you satisfy one condition such as x >= 21 then any other condition is going to be true so you do not need to check if is x < 21. Your else statement will should never be run because you as your code is written it cannot resolve to it ever.

If you wanted to use your code as is you would need to add an addition if statement checking to see if the variable is able to be set to an int.

Example Python Code:

for y in range(100):
    x = input("Enter age:    ")
    if x.isdigit():  # always use built-ins when possible, no reason to reinvent the wheel
        if int(x) >= 21:
            print("you can buy that beer")
        else:
            print("No beer for you!")
    else:
        print("you typed wrong option!")

As you can see I have changed a few things but as it is now it should resolve as you would expect it to.


#10

Hi @orouge,

1) If you type something like "hahahah" I expect it to throw up an error message, simply because this input cannot be converted into an integer and this bit:

will not work out.

2) I think you have been momentarily confused by the purpose of typing for x in range(100). Take a moment now, and pause and think about what this really means before reading on.

Ready?

Okay so actually for x in range(100) will allow the user to re-enter input over and over and over again, until they have had 100 tries. Remember? :slight_smile: So you didn't actually set a limit for x...

If you really want to set a range, you should set it within the if and elif statements. E.g. instead of:

if x >= 21: 
    print("you can buy that beer")

do:

Something like that would work.

P.S. When you mention someone, use this symbol @ ahead of their username hahah
P.P.S. Notice how I and @zeziba both changed the for x in range(100) statement to another loop variable like for i in range(100) for the first bit to avoid the confusion which you landed yourself in...


#11

I see what @orouge was going for now, you should just make it simpler and more clear then.

Example Python Code:

age = str()  # create an empty string so we can check if it's a digit
while not age.isdigit():  # As long as it is not a digit we will loop FOREVER!!!!
    age = input("What is your age:    ")
if int(age) in range(21, 100):  # By just checking if the number is in your range we can reduce the code count and still get the same results
    print("Would you like a beer?")
else:
    print("Would you like a juice")

As you can see, range is a super cool construct that can enable us to do all types of magical things. Also by using different things creatively we can reduce the code count and still get the same result.

If you still require help with this feel free to ask.


#12

Thanks @umopapsidn and @zeziba

With my rudimentary knowledge of programming, @umopapsidn, your following code does what I exactly wanted to do- so thanks for that :wink:

for x in range(100):
x = int(input("Enter your age: "))
if x in range(21, 100):
print(" you can buy that beer")
elif x in range(1, 20):
print("you cant")
else:
print("wrong option")

Meanwhile, your code, @zeziba, looks like will keep me up tonight trying to understand it. it is challenging and thrilling. thanks for your input. I might send some more questions on your way as I work on it :wink:

Thank you,@umopapsidn and @zeziba ,guys again! much appreciated


#13
  1. You are using "int(input)" meaning you are converting it to be an integer so when you type a string it can't see an integer so it goes rogue.

  2. The range is number of times you run the program, giving "200" straight away on the first attempt of running the program will be considered as a first run.. i.e you can run your program 200 times after the 200th time your range runs out

Hope this helps!!


#14

it does!. thanks @digitalace90713!


#15

hey @zeziba ! Thanks again I liked this code. thanks for sending it :wink:

Question: not age.isdigit(): used after while is something advanced; you learn from literature or it is something every programmer within python discovers for themselves??? probably it is a silly question given i have rudimentary knowledge in python; but figured to still ask :wink:

2) why we assigned string to age?

def loop():
    age = str()
    while not age.isdigit():
        age = input("enter your age:      ")
    if int(age) in range(21, 100):
        print("you can get beer")
    elif int(age) in range(20):
        print("under age")
    else:
        print("no sorry")
    loop()
loop()

I will shoot another question at you once i go through your previous code!

Much appreciated! Thanks again!

just updating . looks like for this one we can get rid of while function

def y():
    age = int(input("enter your age:      "))


    if int(age) in range(21, 100):
        print("you can buy beer")
    elif int(age) in range(20):
        print ("under age")
    else:
        print ("wrong option")
    y()
y()

#16

I would refrain from accidentally creating recursive functions until you know what you are doing.

That being said, generally you will want to stick to simple and less complex as it is more readable. The reason why I assigned str() to the cariable first is because the method str.isdigit() is only part of the str class. I also know that input() returns a string of some form so using that knowledge I can test the string in my while loop. The syntax while not says that while this condition is not true run forever. So when the condition is finally true then it will stop looping.

If you think about it, that is exactly the functionality that you would be looking for in something like this. We get the user input and if they fail to enter a number we won't continue, this gives us the ability to know that we can in fact convert the string into an integer without an exception being raised.

As you can see running a loop off of a non-true condition is a very good way to solve some issues that arise.

Also, if you want to use it in a function your code should look more like,

Python Code:

output = {
    1: "Enter your age please:\n",
    2: "Would you like a beer?",
    3: "Would you like a juice?",
    4: "Your age is a crazy number!"
}

def ask_age(min=21, max=100):
    """
    Function checks the age of the user
    :param min: Min Age to trigger underage response
    :param max: Max Age to trigger old enough response
    :return: None
    """
    age = str()
    while not age.isdigit():
        age = input(output[1])
    if int(age) in range(min, max):
        print(output[2])
    elif int(age) in range(0, min):
        print(output[3])
    else:
        print(output[4])

ask_age()

ask_age(15, 47)

ask_age(max=512, min=7)

ask_age(min=14)

ask_age(max=77)

The above has several examples of how to program and use the function as it is. Coding the function this way allows for greater flexibility and an ease in expanding it.

Take note on how I use the responses as well, as you get further into programming you will often need all your output to be in one location and getting used to doing it like this will help you by leaps and bounds.

If you need any help understanding why I did something feel free to ask.


#17

Thanks for new entry @zeziba. I will study more. One more question- in the following code, it was not getting to else until you suggested
from sys import exit

it is cool! so, when do we recognize or feel need to call from sys import exit` it was great the way it worked. not to rush you, take your time whenever you have time, few words about it would be MUCH appreciated! thanks again

def y():
    from sys import exit
    while True:
        if int(input("enter your age:      ")) > 20:
            print("you can buy beer")
            break

        else:
            exit ("sorry you are under age! no alchohol for you")
    y()
y()

2) what is try? except statements? which could be manipulated to meet my needs. should i learn it by heart for now?

while True:
    try:
        if int(input("What is your age")) > 20:
            break
    except TypeError as e:
        print("You failed to enter a valid input")
    except ValueError as e:
        print("You failed to enter a valid input")

how do I change it to suit my needs as you @zeziba mentioned earlier?? with trying to enter >21 and <21 if elif else statements?


#18

thanks @digitalace90713 I checked your code. it is great it checks non-integers too. Could you give me a bit more information about error handling concepts? how can I manipulate them to achieve different ends?

Thanks in advance!


#19

hey couldn't turn up earlier... many experienced coders would ask u to read the manual for the concepts and i did some searching am just a toddler so that's the best info i could provide you... hope this helps