altin
altin

Reputation: 887

python ... working with numbers

I wanted to know if there is another command to make it shorter:

noes = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']

this is the command I use so its has to do with years.

Upvotes: 0

Views: 281

Answers (7)

Manuel Marcus
Manuel Marcus

Reputation: 7

This code should work:

#creates a variable, that is easy to change
number = 15

#creates an empty list
noes = []

#add the numbers to the list using for loop
for x in range(1, number+1):
    noes.append(x)

#note that the first argument will be in the list, but the second will not be in the list at the range function

Upvotes: 0

Hugh Bothwell
Hugh Bothwell

Reputation: 56624

I presume you then use this like

if AgeString in noes:
    print "U R 2 yng!"

It would probably be cleaner to do logical comparison, ie

if int(AgeStr) < 16:
    print "Too young"

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116100

Use

noes = range(1, 15);

Or, if you really need strings:

noes = [];
for i in range(1, 15):
  noes.append(str(i))

Upvotes: 0

khachik
khachik

Reputation: 28703

noes = range(1, 16).

You can use map(str, range(1, 16) or [str(i) for i in range(1, 16] to get strings.

range.

xrange is similar to range, but doesn't make a list, but can be used in for loops, for example.

[str(i) for i in xrange(1, 16)]

Upvotes: 1

Lennart Regebro
Lennart Regebro

Reputation: 172179

That's not numbers. You have quoted them, so they are strings. Numbers would be

noes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] 

And shorter would be

noes = range(1,16)

I'd recommend you to read a Python tutorial.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881113

If you're after a list of strings, you can use:

>>> x = [str(n) for n in range(1,16)] # or xrange if you wish
>>> x
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']

A list of numbers can be made with either of the following:

x = [n for n in range(1,16)]
x = range(1,16)

Upvotes: 6

Cat Plus Plus
Cat Plus Plus

Reputation: 129754

noes = map(str, range(1, 16)) assuming you really want strings. If not, then noes = range(1, 16) will suffice.

Upvotes: 8

Related Questions