Python Forum
Thread Rating:
  • 2 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Variable Range
#1
I am trying to code a variable with a range from 4-10. The user inputs a number that will be determined if it's one of the numbers in the variable (4 to 10).
I tried using the following:

variable = range(4, 10)

#Then the user input:

number = input('Enter a number:')
if number == variable:
     print(variable 'selected.')
This isn't working for me. It seems to just ignore these commands.
What command(s) do I need to use to create a variable range? Thanks.
Reply
#2
The input function returns either a string (3.0+) or a number (if you enter one in 2.7 or before). The range function returns either a range object (3.0+) or a list (2.7-). None of those comparisons work.

Are you trying to get a random number that the user then guesses? If so, look at the random module, either random.randrange or random.randint.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
If the user enters in, say 8, python see that the 8 is one of the numbers in the variable and runs the script contained in the "if" command. Same with any other number 4 to 10. Any ideas on how to do it?
Reply
#4
you are trying to compare a single item to a list, it will never match.
def get_number():
    number = 0

    while number < 4 or number > 10:
        try:
            number = int(input('Please enter a number between 4 and 10: '))
        except ValueError:
            print("That's not a number")
    return number

# try it
if __name__ == '__main__':
    print('{} selected'.format(get_number()))
Reply
#5
That seems to work! I'm still not very good at coding so your code is a little confusing. I'll look into all the commands you used. I hadn't used the greater/less than symbols very much so I'll have to start practicing with them. Thanks for the help.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  matplotlib x axis range goes over the set range Pedroski55 5 3,101 Nov-21-2021, 08:40 AM
Last Post: paul18fr
  Define a range, return all numbers of range that are NOT in csv data KiNeMs 18 6,872 Jan-24-2020, 06:19 AM
Last Post: KiNeMs
  Would like to input a date variable and determine whether it is within the time range harold 3 2,513 Jan-05-2019, 09:04 AM
Last Post: Gribouillis
  Variable in range of float dogginky 3 3,390 Dec-27-2017, 02:36 PM
Last Post: Larz60+
  Modifying / extracting multiple list items simultaneously using variable from range ehammarlund 4 3,658 Dec-06-2017, 08:15 PM
Last Post: ehammarlund

Forum Jump:

User Panel Messages

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