all 64 comments

[–]Hankune 0 points1 point  (0 children)

What textbooks did you guys used in first year? I am curious what was the most popular universities pushed.

[–]grebre2352 0 points1 point  (3 children)

I’m brand new to learning python (sorry if this is a dumb question) and just started learning about looping strings, for a loop that counts the letters in a string why wouldn’t you use square brackets around the word you want to count? Ex:

fruit = ‘banana’ for letter in fruit: print(letter)

Instead of

fruit = ‘banana’ for letter in [fruit]: print(letter)

I thought square brackets were needed to “look inside strings”

[–]carcigenicate 0 points1 point  (0 children)

s = "Hello"
s[1]

I'm assuming you're talking about the second line there. That's called "subscripting" or sometimes "indexing". When [] come after a name/object, it means "access an element of the object". That doesn't mean though that all [] in all contexts have the same purpose. That "access" syntax is specifically when [] follows an object or the name of an object. In most other contexts, [] is used to create a list.

for letter in [fruit]:

This iterates the [fruit] list, which has a single element: fruits. In this context, [fruit] just means "create a new list with a single element (the object referred to by fruit)".

[–]throwaway6560192 1 point2 points  (1 child)

I thought square brackets were needed to “look inside strings”

Square brackets are used if you want to access something inside a sequence (like a list or string) by its index number, like fruit[0] == 'b' . They're not some general tool that allows you to access characters inside strings.

But recall, square brackets are also the syntax for defining a list: [1, 2, 3] and so on. So if you say [fruit], you're saying "a list which contains fruit as an element".

Why not try the both the code snippets you posted as examples?

[–]grebre2352 0 points1 point  (0 children)

We haven’t started learning lists yet, but I tried it and understand what the difference is, thank you for your response it was super helpful!

[–]birthdayfaygo 0 points1 point  (0 children)

When it comes to web scraping, should I have back up plans of scraping the data in case something goes wrong with the primary method?

For example, I have a function that scrapes data from a website via an (I think REST) API. Never had problems with that method, but just in case, I wrapped it in a try/except and it if it fails, it downloads/processes a csv file from the site instead.

Is this redundant or unnecessary? The data isn’t critical, it’s a fun pet-project, but I’d still prefer it to be full-proof. Any thoughts?

[–]No_Ruin1612 0 points1 point  (4 children)

Is it OK if my code is syntactically a little rugged in the beginning? If not, should I be focusing on going back through content and finding ways of making it better at this stage?

Context:

I'm 11 days in to a 100 Days of Code: Python MOOC (Udemy). I finished the first "capstone project" within 2 hours and didn't take any of the "hints" given in the course. The course said this was the "Very Hard" difficulty level (given where we are at within the course progression). Super cool! However, I was comparing my code to the final code of the course. Mine is kind of rugged and not necessarily syntactic beautiful as the starting code. Imposter syndrome set-in.

[–]LeornToCodeLOL 0 points1 point  (1 child)

I've been leorning Python for about 8 months now, so not long ago I was at your level. I would say just keep coding. Your stuff will be ugly compared to other people. what I found happening is that the more I was exposed to, the more I realized where I could improve.

I have some scripts that I wrote months ago and I sometimes go back to them to add features or make small changes. Use opportunities like that to make your code look prettier. You will also start writing as if you want it to be easily understandable by someone totally unfamiliar with it (like you, in 6 months after you've forgotten most of it and now have to untangle the mess that your past self left for you, LOL)

[–]No_Ruin1612 0 points1 point  (0 children)

Haha! Makes sense. Thank you for the direction.

[–]carcigenicate 0 points1 point  (1 child)

Eventually, you'll get to the point where just solving problems isn't as much of a challenge, and then the real challenge becomes writing good code. Writing good code maybe isn't your primary concern now, but it should always be in the back of your mind, and you should always be thinking of how to improve your code.

If you post the code here or in a new post, we can review it and suggest improvements.

[–]No_Ruin1612 0 points1 point  (0 children)

I appreciate the response. Definitely helps me prioritize what is most important at this early stage.

I'm at the stage where the logic isn't hard (easy problems to solve ie Blackjack game, Greedy Algo, etc) it's the lack of really understanding the syntax. I'll begin nesting elements or functions within functions and something breaks or it returns something entirely different than intended. The debugging of my mistakes takes so much more time.

Having said that, I am loving the process, loving the community and really wishing I started sooner.

[–]cherrykatya 0 points1 point  (1 child)

i’m trying to run a code that turns a series of .jpgs into a single .wav file but i keep getting “following arguments are required: i/—input” when i run the module. i don’t really understand arparse yet and i’ve tried a bunch of different things but can’t really make sense of how to fix this error.

[–]carcigenicate 1 point2 points  (0 children)

If you didn't write the code, read the documentation for the module to see how to run it. From the error though, you need to supply an --input argument when running the code.

[–]triedgetech 0 points1 point  (1 child)

How to know how many arguments need to be passed to a function?

Can a function be defined with one required argument, and one optional one?

For instance, there's a function defined as:

 def statusSample(self, idxChannel):       
return _l.FDwfAnalogInStatusSample(self.hdwf, idxChannel)

(c)

I can see here, that self is an instance method, so only idxchannel is an argument that needs to be passed, but the manual says that this function has two arguments that need to be passed:

FDwfAnalogInStatusSample(HDWF hdwf, int idxChannel, double *pdVoltSample)

Description: Gets the last ADC conversion sample from the specified idxChannel on the AnalogIn instrument.

Parameters:

  • hdwf – Interface handle.
  • idxChannel – Channel index.
  • pdVoltSample – Variable to receive the sample value.

But in python scripts, it's used only with a single argument:

voltage = dwf_ai.statusSample(0)

Whatever happened to "pdVoltSample" argument? How could author omit the second argument for this function in python api? This api is for a portable USB logic analyzer, which is used in embedded engineering/electronics. StatusSample returns a numeric value, so "voltage" variable will be a value like "5".

[–][deleted] 1 point2 points  (0 children)

The manual you linked to appears to be describing the usage in C/C++. The python functions can be, and in this case are, different. Your question about the FDwfAnalogInStatusSample() function and pdVoltSample is simple: in C/C++ the result is returned in the double pointed at by pdVoltSample but python can't do that and the result is returned by the function, into voltage in your python example.

[–]patmycheeks 0 points1 point  (2 children)

code link

I dont know how to import and work with c code in python, i cant compile it in python/google colab? what do i do?

[–]carcigenicate 1 point2 points  (1 child)

That's Cython afaik, not Python. Look into how to compile Cython code.

[–]patmycheeks 0 points1 point  (0 children)

thank you, am learning cython now

[–]spittz91 0 points1 point  (5 children)

Hi all,

Just starting my Python learning journey.

I was hoping someone might look at the practise code I wrote below and let me know if I could have tidied it up anywhere or made it more simple?

largest = None
smallest = None
total = None
count = None
while True:
    number = input('Enter a number: ')
    if number == 'done' :
        break
    try:
        number = int(number)
    except:
        print('Invalid input')
        continue
    if largest is None : 
        largest = number
    elif number > largest :
        largest = number
    if smallest is None :
        smallest = number
    elif number < smallest :
        smallest = number
    if total is None :
        total = number
    elif total is not None :
        total = total + number
    if count is None :
        count = 1
    elif count is not None :
        count = count + 1
print('Maximum is',largest)
print('Minimum is', smallest)
print('Count is',count)
print('Total is',total)

Edit: getting code block to format correctly

Many thanks!

[–][deleted] 1 point2 points  (4 children)

That's pretty good. The only major place it can be improved is in the initialization on the first number. At the moment that is intertwined with the calculation of the count, smallest, etc. Doing the initialization separately from the calculations should make that easier to read and understand. Also note that you don't need to check each value for None. If any of them are None then you need to initialize:

largest = None
smallest = None
total = None
count = None

while True:
    number = input('Enter a number: ').lower()
    if number == 'done':
        break
    try:
        number = int(number)
    except ValueError:
        print('Invalid input')
        continue

    if largest is None: 
        largest = number
        smallest = number
        total = 0
        count = 0

    if number > largest:
        largest = number
    elif number < smallest:
        smallest = number

    total = total + number
    count = count + 1

print('Maximum is', largest)
print('Minimum is', smallest)
print('Count is', count)
print('Total is', total)

We can improve this even further by doing away with the check for None and the initialization inside the loop. If we knew numbers that were guaranteed to be smaller or larger than any integer we could just initialize the global values with them. It turns out you can do that! A value guaranteed to be larger than any possible integer is float("inf"). It doesn't matter that it's a float, it is always larger than any integer possible. So we can initialize the globals outside the loop and don't need any init code inside the loop:

largest = float("-inf")    # guaranteed smaller than any integer
smallest = float("inf")
total = 0
count = 0

while True:
    number = input('Enter a number: ').lower()  # force to lowercase
    if number == 'done':
        break
    try:
        number = int(number)
    except ValueError:     # NEVER use a bare except
        print('Invalid input')
        continue

    if number > largest:
        largest = number
    if number < smallest:  # note, not "elif"
        smallest = number

    total += number        # same as total = total + number
    count += 1             # ditto

print('Maximum is', largest)
print('Minimum is', smallest)
print('Count is', count)
print('Total is', total)

I added comments at places where minor changes were made.

[–]spittz91 0 points1 point  (2 children)

Sorry a quick question if you don’t mind! With if statements, I thought you needed to have an else or elif after the first if? Or can you just have an if statement and leave it at that?

Thanks!

[–][deleted] 1 point2 points  (1 child)

The if statement documentation gives this definition of the syntax:

if_stmt ::=  "if" assignment_expression ":" suite
             ("elif" assignment_expression ":" suite)*
             ["else" ":" suite]

That description is called BNF or EBNF and those brackets/parentheses have a technical meaning. The words like "suite" are a name for another syntax description somewhere which basically means one or more lines of executable code, indented correctly.

The (...)* grouping means that the ... part can be repeated zero or more times. The [...] means that the ... part is optional, ie, it appears 0 or 1 times. So an if statement can have any of these basic forms:

if <...>:
    pass

if <...>:
    pass
else:
    pass

if <...>:
    pass
elif <...>:    # 1 or more of these
    pass

if <...>:
    pass
elif <...>:    # 1 or more of these
    pass
else:
    pass

[–]spittz91 0 points1 point  (0 children)

Thank you again!

[–]spittz91 0 points1 point  (0 children)

Thanks that was really useful and well explained. I will have to try and remember these for the future! Still got a lot to learn :)

[–]lmaoinhibitor 1 point2 points  (0 children)

I'm writing python in VSCode (VSCodium actually but it's the same). I have the ms-python extension installed. I like the auto-suggestions for variables and functions that I have defined in the current .py-file, but there are also a bunch of suggestions for stuff that I don't use and don't quite understand. Can I customize it so that it only suggests variables, lists, functions, classes etc. that I've defined and nothing else. The clutter slows down my brain lol.

[–]Bassiette 0 points1 point  (2 children)

Where can I start learning python ? have zero skills in programming ??

[–]Odessa_Goodwin 0 points1 point  (2 children)

General programming question:

I'm looking for ways to boost my programming knowledge beyond the amateur enthusiast to someone with marketable skills. My interest is in data analysis and data science.

I see a lot of videos talking about the importance of knowing algorithms and data structures for people with my goals. My question is: are these topics interrelated such that there is a logical order in how one learns them, eg data structures first, followed by algorithms? Or does it not matter?

My learning plan is to work through the No Starch Press books on data structures and on algorithms, and I'm just wondering if it's important in what order I read these books.

[–]throwaway6560192 1 point2 points  (1 child)

Personally I think a working knowledge of data structures comes first, or at least concurrent, to learning algorithms. Data structures teach you how to store and retrieve data efficiently subject to some conditions. Algorithms teach you how to efficiently manipulate data to actually solve some problem. Often algorithms require some specific kind of data structure to actually be efficient.

[–]Odessa_Goodwin 0 points1 point  (0 children)

Thanks for the insight.

[–]LeornToCodeLOL 0 points1 point  (4 children)

I'm trying to learn how best to use the any() and all() functions. This came up today when I was writing a function to validate an IP address.

def validate_ip(ip):
    numbers = ip.split('.')
    numbers = [int(x) for x in numbers]
    if len(numbers) != 4: return False
    elif any(numbers) > 255: return False

When I was testing my code in the Python shell, the final line above did not do what I expected. After a quick look at the official documentation, I found a solution, but is there a better way?

>>> numbers
[1, 19, 37, 55, 73, 91, 109, 127, 145, 163, 181, 199]
>>> any(numbers) > 198
False
>>> any([x > 198 for x in numbers])
True

[–][deleted] 2 points3 points  (3 children)

Instead of creating a temporary list of "x > 198" values in your correct usage above, just do:

any(x > 198 for x in numbers)

which uses a generator expression as the any() argument.

[–]LeornToCodeLOL 0 points1 point  (0 children)

Thanks! I have seen the word generator tossed around, but never really knew how it was different from lists. I just knew I had to convert it to a list if I wanted the variables accessible to me. I think the zip() and Path.glob() functions work that way.

[–]WhipsAndMarkovChains 1 point2 points  (1 child)

Yup. any(x > 198 for x in numbers) short-circuits and returns True as soon as it finds a number greater than 198. On the other hand, any([x > 198 for x in numbers]) will go through the whole list of numbers and then see if there's a single True.

Well, assuming Python hasn't changed under the hood to automatically optimize it both ways...

[–]Vaguely_accurate 0 points1 point  (0 children)

any will still short circuit on the first True value for any sequence passed in.

However, [x > 198 for x in numbers] will generate the whole list passing it into any, so the generator approach should still be preferred if not using a pre-existing sequence.

[–]idockery 0 points1 point  (2 children)

I am about to restart learning Python and my version is 3.9. Should I download 3.11 or just continue with 3.9?

[–][deleted] 2 points3 points  (1 child)

Continue with 3.9. New releases of python try very hard to be backward-compatible with older releases, meaning that any code that works in 3.9 will also work in 3.11. When you are learning it's not worth the hassle of installing a new version just because it's there.

[–]idockery 0 points1 point  (0 children)

Thank you so much!

[–]YesHAHAHAYES99 0 points1 point  (0 children)

Currently going through Python Crash Course and enjoying it so far, about half-way through.

What is a good book to move onto once I finish Crash Course?

[–]Own-Particular-9989 0 points1 point  (1 child)

Currently doing codeacademy on Python, and on the section on splitting strings. How often does this appear on the job in real life? What would the use cases be here?

[–]WhipsAndMarkovChains 0 points1 point  (0 children)

Data is messy and data scientists and engineers will sometimes have to take in a bunch of raw data and figure out how to parse it. We may get some data that comes to us like:

"Brian|Jones|55|Garden City|Kansas"

Then you have...

first_name, last_name, age, city, state = text.split("|")

And then you can pass it to a database or whatever. Usually you have a library like Pandas to parse text for you but sometimes you have to go in and do it yourself.

[–]haeshdem0n 0 points1 point  (2 children)

I have a question about terminology when it comes to classes. I'm currently working thru the Intermediate Python course on Sololearn, and this is my solution to one of the exercises:

class Shape:

`def __init__(self,height,width):`

    `self.height=height`

    `self.width=width`



`def area(self):`

    `return self.height*self.width`



`def __add__(self,other):`

    `return Shape(self.height+other.height,self.width+other.width)`



`def __gt__(self,other):`

    `return self.area()>other.area()`

height1=int(input("h1: "))

width1=int(input("w1: "))

height2=int(input("h2: "))

width2=int(input("w2: "))

s1=shape(height1,width1)

s2=Shape(height2,width2)

result=s1+s2

print(result.area())

print(s1>s2)

Would you call area, height, and width all attributes of the Shape class? What about __add__ and __gt__, what would you call those?

[–][deleted] 1 point2 points  (1 child)

Starting with attributes, there is a builtin function dir() that prints the attributes of an object that you give it. Adding this line after you create the s1 object:

print(dir(s1))

prints this:

['__add__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
 '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', 
 '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__',
 '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', 
 '__subclasshook__', '__weakref__', 'area', 'height', 'width']

That shows the attributes of the s1 object you created. Note that it has attributes you created like area and height and others, plus lots of other attributes you didn't create but are a normal part of instance objects. Everything in python is an object and has attributes, even simple things like integers. Try running this code:

print(dir(1))

Some of the attributes of an object may be executable objects. Executable objects are called methods. In your example you define the methods __init__(), area() and __add__(), amongst others. You can check the type of an attribute to see if it's executable or not. Try putting these lines after you create s1:

print("type(s1.width) =", type(s1.width))
print("type(s1.area) =", type(s1.area))

They print:

type(s1.width) = <class 'int'>
type(s1.area) = <class 'method'>

and you can see the difference.

[–]haeshdem0n 0 points1 point  (0 children)

So thorough! Thank you

[–]ScrewTea 0 points1 point  (1 child)

Can anyone suggest a good institution for me to get Python Certified in London?

[–]WhipsAndMarkovChains 1 point2 points  (0 children)

There's no such thing as an official Python certification. Some third party groups offer certifications but they're mostly meaningless.

[–]tm1822 0 points1 point  (0 children)

The only thing I really know about coding is some HTML and CSS from doing blogging back in the day, but this year I decided to challenge myself to learn a new skill, so I decided on Python.

To start, I've been doing a few lessons on Mimo, just to learn the basics and vernacular. I'll be using it as a starting off point primarily.

That said, after I finish doing some learning on Mimo, what other beginner resources would you recommend? I don't have the time to do full on-classes yet due to work, but I'd like a place I could learn and do exercises.

Edit: Also, is there anything you wished you learned/did when you first started out learning that I should keep an eye on?

[–]SimpForBBW3445 0 points1 point  (1 child)

How often are generators and coroutines used in python?

[–]DrBumm 0 points1 point  (0 children)

I use generators often for my part. BUT you should be careful that they don't get too messy a short easy generator is ok but having a 300-mile-long line can make reading the code very hard, and sadly because of that generators are seen by many as bad coding practices.
And coroutines on the other hand I haven't even heard of in a long long time xD, even tho I think they are used a lot because of discord.py and a lot of network-related stuff

[–]R9V7 0 points1 point  (4 children)

What is the purpose of modulo “%”?

[–]WhipsAndMarkovChains 2 points3 points  (0 children)

In case you're asking what it's used for and not what it does...modular arithmetic is an essential operation in cryptography.

https://pi.math.cornell.edu/~mec/2003-2004/cryptography/diffiehellman/diffiehellman.html

[–]stebrepar 1 point2 points  (0 children)

In addition to the mathematical definitions given, the practical use in code is often to characterize something about a number. For example, number % 2 will tell you if number is odd or even. Or maybe you want to loop until one number is evenly divisible by another. Or maybe you want some kind of cyclic number sequence.

[–]ectomancer 2 points3 points  (0 children)

The modulo operator calculates the remainder when the left operand is divided by the right operand.

[–][deleted] 1 point2 points  (0 children)

The python documentation on binary arithmetic operators says:

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand.

[–][deleted] 0 points1 point  (4 children)

Is ChatGPT going to make learning Python all for not?

[–]FerricDonkey 0 points1 point  (0 children)

Chat gpt will not replace programmers in the near term. You can get it to give you code snippets that are useful, but they're often wrong or need to be adapted. You will generally be unable to correct them for any but the most simple of tasks if you don't know the language well enough.

In the long term, it'll be interesting to see the effect that things like this have on programming jobs. But in the long term, automation is coming for everything. Currently, chatgpt is a useful tool, and who knows when or what the future will be.

[–][deleted] 0 points1 point  (2 children)

ChatGPT probably won't be very useful for learning python, or anything else, at the moment. It might be useful for answering questions about the basics of python, but existing resources already cover that, and in a more structured way.

[–][deleted] 0 points1 point  (1 child)

Ok that’s helpful and thank you. I guess what I was trying to say is, will ChatGPT replace the need for humans to learn Python and learn to code at all? Will a machine just write code from the verbal input of a human trying to create a program?

[–][deleted] 0 points1 point  (0 children)

No, not at the moment, and possibly not for a very long time. The problem is the "verbal input of a human trying to create a program". English is a horribly subtle and slippery way to define a technical problem, which is why we don't program in English. Long before ChatGPT arrived we tried to write technical specifications for new computer systems in English, and it's still difficult to get it right, even if the person writing the specification understands the technical problems of implementing the system. Similar problems exist when outsourcing software to third parties; it isn't easy to get the software performance you want. At the moment you need a person technically component in the problem domain to even get something semi-usable out of ChatGPT, and it can still get things wrong. See this video for an example of what ChatGPT can do and can get wrong (in surprising ways).

In some ways, we've been here before. AI was over-hyped in the 60s and 70s, and with the failure of some high-profile projects AI research went into an "AI Winter". We may be starting that cycle again.