Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
Hot Dog Day #42
Jun 17, 2001

Egbert B. Gebstadter

Pollyanna posted:

Is there, uh...an explanation on how to use Requests? Say I want to get the text on http://www.alcyone.com/oo/ , like the title and then a list of all the links there. The Requests quickstart guide talks about getting post data and keys and values and such...but no real explanation on "hey get this text". I am not good at HTTP, is this what Requests is good for? Or is it more complicated than that? :(

Requests will get you the file, but you'll need some kind of parser like Beautiful Soup to actually do anything with the file (like grabbing all the links, as in your example).

Adbot
ADBOT LOVES YOU

the
Jul 18, 2004

by Cowcaster
Trying to figure out how to make an n * n matrix in Python and then populate it with random numbers. The user specifies a size (example, 5 makes a 5x5 matrix). I know how to make any matrix, as in:

Python code:
numpy.matrix([[2,3],[5,6]])


Would make

code:
[2 3]
[5 6]
But how do I create one without knowing the size?

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

the posted:

Trying to figure out how to make an n * n matrix in Python and then populate it with random numbers. The user specifies a size (example, 5 makes a 5x5 matrix). I know how to make any matrix, as in:

Python code:
numpy.matrix([[2,3],[5,6]])


Would make

code:
[2 3]
[5 6]
But how do I create one without knowing the size?

I assume

Python code:
numpy.matrix([[0] * 5] * 5)

Dominoes
Sep 20, 2007

Pollyanna posted:

Is there, uh...an explanation on how to use Requests? Say I want to get the text on http://www.alcyone.com/oo/ , like the title and then a list of all the links there. The Requests quickstart guide talks about getting post data and keys and values and such...but no real explanation on "hey get this text". I am not good at HTTP, is this what Requests is good for? Or is it more complicated than that? :(

Python code:
url = 'http://www.alcyone.com/oo/'
print(requests.post(url).text)
The Requests quickstart and advanced guides are pretty good at explaining by example; give them another look. You could use regular expressions to extract the links from the HTML.


Dren posted:

QTimer should be protecting you from a lot of the mess that this code would cause if it were executed in a separate thread because it executes its callback in the event thread. If it didn't and the callback was executing from a different thread, you'd have bad problems if you happened to change parameters while the callback was executing.

Here's an effort to decouple metronome behavior and instrument playing behavior. The metronome is in charge of bpm, meter, and current_beat. The instrument is in charge of the other stuff. The way it's set up the metronome's start method accepts the play_beat callback function, which has been modified to accept downbeat as an argument. If you wanted you could add a method to it to allow other instruments to be added to the timer's callback. Might be interesting.


Decoupling the functionality into Instrument and Metronome like this also gives another possible extension if you allow multiple instruments, global volume and per-instrument volume. You could add a volume property to the metronome, which would be the global volume, and let the volume setting on the instrument be a percentage of the global volume.
Thanks a lot dude. Time to look up decorators!

Dominoes fucked around with this message at 02:09 on Aug 26, 2013

the
Jul 18, 2004

by Cowcaster

Hammerite posted:

I assume

Python code:
numpy.matrix([[0] * 5] * 5)

Thanks, I think I found a better way though:

Python code:
import numpy

question = raw_input("Specify size of n: ")

question = int(question)

array1 = numpy.random.rand(question,question)

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Dominoes posted:

You could use regular expressions to extract the links from the HTML.

http://stackoverflow.com/a/1732454/23972

quote:

You can't parse [X]HTML with regex. Because HTML can't be parsed by regex. Regex is not a tool that can be used to correctly parse HTML. As I have answered in HTML-and-regex questions here so many times before, the use of regex will not allow you to consume HTML. Regular expressions are a tool that is insufficiently sophisticated to understand the constructs employed by HTML. HTML is not a regular language and hence cannot be parsed by regular expressions. Regex queries are not equipped to break down HTML into its meaningful parts. so many times but it is not getting to me. Even enhanced irregular regular expressions as used by Perl are not up to the task of parsing HTML. You will never make me crack. HTML is a language of sufficient complexity that it cannot be parsed by regular expressions. Even Jon Skeet cannot parse HTML using regular expressions. Every time you attempt to parse HTML with regular expressions, the unholy child weeps the blood of virgins, and Russian hackers pwn your webapp. Parsing HTML with regex summons tainted souls into the realm of the living. HTML and regex go together like love, marriage, and ritual infanticide. The <center> cannot hold it is too late. The force of regex and HTML together in the same conceptual space will destroy your mind like so much watery putty. If you parse HTML with regex you are giving in to Them and their blasphemous ways which doom us all to inhuman toil for the One whose Name cannot be expressed in the Basic Multilingual Plane, he comes. HTML-plus-regexp will liquify the n​erves of the sentient whilst you observe, your psyche withering in the onslaught of horror. Rege̿̔̉x-based HTML parsers are the cancer that is killing StackOverflow it is too late it is too late we cannot be saved the trangession of a chi͡ld ensures regex will consume all living tissue (except for HTML which it cannot, as previously prophesied) dear lord help us how can anyone survive this scourge using regex to parse HTML has doomed humanity to an eternity of dread torture and security holes using regex as a tool to process HTML establishes a breach between this world and the dread realm of c͒ͪo͛ͫrrupt entities (like SGML entities, but more corrupt) a mere glimpse of the world of reg​ex parsers for HTML will ins​tantly transport a programmer's consciousness into a world of ceaseless screaming, he comes, the pestilent slithy regex-infection wil​l devour your HT​ML parser, application and existence for all time like Visual Basic only worse he comes he comes do not fi​ght he com̡e̶s, ̕h̵i​s un̨ho͞ly radiańcé destro҉ying all enli̍̈́̂̈́ghtenment, HTML tags lea͠ki̧n͘g fr̶ǫm ̡yo​͟ur eye͢s̸ ̛l̕ik͏e liq​uid pain, the song of re̸gular exp​ression parsing will exti​nguish the voices of mor​tal man from the sp​here I can see it can you see ̲͚̖͔̙î̩́t̲͎̩̱͔́̋̀ it is beautiful t​he final snuffing of the lie​s of Man ALL IS LOŚ͖̩͇̗̪̏̈́T ALL I​S LOST the pon̷y he comes he c̶̮omes he comes the ich​or permeates all MY FACE MY FACE ᵒh god no NO NOO̼O​O NΘ stop the an​*̶͑̾̾​̅ͫ͏̙̤g͇̫͛͆̾ͫ̑͆l͖͉̗̩̳̟̍ͫͥͨe̠̅s ͎a̧͈͖r̽̾̈́͒͑e n​ot rè̑ͧ̌aͨl̘̝̙̃ͤ͂̾̆ ZA̡͊͠͝LGΌ ISͮ̂҉̯͈͕̹̘̱ TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚​N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ

(use lxml.html to parse HTML)

tef
May 30, 2004

-> some l-system crap ->

Dominoes posted:

You could use regular expressions to extract the links from the HTML.

You are a bad person and you should feel bad

tef
May 30, 2004

-> some l-system crap ->
lxml is an excellent choice to parse out html, find links and extract text.

to wit:

code:
import lxml.html

html = lxml.html.fromstring(content_of_page)
html.make_links_absolute(url_of_page)

for element, attribute, link, pos in html.iterlinks():
    print link

Nippashish
Nov 2, 2005

Let me see you dance!

the posted:

Trying to figure out how to make an n * n matrix in Python and then populate it with random numbers. The user specifies a size (example, 5 makes a 5x5 matrix).

Use the functions in numpy.random.

the posted:

But how do I create one without knowing the size?

More generally, you can allocate blocks using ones/zeros/np.random.whatever and fill them in element by element or stitch them together using hstack/vstack/dstack/concatenate/kron/etc to build up structured arrays.

Dren
Jan 5, 2001

Pillbug
I thought beautifulsoup was the bestest HTML parser because it does sloppy parsing. That is, it will still work if the document is not well formed (like the tags aren't closed or something). XML parsers choke on stuff like that. Is lxml better than that now?

digitalcamo
Jul 11, 2013
I recently decided to sign up for a few college classes going towards a Programmer/Analyst degree concentration. I have been learning with Python 2. Well I thought I'd be a little step ahead of the class but towards the end of the class we will be using Python 3. So just how screwed up am I going to be trying to switch over. I'm hoping the transition won't be difficult since I'm very new to programming. Right now we are learning with Alicee which doesn't make much sense to me as how that is supposed to help you learn to program especially since you do not coding at all. But, just wanted to know if I need to be prepared for mass confusion going from Python 2 to 3.

Crosscontaminant
Jan 18, 2007

If you're maintaining an existing project, in which case it's a huge mess because you have to make sure your code doesn't make any incorrect assumptions) but if you're not it's not a big change. The biggest hurdle is the str/bytes thing, since in Python 2 unicode and str objects quack like the same duck whereas in Python 3 bytes objects are their own thing.

At this point just about everything worth using is Python 3-compatible (the sticking points are Twisted, Pygame and Pyglet, all of which have bigger problems than Python 3 compatibility).

Dren
Jan 5, 2001

Pillbug
The biggest changes you will notice are that print is a function and that division between two integers will give you a float result (if the result has a fractional part) instead of a truncated int.

tef
May 30, 2004

-> some l-system crap ->

Dren posted:

The biggest changes you will notice are that print is a function and that division between two integers will give you a float result (if the result has a fractional part) instead of a truncated int.

After unicode being the default string type, of course.

BigRedDot
Mar 6, 2008

Nippashish posted:

More generally, you can allocate blocks using ones/zeros/np.random.whatever and fill them in element by element or stitch them together using hstack/vstack/dstack/concatenate/kron/etc to build up structured arrays.

Yes you can but you should try to create all (or as many as you can) of the blocks first, and stitch them all together once, because those operations are quite expensive in terms of reallocations and data copying.

Hot Dog Day #42
Jun 17, 2001

Egbert B. Gebstadter

Hammerite posted:

I assume

Python code:
numpy.matrix([[0] * 5] * 5)

This might work for numpy, but it's a really bad habit to get into for making matrix-type nested lists, for the following reason:
Python code:
>>> L = [[0]*5]*5
>>> L
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> L[0][0] = 1
>>> L
[[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]
The problem is the last *5, which makes a list containing 5 references to the same list [0,0,0,0,0], so that any change to one of those lists changes all the lists.

Better would be
Python code:
L = [[0 for x in range(5)] for y in range(5)]
which gives the expected behavior after L[0][0] = 1.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

yaoi prophet posted:

I totally write classes that I'll only ever have one instance of at a time, it helps group functionality together. Same with functions that I'll only call once.

John Regehr has an excellent article on this: http://blog.regehr.org/archives/942

You should totally create functions that are only used once, if you think it helps. There's no rule that functions have to be called more than once.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Hot Dog Day #42 posted:

This might work for numpy, but it's a really bad habit to get into for making matrix-type nested lists, for the following reason:
Python code:
>>> L = [[0]*5]*5
>>> L
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> L[0][0] = 1
>>> L
[[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]
The problem is the last *5, which makes a list containing 5 references to the same list [0,0,0,0,0], so that any change to one of those lists changes all the lists.

Better would be
Python code:
L = [[0 for x in range(5)] for y in range(5)]
which gives the expected behavior after L[0][0] = 1.

Ah, you have a very good point.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


Note: In the middle of posting this I realized my mistake and fixed it. But I'm going to post it here anyway so you can all laugh at me. gently caress recursion. It's simple but sometimes difficult for me to wrap my brain around a problem with it. Anyway...

I'm having the problem with printing a very generic tree structure out to the screen. So far I've got this method that walks the tree and outputs it. But It prints the tree from the bottom up. I need it from top down. I have no idea what is going on.

This method is part of a very simple class that contains the tree structure. Each instance contains a list of child nodes.

code:
def text(self, depth=0):
    depth += 1
    [ child.text(depth) for child in self.children ]
    print "  " * depth + self.name
Now, as I started before, as I was typing this up I realized that all I needed to do was move the print statement to occur before the recursion.

code:
def text(self, depth=0):
    print "  " * depth + self.name
    depth += 1
    [ child.text(depth) for child in self.children ]
This way it gets printed out as it descends the tree from the top down. But, holy crap did I waste a bunch of time on this. Too much time.

Commence laughter at my expense.

Dren
Jan 5, 2001

Pillbug
Recursion: Not that hard, actually.

SirPablo
May 1, 2004

Pillbug
This might be in left-field/hail mary territory because it is such a niche use, but any suggestion how to open grib2 files using the PythonX,Y framework? I was using python 2.5 before and had a mix of library that worked for what I do (working with a lot of weather model data that is stored in the grib/grib2 format) but decided to try x,y to just have as many tools available as I could. Well, now I'm missing this one small but important piece. I found this but I got the same error indicated in the later comments. Any suggestions (besides reverting back to my 2.5 stuff)?

accipter
Sep 12, 2003

SirPablo posted:

This might be in left-field/hail mary territory because it is such a niche use, but any suggestion how to open grib2 files using the PythonX,Y framework? I was using python 2.5 before and had a mix of library that worked for what I do (working with a lot of weather model data that is stored in the grib/grib2 format) but decided to try x,y to just have as many tools available as I could. Well, now I'm missing this one small but important piece. I found this but I got the same error indicated in the later comments. Any suggestions (besides reverting back to my 2.5 stuff)?

Have you looked at this?

http://scitools.org.uk/iris/docs/latest/index.html

Pollyanna
Mar 5, 2005

Milk's on them.


Dominoes posted:

regular expressions

nnnnnnnnoooooooooooooooooooooooooooo :(

I hate those. They're such a pain in the rear end to figure out and type. It's one of those things that you're likely to never be able to write on-the-fly. I'm gonna have to use them eventually though, and I dread that day.

Hot Dog Day #42 posted:

Requests will get you the file, but you'll need some kind of parser like Beautiful Soup to actually do anything with the file (like grabbing all the links, as in your example).

This on the other hand makes it all better. :swoon: Thanks for the link!


oh my god

Pollyanna fucked around with this message at 23:52 on Aug 26, 2013

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Pollyanna posted:

nnnnnnnnoooooooooooooooooooooooooooo :(

I hate those. They're such a pain in the rear end to figure out and type. It's one of those things that you're likely to never be able to write on-the-fly. I'm gonna have to use them eventually though, and I dread that day.


This on the other hand makes it all better. :swoon: Thanks for the link!

Try reading the rest of the posts after those two.

Pollyanna
Mar 5, 2005

Milk's on them.


Thermopyle posted:

Try reading the rest of the posts after those two.

I got it installed now. BS actually recommends doing so in the documentation, which I just started reading :shobon:

the
Jul 18, 2004

by Cowcaster
Why is this second line returning an invalid syntax?

Python code:
def f(r):
    return numpy.sin(r)/((r)^^0.5)

Dominoes
Sep 20, 2007

the posted:

Why is this second line returning an invalid syntax?

Python code:
def f(r):
    return numpy.sin(r)/((r)^^0.5)
Replace ^^ with **.



** is what Python uses for exponents. ^ is a notation for exponents elsewhere; it's a bitwise operator in Python. You combined them.

Dominoes fucked around with this message at 03:18 on Aug 27, 2013

keyframe
Sep 15, 2007

I have seen things
I have another noob question. I was doing this exercise at code academy that requires you to calculate the average of student test scores and one line was getting long so I tried to break it like this:

code:
def get_average(student):
    
    studentAvg = average(student["tests"]) * 0.60 
    + average(student["homework"]) * 0.10 
    + average(student["quizzes"]) * 0.30 
    
    
    return studentAvg
which runs but returns a wrong value, if I run it like this it returns the right value:

code:
def get_average(student):
    
    studentAvg = average(student["tests"]) * 0.60 + average(student["homework"]) * 0.10 + average(student["quizzes"]) * 0.30 
    
    
    return studentAvg
I was wondering if there is a way to break a long line of statement like that into multiple lines for readability but still have python treat it like a single line?


EDIT: Found it after googling a bit! I needed to use "\" at the end of the line to continue the line. :unsmith:

keyframe fucked around with this message at 03:39 on Aug 27, 2013

Dominoes
Sep 20, 2007

Put a backslash after lines 1 and 2 of your function. You can cheat and not use it when breaking up something that uses commas, if the break's after a comma.


When you get a chance, read Pep 8, for info on how to indent statements split across multiple lines.

Dominoes fucked around with this message at 03:48 on Aug 27, 2013

Met48
Mar 15, 2009

keyframe posted:

EDIT: Found it after googling a bit! I needed to use "\" at the end of the line to continue the line. :unsmith:

You can also use brackets:

Python code:
def get_average(student):
    studentAvg = (average(student["tests"]) * 0.60
                  + average(student["homework"]) * 0.10
                  + average(student["quizzes"]) * 0.30)
    
    return studentAvg

keyframe
Sep 15, 2007

I have seen things
Thanks a lot!

BeefofAges
Jun 5, 2004

Cry 'Havoc!', and let slip the cows of war.

For most cases when you actually need a regex (not for parsing HTML) it's way easier to use http://txt2re.com/ than to try to develop a regex by hand.

Pollyanna
Mar 5, 2005

Milk's on them.


BeefofAges posted:

For most cases when you actually need a regex (not for parsing HTML) it's way easier to use http://txt2re.com/ than to try to develop a regex by hand.

Like manna from the gods. I'm crying now.

Gangsta Lean
Dec 3, 2001

Calm, relaxed...what could be more fulfilling?

SirPablo posted:

This might be in left-field/hail mary territory because it is such a niche use, but any suggestion how to open grib2 files using the PythonX,Y framework? I was using python 2.5 before and had a mix of library that worked for what I do (working with a lot of weather model data that is stored in the grib/grib2 format) but decided to try x,y to just have as many tools available as I could. Well, now I'm missing this one small but important piece. I found this but I got the same error indicated in the later comments. Any suggestions (besides reverting back to my 2.5 stuff)?

I don't know anything about pythonxy, never heard of it until now, but have you looked into using GDAL? I also use lots of weather model data and GDAL is my goto library for reading grib2. It's a C++ library, but it has bindings to many languages including python by using SWIG. With python, you can read each timestep's data as a numpy array.

GDAL is very powerful and can reproject data, load and save many file formats through a common API, and is used by many mapping tools under the hood since it has such a large number of standard capabilities.

I don't know about its python 2.5 support, I use it with 2.7.

code:
import osgeo.gdal
osgeo.gdal.UseExceptions()
osgeo.gdal.SetConfigOption('GRIB_NORMALIZE_UNITS', 'NO')

dataset = osgeo.gdal.Open('my filename')
for band_index in xrange(dataset.RasterCount):
    band = dataset.GetRasterBand(band_index + 1)
    md = band.GetMetadata()
    geotransform = dataset.GetGeoTransform()
    wkt = dataset.GetProjection()
    data = band.ReadAsArray()

QuarkJets
Sep 8, 2008

Gangsta Lean posted:

I don't know anything about pythonxy, never heard of it until now, but have you looked into using GDAL? I also use lots of weather model data and GDAL is my goto library for reading grib2. It's a C++ library, but it has bindings to many languages including python by using SWIG. With python, you can read each timestep's data as a numpy array.

GDAL is very powerful and can reproject data, load and save many file formats through a common API, and is used by many mapping tools under the hood since it has such a large number of standard capabilities.

I don't know about its python 2.5 support, I use it with 2.7.

code:
import osgeo.gdal
osgeo.gdal.UseExceptions()
osgeo.gdal.SetConfigOption('GRIB_NORMALIZE_UNITS', 'NO')

dataset = osgeo.gdal.Open('my filename')
for band_index in xrange(dataset.RasterCount):
    band = dataset.GetRasterBand(band_index + 1)
    md = band.GetMetadata()
    geotransform = dataset.GetGeoTransform()
    wkt = dataset.GetProjection()
    data = band.ReadAsArray()

GDAL is one of the libraries that comes with Pythonxy :eng101:

SirPablo
May 1, 2004

Pillbug

Gangsta Lean posted:

I don't know anything about pythonxy, never heard of it until now, but have you looked into using GDAL? I also use lots of weather model data and GDAL is my goto library for reading grib2. It's a C++ library, but it has bindings to many languages including python by using SWIG. With python, you can read each timestep's data as a numpy array.

GDAL is very powerful and can reproject data, load and save many file formats through a common API, and is used by many mapping tools under the hood since it has such a large number of standard capabilities.

I don't know about its python 2.5 support, I use it with 2.7.

code:
import osgeo.gdal
osgeo.gdal.UseExceptions()
osgeo.gdal.SetConfigOption('GRIB_NORMALIZE_UNITS', 'NO')

dataset = osgeo.gdal.Open('my filename')
for band_index in xrange(dataset.RasterCount):
    band = dataset.GetRasterBand(band_index + 1)
    md = band.GetMetadata()
    geotransform = dataset.GetGeoTransform()
    wkt = dataset.GetProjection()
    data = band.ReadAsArray()

Yes! This looks like it will work, thank you!

octobernight
Nov 25, 2004
High Priest of the Christian-Atheist Church
This is a weird bug, but I hope someone knows what's going on. I have a module named foo, and a script run_foo.py.

When I run the script, I get the error message:
code:
/lusr/bin/python /u/octobernight/programs/foo/run_foo.py
Traceback (most recent call last):
  File "/u/octobernight/programs/foo/run_foo.py", line 7, in <module>
    from foo import logger
ImportError: No module named foo
However, if I run the script under python debugger from the exact same location,
code:
/lusr/bin/python -m pdb /u/octobernight/programs/foo/run_foo.py
, I can execute line 7 without any error message.

code:
(Pdb) n
> /u/octobernight/programs/foo/run_foo.py(7)<module>()
-> from foo import logger
(Pdb) n
Can someone explain why this behavior can occur?

keyframe
Sep 15, 2007

I have seen things
Another day another question :unsmith:

I am trying to write a function that appends a user input number to the end of the list, this is what I have so far:

code:
numbers = [1,4,5]


def list_adder(n):
    n.append(int(input("enter number")))
    return n
  
    
    
print list_adder(numbers)
It works when you enter a number. I have been trying to write a if statement inside the function that checks if the input is numbers and give a "not a number" message if it is string. Did some search online and it seems the way to do a check for that is .isdigit() but it seems isdigit does not work with lists. What can I do here to accomplish this? Using python 2.7.5 by the way.

salisbury shake
Dec 27, 2011
code:
numbers = [1,4,5]
def list_adder(n):
    number = raw_input('Enter number: ')
    if number.isdigit():
      n.append(int(number))
    else:
      list_adder(n)
    return n
print list_adder(numbers)

Adbot
ADBOT LOVES YOU

FoiledAgain
May 6, 2007

keyframe posted:

Another day another question :unsmith:

I am trying to write a function that appends a user input number to the end of the list, this is what I have so far:

code:
numbers = [1,4,5]


def list_adder(n):
    n.append(int(input("enter number")))
    return n
  
    
    
print list_adder(numbers)
It works when you enter a number. I have been trying to write a if statement inside the function that checks if the input is numbers and give a "not a number" message if it is string. Did some search online and it seems the way to do a check for that is .isdigit() but it seems isdigit does not work with lists. What can I do here to accomplish this? Using python 2.7.5 by the way.


The .isdigit() is a method that only works on strings, so you have to check it with an individual elements of the list, not on the list itself. For example, you write mylist[0].isdigit() to check if the first element of the list is a digit.

However, this will still throw an error if the element of the list you are checking is not a string. If mylist=[1,2,3] and I ask mylist[0].isdigit() then I'll get an AttributeError because mylist[0] is an integer, not a string, so it has no .isdigit() method.

If you want to just check that an object is a string you can do either of the following:

type(x) == str
isinstance(x,str)

So you can loop through your list and check each one of them this way (among many other ways) and then raise an error or whatever if you find one that doesn't work.

code:
for thing in mylist:
    if isinstance(thing,str) and not thing.isdigit():
        raise ValueError('hey dummy only use numbers')

  • Locked thread