Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
help with list
#11
guys one last question,in case i wanted to check if the given numbers are in range example a is between 100 to 120 and b is between 3 to 7 the code should be like this?

a = int(input("Give number a: "))
b = int(input("Give number b: "))
if a in range(100,121):
    print ("correct number a")
else:
    print ("give new number a:")
if b in range(3,8):
    print ("correct number b")
else:
    print ("Give new number b:")
luck = list()
for i in range(1,b+1):
    luck.append(a**i)
print (luck)
well i am running it and when i give a=125 it gives "correct number a" instead of the other option.Am i doing something wrong?
Reply
#12
(Jan-31-2019, 09:51 AM)sonedap Wrote: well i am running it and when i give a=125 it gives "correct number a" instead of the other option.Am i doing something wrong?

I could not replicate your problem. I run your code with entering 125 and 6 and output was:

Output:
Give number a: 125 Give number b: 6 give new number a: correct number b [125, 15625, 1953125, 244140625, 30517578125, 3814697265625]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#13
so,it's wrong!
since it asks for a new number then shouldn't the list have the new number a as base and not the first one we gave???
How can i change that?
Reply
#14
You are master of Python. Python is obedient and if he understands you he does whatever you throw at him. Python does not have brain like we humans do to guess whether what you told him to do was actually what you wanted him to do. Therefore you must use your great power carefully. You must learn to express yourself clearly and unambiguous way.

Sloppy expression skills in spoken language translates into code with unexpected results. You wrote: "it gives "correct number a" instead of the other option". I demonstrated that this is not the case. You responded: 'so,it's wrong!'. How come? It was you who was wrong by stating that output is "correct number a".

If you are not able to express yourself in spoken language you are not able to express yourself in programming.

Regarding your problem: you should validate user input. This means that you have to ask user until answer is valid. There is while loop in Python to do so. Easiest way is to move validation to separate function but I don't know whether you know (or are allowed) how to use them.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#15
(Jan-31-2019, 11:04 AM)perfringo Wrote: Sloppy expression skills in spoken language translates into code with unexpected results. You wrote: "it gives "correct number a" instead of the other option". I demonstrated that this is not the case. You responded: 'so,it's wrong!'. How come? It was you who was wrong by stating that output is "correct number a".

If you are not able to express yourself in spoken language you are not able to express yourself in programming.

Regarding your problem: you should validate user input. This means that you have to ask user until answer is valid. There is while loop in Python to do so. Easiest way is to move validation to separate function but I don't know whether you know (or are allowed) how to use them.

i meant that since a=125 its out of range and it should give the "give again number a" answer.
as for validation,you mean something like that?

while True:
    try:
        a = int(input('a: '))
        if a < 100 or a > 121:
            raise ValueError
        break
    except ValueError:
        print("Invalid integer. The number must be in the range of 100-121.")
and one more while for number b?
Reply
#16
(Jan-31-2019, 11:20 AM)sonedap Wrote: i meant that since a=125 its out of range and it should give the "give again number a" answer.

Your code did exactly that: "give new number a:" (line #3 in output). As there was no loop nor termination your code run happily till end.

Yes, code you wrote is validating user input. But you need to use it two times (for both a and b). Therefore it is advisable to move into function. One way of writing function with needed functionality:

def validate(request, allowed_range):
    """Return input in allowed_range
    
    :param request: request made to user
    :type request: str
    :param allowed_range: allowed numbers range
    :type allowed_range: range
    :return: user input within allowed range
    :rtype: int
    """
    m = (f'Expected integer in range {min(allowed_range)} - {max(allowed_range)} '
         f'but input was')
     
    while True:
        answer = input(request)
        try:
            answer = int(answer)
            if answer in allowed_range:
                return answer
            raise ValueError
         
        except ValueError:
            print(f'{m} {answer}')
Then you can just:

a = validate('Enter number a in range 100-120: ', range(100, 121))
b = validate('Enter number b in range 3-7: ', range(3, 8))
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#17
Sorry but i don't understand how fuction works.
So to make it simple i just need to validate in put 2 times before using list in program
Reply
#18
(Jan-31-2019, 02:30 PM)sonedap Wrote: Sorry but i don't understand how fuction works.

You don't understand how functions in Python work or you don't understand how this particular function works?
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#19
(Jan-31-2019, 02:33 PM)perfringo Wrote: You don't understand how functions in Python work or you don't understand how this particular function works?
well,i am studying Functions now and i still don't get how they work in general.
Also,i don't understand how this one function works..
But,i tried and i wrote another Function (one simpler i think)and it works!
i am happy!!
Thanks for your help!!!!
Reply
#20
(Jan-31-2019, 03:29 PM)sonedap Wrote: well,i am studying Functions now and i still don't get how they work in general.
Also,i don't understand how this one function works..

Maybe following can help:

There are numerous built-in functions in Python. You used number of them in your code: int, print, range. So using functions and providing arguments to functions should be easy-peasy for you.

If there is something you want to accomplish and it is not possible with using built-in functions and functions in built-in modules / third party modules then you can define functions yourself.

Functions are useful for two main reasons: (1) you can reuse them and (2) you can separate what is done from how it's done. Imagine, that every time you want something print you would have to write instead print('something') pretty lengthy and possibly complicated code and you get the picture.

Function I wrote is quite similar to the code you provided in your snippet.

To walk you through this code by rows:

def validate(request, allowed_range):
    """Return input in allowed_range
     
    :param request: request made to user
    :type request: str
    :param allowed_range: allowed numbers range
    :type allowed_range: range
    :return: user input within allowed range
    :rtype: int
    """
    m = (f'Expected integer in range {min(allowed_range)} - {max(allowed_range)} '
         f'but input was')
      
    while True:
        answer = input(request)
        try:
            answer = int(answer)
            if answer in allowed_range:
                return answer
            raise ValueError
          
        except ValueError:
            print(f'{m} {answer}') 
# 1 - defining function by using keyword def, giving it descriptive name following PEP8 and descriptive parameter names. These parameters names are arbitrary and have nothing to do with arguments you will actually use when calling the function (read more: What is the difference between arguments and parameters?). Parameters are defined here so that different requests and ranges can be used when calling function.

# 2 - 10 - docstring which describes what the function does and what types of arguments it accepts. Docstring serves two primery objectives: to give others understanding what function does and to remind yourself what you did. Believe me, if you return to function you wrote couple of months ago it seems that somebody else wrote it. For that reason it advisable to document your function even if it is not meant for others. You can access this docstring like with built-in functions by help(function_name). If this function is in your namespace then you can do this:

>>> help(validate)
validate(request, allowed_range)
    Return input in allowed_range
    
    :param request: request made to user
    :type request: str
    :param allowed_range: allowed numbers range
    :type allowed_range: range
    :return: user input within allowed range
    :rtype: int


# 11-12 - defining part of message to display when user enters values which are not in allowed range. To assist user, it takes max and min values from range to indicate within which range input should be. This could be done in except block but for (subjective) readability purposes (line is long and print statement is intented 8 spaces) it is created separately. F-strings are used (requires Python 3.6 or newer).

# 14-23 - while-loop is quite similar to code you provided. Differences are: user input is assigned to name 'answer' before try..except [#15]. This way it is (subjectively) more readable and usable for message in except-block; if user input is not int (actually string which can be converted to string) [#17] or if it is int but not in allowed range [#20] ValueError will be raised. If input is in accepted range it returns user input as int [#19].

# 22-23 - if ValueError occurs in try-block (either from input not being int or not in allowed range) message will be printed which states allowed range and what user entered.

while loop executes until int is returned.

After defining function you can use it. When calling function in these particular cases arguments are: 'Enter number a in range 100-120: ' ; 'Enter number b in range 3-7: ' (request) and range(100, 121) ; range(3, 8) (allowed_range)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Forum Jump:

User Panel Messages

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