The new forums will be named Coin Return (based on the most recent vote)! You can check on the status and timeline of the transition to the new forums here.
The Guiding Principles and New Rules document is now in effect.

Learning Python While Under Lockdown in China

Loren MichaelLoren Michael Registered User regular
edited March 2020 in Help / Advice Forum
hello hello! I'm in China bored out of my mind because of the apocalypse virus, safe but basically idle; after a few weeks of killing it on the new Slay the Spire character, I've decided to become productive, at least until my normal work starts again

so I decided to teach myself Python 2

I'm using Learn Python the Hard Way, and so far I have an aptitude for typing things out accurately, and I'm generally pretty good at breaking down what I've done and how/why it works rather than just Cargo Culting my way through

well so now I've finally run into a wall in Exercise 33 (I'm learning about "while loops"), where I've been instructed to first do this:
i = 0
numbers = []

while i < 6:
    print "At the top i is %d" % i
    numbers.append(i)

    i = i + 1
    print "Numbers now:", numbers
    print "At the bottom i is %d" % i

print "The numbers:"

for num in numbers:
    print num

that works fine, no problem; I basically get what it all means and I'm sure it'll settle in with practice

here's where my problem is: in the study drills I've been instructed to:
1. Convert this while loop to a function that you can call, and replace 6 in the test (i < 6) with a variable
2. Now use this function to rewrite the script to try different numbers
3. Add another variable to the function arguments that you can pass in that lets you change the +1 on line 8 so you can change how much it increments by
4. Rewrite the script again to use this function to see what effect that has
5. Now, write it to use for-loops and RANGE instead. Do you need the increment or in the middle any more? What happens if you do not get rid of it?

"Convert this while loop to a function that you can call" has been giving me a hard time for the past day or so; I've done functions and I'm aware of the basic form and syntax (I think), here's something I had to do earlier in Exercise 20 for reference:
from sys import argv 

script, input_file = argv 

def print_all(f): 
    print f.read() 

def rewind(f): 
    f.seek(0) 

def print_a_line(line_count, f): 
    print line_count, f.readline() 

current_file = open(input_file)

print "First let's print the whole file:\n"

print_all(current_file)

print "Now let's rewind, kind of like a tape."

rewind(current_file)

print "Let's print three lines:"

current_line = 1
print_a_line(current_line, current_file)

current_line += 1 
print_a_line(current_line, current_file)

current_line = current_line + 1 
print_a_line(current_line, current_file)

this also didn't give me any real issues, and I think I have a good basic understanding of what all that means and with a little variety and repetition it'll settle in just fine

combing these as instructed though—if I'm reading correctly that that's what's being asked of me—is giving me a huge headache

I'm really embarrassed to show my work but here's one of many iterations that I've tried, and different ways I've tried to call it up:

one of my tries:
def blanket(pillow):
    i = 0
    numbers = []

    while i < pillow:
        print "At the top i is %d" % i
        numbers.append(i)

        i = i + 1
        print "Numbers now:", numbers
        print "At the bottom i is %d" % i

    print "The numbers:"

    for num in numbers:
        print num 

some ways I tried to call it up with no discernible result:
shangyang:lpthw LorenMichael$ python sample1.py
shangyang:lpthw LorenMichael$ python sample1.py pillow 4
shangyang:lpthw LorenMichael$ python sample1.py pillow(4)
-bash: syntax error near unexpected token `('
shangyang:lpthw LorenMichael$

anyways, please help me resolve just that one bit, I'm not sure what I'm not getting or what I am doing wrong and this is the first problem I haven't been able to resolve on my own

and please be gentle

a7iea7nzewtq.jpg
Loren Michael on

Posts

  • Loren MichaelLoren Michael Registered User regular
    also if you have any general suggestions on learning Python (or any other programming language), please let me know, I have a massive surplus of free time for at least another 2-4 weeks

    a7iea7nzewtq.jpg
  • EchoEcho ski-bap ba-dapModerator, Administrator admin
    I haven't tried it myself, but I've heard lots of good stuff about https://exercism.io/, you get an actual mentor that looks at your solution to problems and suggests improvements.

  • furbatfurbat Registered User regular
    edited March 2020

    here's where my problem is: in the study drills I've been instructed to:
    1. Convert this while loop to a function that you can call, and replace 6 in the test (i < 6) with a variable
    2. Now use this function to rewrite the script to try different numbers
    3. Add another variable to the function arguments that you can pass in that lets you change the +1 on line 8 so you can change how much it increments by
    4. Rewrite the script again to use this function to see what effect that has
    5. Now, write it to use for-loops and RANGE instead. Do you need the increment or in the middle any more? What happens if you do not get rid of it?

    I teach/taught a class on python. I'm doing something a bit um different.... for the next couple years so that's on hold. As for resources? I think you are on the right track, I'll let other people help you out.

    Ok on for the questions.

    You can define a function using white space just like you define a while/for loop. The following lines will print 'tomato'.
    def foo( potato):
        print potato
    
    foo('tomato')
    

    It's important that your function is defined before it is called in your code. Line 1 defines the function foo. Potato is the argument. Line 2 is the code executed when the function is called. Line 4 is the function call. ''tomato" is the value passed to the function. Since the function foo was defined to take an argument you must pass an argument to it.

    We can add additional arguments to our function with a comma. So foo( potato) can become foo( potato, pizza). Let's try this:
    def foo( potato, pizza):
        while pizza > 0:
            print potato
            pizza -= 1
    
    foo('tomato', 3)
    

    The output should be:

    tomato
    tomato
    tomato

    pizza -= 1 is shorthand for pizza = pizza - 1. This is useful since you will increment and decrement numbers often.

    Finally, range(n) will create a list of numbers from 0 to n-1. So range(3) will return [0,1,2]. The length of this list is n items long. This is used by python commonly in for loops. Let's add a for loop to our code and another argument.
    def foo( potato, pizza, hamburger):
        while pizza > 0:
            print potato
            pizza -= 1
        for num in range(hamburger):
            print num, potato
    
    foo('tomato', 3, 4)
    

    Try the above code.

    I hope this helps! For resources... there are so many things out there and I used none of them to learn python so I can't really help you there.

    furbat on
  • Stabbity StyleStabbity Style He/Him | Warning: Mothership Reporting Kennewick, WARegistered User regular
    Why Python 2 instead of 3? 2's been discontinued and mostly exists for legacy stuff. I guess you probably have a 2 version of the book, but I'd probably recommend switching to Python 3 exercises online instead.

    Stabbity_Style.png
  • CelestialBadgerCelestialBadger Registered User regular
    Why Python 2 instead of 3? 2's been discontinued and mostly exists for legacy stuff. I guess you probably have a 2 version of the book, but I'd probably recommend switching to Python 3 exercises online instead.

    For the purpose of learning to program in general it doesn't really matter which version, as long as the installed version of Python matches the book.

  • MorranMorran Registered User regular
    The perfect companion to "learn python the hard way" is "the python challenge", www.pythonchallenge.com

    Where "the hard way" provides very concrete directions, "challenge" is a series of increasingly tricky open-ended assignments which you need to figure out on your own.

    The first assignment just requires you to figure out how to use python as a calculator. Easy enough, but a few assignments in you need to figure out how to solve a cypher hidden in metadata of a webpage...

  • PowerpuppiesPowerpuppies drinking coffee in the mountain cabinRegistered User regular
    I suspect you're missing an unindented line that calls the blanket function you've defined. Right now I think you have a function that does what you want but not a script that calls your function. If Python reads your file from the top, it finds a function called blanket and a definition for that function. At the end of that definition, the file ends. So python says "oh, you didn't want me to do anything? Cool. I know about that function now."

    Whereas in line 14 of your exercise 20 file, you have the first statement in your script, outside of any function.

    sig.gif
  • KetBraKetBra Dressed Ridiculously Registered User regular
    edited March 2020
    So this is what you have to start with:
    i = 0
    numbers = []
     
    while i < 6:
        print "At the top i is %d" % i
        numbers.append(i)
     
        i = i + 1
        print "Numbers now:", numbers
        print "At the bottom i is %d" % i
     
    print "The numbers:"
     
    for num in numbers:
        print num
    

    What you want to do is replace the while loop in that code with a function. This is what that will look like (without defining the function)
    numbers = num_loop()
    print "The numbers:"
     
    for num in numbers:
        print num
    

    If you compare what I have with you have you'll see two significant differences. The first is that mine has a function call (the numbers = num_loop). The second is that yours has a function definition. That's something that needs to be written in mine to make it work, but give it a shot. Keep in mind the use of the return statement to pass the list you construct in the function out of it. Hopefully this is helpful!

    Footnote: It may be useful to grab yourself an development environment that will let you run your code inside it. Something like Spyder (packaged with Anaconda) or pycharm are decent places to start.

    KetBra on
    KGMvDLc.jpg?1
  • TofystedethTofystedeth Registered User regular
    Why Python 2 instead of 3? 2's been discontinued and mostly exists for legacy stuff. I guess you probably have a 2 version of the book, but I'd probably recommend switching to Python 3 exercises online instead.

    Unfortunately there's still a ton of stuff that hasn't been updated to support 3, despite it existing for like a decade. For instance, if you Google Cloud Platform stuff, that's still 2.7.

    steam_sig.png
  • ShivahnShivahn Unaware of her barrel shifter privilege Western coastal temptressRegistered User, Moderator mod
    also if you have any general suggestions on learning Python (or any other programming language), please let me know, I have a massive surplus of free time for at least another 2-4 weeks

    Do you know how to program, generally? I ask because as a kid I spent a lot of time on and off learning stuff, but I generally focused on the language and ended up burning out with bad code. As an adult I tried to learn programming/computer science more generally, and had much, much greater success. Like, I knew what a function was, but I didn't totally get classes and such because I didn't have the background to know why they might be important, and most tutorials gloss over it. The secret truth is that almost all programming language tutorials are written for people who are already at least semi-competent programmers.

    Anyway. I have not tried the stuff you're using, so I can't say if it falls into that category. What I will say is that, while I knew smatterings of things for a long time, my actual growth into a competent hobby programmer really started when I looked at MIT's Opencourseware introductory courses. I "took" (mostly, read lecture notes with serious intent to absorb) their introductory computer science courses when I had time at home or at work. It only took a couple of the courses for me to really start to understand things in a way I hadn't before. After that, I took courses that were more advanced and that I was more interested in - some of MIT's later courses, which were higher level, and some cryptography and neural network stuff in Coursera, which is really my present hobby specialty.

    All this is to say that I suggest trying to learn programming broadly, in addition to learning a language (incidentally, due to its relatively easy-to-understand nature, Python is used in a lot of introductory courses). There are a lot of good (free!) options out there, from MIT's Opencourseware, to Coursera, and others. Most have very basic courses, the beginning of which may be already known, but which likely will give you a rigorous framework to understand the theoretical reasons for things, in a way that will make you much more skilled. And they're usually pretty fun - it might just be me, but I found it hard to learn from tutorials which focused on "how" instead of "why," since writing a bunch of functions to do things so that you can learn to do functions, or making a class to make a class, doesn't stick in the head as well, or feel as satisfying, as doing those things with an understanding of what's going on and why it's a good idea.

  • Loren MichaelLoren Michael Registered User regular
    thanks for all your suggestions! had some issues yesterday but I'm going to go back to the grind today and see what's what
    Shivahn wrote: »
    also if you have any general suggestions on learning Python (or any other programming language), please let me know, I have a massive surplus of free time for at least another 2-4 weeks

    Do you know how to program, generally? I ask because as a kid I spent a lot of time on and off learning stuff, but I generally focused on the language and ended up burning out with bad code. As an adult I tried to learn programming/computer science more generally, and had much, much greater success. Like, I knew what a function was, but I didn't totally get classes and such because I didn't have the background to know why they might be important, and most tutorials gloss over it. The secret truth is that almost all programming language tutorials are written for people who are already at least semi-competent programmers.

    Anyway. I have not tried the stuff you're using, so I can't say if it falls into that category. What I will say is that, while I knew smatterings of things for a long time, my actual growth into a competent hobby programmer really started when I looked at MIT's Opencourseware introductory courses. I "took" (mostly, read lecture notes with serious intent to absorb) their introductory computer science courses when I had time at home or at work. It only took a couple of the courses for me to really start to understand things in a way I hadn't before. After that, I took courses that were more advanced and that I was more interested in - some of MIT's later courses, which were higher level, and some cryptography and neural network stuff in Coursera, which is really my present hobby specialty.

    All this is to say that I suggest trying to learn programming broadly, in addition to learning a language (incidentally, due to its relatively easy-to-understand nature, Python is used in a lot of introductory courses). There are a lot of good (free!) options out there, from MIT's Opencourseware, to Coursera, and others. Most have very basic courses, the beginning of which may be already known, but which likely will give you a rigorous framework to understand the theoretical reasons for things, in a way that will make you much more skilled. And they're usually pretty fun - it might just be me, but I found it hard to learn from tutorials which focused on "how" instead of "why," since writing a bunch of functions to do things so that you can learn to do functions, or making a class to make a class, doesn't stick in the head as well, or feel as satisfying, as doing those things with an understanding of what's going on and why it's a good idea.

    I have zero background in programming, which is why I'm going with the resource that I am, as it's EXTREMELY basic

    that said, I have a lot of friends who are more computer savvy than I am, and I grew up being generally competent with computers, and generally it's been the more technical details that have kept it foreign to me rather than not getting the general principles

    as far as adjacent skills and interests, I've been learning Chinese for the past 15 years and while I definitely don't have an aptitude for particular languages, linguistics as such is interesting to me

    my ultimate goal is that I'd like to make a calendar app* eventually akin to what Google or Apple provides—a personal hobbyhorse—and know enough to tinker with that until I'm satisfied, so I think the general shape of our interests and approaches may be slightly different, as I read you as having a broad interest that allows you to serve the narrow goals or projects you like, and I have a specific small project in mind that I hope to use to eventually serve broader interests

    I'll definitely take a look at the stuff you (and everyone else) mentioned, thanks!

    *if anyone has any very specific suggestions or resources on this narrow and hopefully simple subject, please let me know

    a7iea7nzewtq.jpg
  • Loren MichaelLoren Michael Registered User regular
    @furbat your suggestions worked like a charm and it's very easy to see how it works and such, thank you very much

    @Powerpuppies and @KetBra OMG you're right, I'd been brain farting about calling that function or maybe how to call that function; I synthesized what I did with furbat's suggestion and the original thing I posted above which was an easy tweak and worked perfectly:
    def blanket(pillow):
        i = 0
        numbers = []
    
        while i < pillow:
            print "At the top i is %d" % i
            numbers.append(i)
    
            i = i + 1
            print "Numbers now:", numbers
            print "At the bottom i is %d" % i
    
        print "The numbers:"
    
        for num in numbers:
            print num
    
    blanket(6)
    

    I'm sure I'll have many other forehead slappers, in the meantime thanks a lot; a simple thing I'd been overlooking is a lot more manageable than Fundamentally Not Getting It, so I'm really relieved

    a7iea7nzewtq.jpg
  • discriderdiscrider Registered User regular
    Programming is mostly overlooking simple things, so I think you've got it now.

  • SmrtnikSmrtnik job boli zub Registered User regular
    Also keep in mind "calendar" is something that sounds deceptively simple, but it's actually hard to make a correct one because humans made a lot of weird special rules about it over the centuries. For an example, look at rules for leap years.

    Generally, the professional advice for making a calendar functionality for an application that's sold to do something else is: use a library that comes with the language or someone else wrote that millions have vetted.

    steam_sig.png
  • CampyCampy Registered User regular
    Smrtnik wrote: »
    Also keep in mind "calendar" is something that sounds deceptively simple, but it's actually hard to make a correct one because humans made a lot of weird special rules about it over the centuries. For an example, look at rules for leap years.

    Generally, the professional advice for making a calendar functionality for an application that's sold to do something else is: use a library that comes with the language or someone else wrote that millions have vetted.

    A thousand times this. Dates, times and timezones are an absolute minefield of obscure edge cases. Due to the recent leap day, there was a bunch of web applications that were shown up to not be utilising a decent datetime library. Some were benign, Facebook was only showing posts from 4 years ago on their "This time last year" posts. Some less so, e.g. a fairly widely used stocks and shares trading application straight up stopped letting you trade for a day. Not ideal in the current financial climate!

    If you're looking for a more advice around programming on the forums, there's a whole bunch of experienced programmers that post in the programming thread. It can be quite high level discussion at times, but don't let that put you off, people will be happy to help out a new starter.

  • KetBraKetBra Dressed Ridiculously Registered User regular
    edited March 2020
    Smrtnik wrote: »
    Also keep in mind "calendar" is something that sounds deceptively simple, but it's actually hard to make a correct one because humans made a lot of weird special rules about it over the centuries. For an example, look at rules for leap years.

    Generally, the professional advice for making a calendar functionality for an application that's sold to do something else is: use a library that comes with the language or someone else wrote that millions have vetted.

    See:
    https://www.youtube.com/watch?v=-5wpm-gesOY

    Thankfully Python has a few different ways of dealing with time in its various forms that removes some of this thinking. Yay! (Even so, you can still run into problems)

    KetBra on
    KGMvDLc.jpg?1
  • ArbitraryDescriptorArbitraryDescriptor Registered User regular
    edited March 2020
    Smrtnik wrote: »
    Also keep in mind "calendar" is something that sounds deceptively simple, but it's actually hard to make a correct one because humans made a lot of weird special rules about it over the centuries. For an example, look at rules for leap years.

    Generally, the professional advice for making a calendar functionality for an application that's sold to do something else is: use a library that comes with the language or someone else wrote that millions have vetted.

    Though as a self-learning exercise, trying to develop a logical framework to represent the gregorian calendar is great way to drill home how complicated simple things can get when you start stacking them up with no real plan, and how seemingly harmless band-aids, like leap years, can come back and bite you in the ass later.

    "I can just etch an extra day on the February every four years. I think I can handle an extra five minutes of work every four years :p"

    ArbitraryDescriptor on
Sign In or Register to comment.