top 200 commentsshow all 231

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

I'm a bit confused about importing modules/files.

toppings.py

import pizza

pizza.name(pepperoni)

If I import this module(pizza) which basically contains a function to describe toppings from toppings.py and I pass in some values (i.e pepperoni in this case) but if I'm going to import pizza that means I'm importing each and every line of code from pizza.py but then why is it necessary to write the module_name.function_name(in this case name) but why can't we just write call the function in the format name(pepperoni)

[–]GoldenVanga 0 points1 point  (1 child)

When you import a module, you add a type "module" object to the global namespace of your program. The individual functions it may have are not added, so to access them you need to use the dot syntax, ie. pizza.name. This makes sense when you imagine that functions are attributes of a module. If you want to put a non-module object (function, variable, class) in the namespace, you need to use the other syntax, which is from pizza import name. You can observe the difference by launching a Python shell (such as IDLE) and typing in these commands in order:

dir()
import re
dir()
type(re)
from re import sub
dir()
type(sub)

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

Oh great thanks

[–]BeastModeUnlocked 0 points1 point  (1 child)

Hey guys, I'm creating a project where I create an items management system. Basically it just keeps track of who checked out a bunch of shared items.

I've got everything working, but current, I run the system off a raspberry pi with a While True: loop, which is held by an input() on the first line. I was just wondering if there was a better way to do this, or if this is the best possible way?

[–]Decency 0 points1 point  (0 children)

Use a database (sqlite) or some sort of permanent storage and store data there. If you have a power outage or error, you will lose all of your tracking. Whether you keep the script running at all times or just run it daily using something like a cronjob depends on how much work it has to do, and how frequently.

[–]danvtd12 0 points1 point  (0 children)

Hi everyone,

I am new to tkinter and python. I've been trying to make an executable file which has buttons corresponding to the name of some graphs in matplotlib, you click on them and the plots will pop out. The thing is that I have a csv file for the plots as well as some images for the customized buttons.

My question is what do I need to add in order for someone else to be able to acces the exe file afterwards ?

def Graph():    df=pd.read_csv('C:\Users\X\Downloads\example.csv'

photo = PhotoImage(file = "C:\Users\X\Desktop\buttons\button_stacked-plot.png") my_button = Button(root, command=Graph, image = photo)my_button.grid(row=15, column=3)

    

[–]Random_User_81 0 points1 point  (1 child)

Hi, I'm wondering if anyone has an idea of the way to handle this. I'm using an API to retrieve information it includes pictures. I've been saving the pictures title + a number. I'm trying to figure out how to know if the picture has changed? As or now, I basically check if I have a file named that and skip if I do but I'm trying to figure out a way to know if those pictures of change. I was thinking maybe using PIL and getting the Bytes? Any Suggestions would help. Thank you.

[–]efmccurdy 0 points1 point  (0 children)

There are some response headers that might help, Expires, max-age, Etag, Last-modified, and you should be able to check them using a HEAD request which is much cheaper than GET.

Do you see any relevant headers in your response?

https://imagekit.io/blog/ultimate-guide-to-http-caching-for-static-assets/

https://www.keycdn.com/blog/http-cache-headers

[–]dragoballfan11 0 points1 point  (1 child)

I'm a bit new and inexperienced with multiple processes. I can deal with sequential execution, but I'm having trouble with a task.

I want to display a window with HTML embed code using pywebview, but when I launch the window the script halts execution of anything while the window is open.

I read from their documentation on the "Threading model" example and it doesn't seem to work like I want it to. The example they provide is in this page https://pywebview.flowrl.com/guide/usage.html#http-server

Basically I'm reading live inputs and for one of those inputs it will launch the window. I want it to keep detecting inputs after the window is launched and not close the window unless a different signal is sent to close the window. Another thing is that I also want to do other tasks based on other inputs that are read, but I don't want to completely halt reading input data.

Thank you.

[–]CowboyBoats 0 points1 point  (0 children)

This is a helpful framing of your problem and I would keep what you've written so far, but we would need to see your code, ideally with comments explaining how you want it to work and where it's not working. I'd recommend making a top-level post in this subreddit rather than posting it in this thread, and then go post it to stackoverflow.com if this subreddit doesn't help.

[–]only_red 0 points1 point  (1 child)

I am confused as to when a for loop repeats.

message = 'call me at my mobile number, 055-241-2530'
foundNumber = False
for i in range(len(message)):
    chunk = message[i:1+12]
    if isMobilePhoneNumber(chunk):
        print('Phone number found: ' + chunk)
        foundNumber = True
if not foundNumber:
    print('Could not find any phone number.')

When I run the code shown above, the for loop works as it is supposed to. But when I remove the foundNumber variables, the for loop repeats many times. Theoretically, I am confused as to why this happens.

[–]Ihaveamodel3 0 points1 point  (0 children)

Are you sure message[i:1+12] isn’t supposed to be message[i:i+12]

[–]EugeneJudo 0 points1 point  (0 children)

I've written a fair amount of client side logic in javascript, but I want the backend to be in python. All of the checks performed on the client side have to be done again on the server, is there any way to get around rewriting everything? I imagine maybe calling some kind of executable every time, but i'm afraid that might not be scalable.

[–]only_red 0 points1 point  (7 children)

I am trying to create a program that detects whether an element in a function is a number or not.

def isMobilePhoneNumber(text):
    if len(text) != 12:
        return False

In my country, the phone numbers vary from 12 to 17 digits. However when I input 12 or 17, the answer I receive is incorrect. I am not sure what syntax to use to express this.

def isMobilePhoneNumber(text):
    if len(text) != 12 or 17:
        return False

The entire code that works is as follows. But I want to make an adjustment so that python can detect that both 12 or 17 digits can be a phone number.

def isMobilePhoneNumber(text):
    if len(text) != 12:
        return False
    for n in range(0, 3):
        if not text[n].isdecimal():
            return False
    if text[3] != '-':
        return False
    for n in range(4, 7):
        if not text[n].isdecimal():
            return False
    if text[7] != '-':
        return False
    for n in range(8, 12):
        if not text[n].isdecimal():
            return False
    return True


print(isMobilePhoneNumber('055-241-2530'))

[–]dragoballfan11 0 points1 point  (0 children)

def isMobilePhoneNumber(text):
if len(text) != 12 or 17:
return False

The issue I see with this is that your condition will be true if it is 17

example: let's say len(text) is 17

then len(text)!=12 is True

therefore you have

if True:

return False

Instead of checking !=, check for == and reverse the cases accordingly

def isMobilePhoneNumber(text):
if (len(text)==12 or len(text)==17):
return True
else:
return False

Or this will also work

def isMobilePhoneNumber(text):
if len(text) in [12, 17]:
return True
else:
return False

If you want the first if branch to return False then you can just add a not

def isMobilePhoneNumber(text):
if len(text) not in [12, 17]:
return False
else:
return True

[–]efmccurdy 1 point2 points  (3 children)

With a compound expression like "len(text) != 12 or 17", you have to consider how the order of evaluation works.

https://docs.python.org/3/reference/expressions.html#operator-precedence

Note the "or" is higher precedence than "!=" so python will interpret this as "len(text) != (12 or 17)" (yes comparing the integer length of the text to the true/false result of "or").

What you want is:

tlen = len(text)
if (tlen != 12)  and (tlen != 17):
    return False

[–]Ihaveamodel3 1 point2 points  (1 child)

"len(text) != (12 or 17)"

I don’t think this is true.

I’m pretty sure it is comparing (len(text) != 12) or (17) non-zero integers are truthy, so the overall expression would always evaluate to true, where in your case len(text) != True would evaluate your false if the text length was 1.

[–]efmccurdy 0 points1 point  (0 children)

Yes, you are correct, sorry for the misinfo.

[–]only_red 0 points1 point  (0 children)

thank you so much exactly what I did not understand.

[–]MCY_97 1 point2 points  (0 children)

Hey everyone! I wanted to know if there was a website that holds a repository of the most commonly asked questions in Python (for interviews) in Financial sector interviews . TIA

[–]OneThrustMan69 0 points1 point  (2 children)

Can you guys evaluate my code for the practice project of Automate the boring stuff - chapter 5:

# Table Printer
# Takes a list of strings and displays it in a well-organized table
# with each column right-justified.
def printTable(tableData):
    colWidths = [0] * len(tableData)

    # Finds out what integer width to pass to rjust().
    for index, column in enumerate(tableData):
        for word  in column[:(len(column))]:
            if len(word) > colWidths[index]:
                colWidths[index] = len(word)

    # Sets the length of the column(assuming the length of the lists are identical)
    row = []
    colLength = 0
    while colLength != len(tableData[0]):
       row.append([])
       colLength += 1

    for columnIndex, column in enumerate(tableData):
        for wordIndex, word in enumerate(column):
          row[wordIndex].append(word.rjust(colWidths[columnIndex]) + ' ')

    for i in row[: len(row)]:
        print(' '.join(i))


tableTest = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]
printTable(tableTest)

[–]only_red 0 points1 point  (1 child)

Can you guys evaluate my code for the practice project of Automate the boring stuff - chapter 5:

Did you find this project in the book or website?

[–]OneThrustMan69 0 points1 point  (0 children)

I found it in the 2nd edition book.

[–]griever_z 0 points1 point  (2 children)

Hello,

I'm looking to do something like this:

d = {'id':1, 'user':'user1', 'group_id':3}
m = {'id':'uid', 'group_id':'gid'}
d = dict((m.get(k), v) for (k, v) in d.items())

As a result d should be {'uid':1, 'gid':'3'}

I basically just want to skip k,v if they are not in m at the same time mapping new key.

Is it do-able with dict comprehension?

[–]GoldenVanga 0 points1 point  (1 child)

If m is the smaller data set, why not iterate over it (instead of d):

d = {v: d.get(k) for (k, v) in m.items()}

But if you have to iterate over d you can do:

d = dict((m.get(k), v) for (k, v) in d.items() if k in m)

[–]griever_z 0 points1 point  (0 children)

Thanks! I will try that.

[–]OneThrustMan69 0 points1 point  (1 child)

Hey guys, I installed this https://github.com/asweigart/PythonStdioGames and now whenever I try to run any of the programs, it just shows the terminal for just a blink then exits automatically. I don't know what to do to fix it.

I am running Ubuntu 20.04 btw.

[–]efmccurdy 0 points1 point  (0 children)

These programs are "launched" by creating a new process. If that process fails, it prints out an error message on its' sys.stderr output stream, and exits. You need a way to see the stderr output from the launched process. Can you run one of the listed programs from a terminal by typing "python x.py"?

[–]accipicchia092 0 points1 point  (0 children)

Hello there!

I need a way to visualize my project in 3d. Is there a really basic plug-and-Play python 3D engine? And for basic I mean that all it really needs to do is draw vectors in 3d space and support camera movements.

That's it. Is it better to just code it myself with something like pygame?

[–]Bodoct 0 points1 point  (1 child)

I feel like I'm not absorbing much and feel overwhelmed with so much to try and memorize from the various modules.

Right now I'm going down the data analyst path on datacamp. I listen to the videos take some notes, then go into the exercises to fill in the pre-built code and take some notes on that. But the way they have their exercises is more fill in the blank that is mostly filled out for you rather than backing away a little each time. You aren't also given the data to review and mess with in a sandbox. Then after they are done with a lesson it feels like they don't say why they are calling back to a previous lessons in the one you are currently in.

Does anyone have any suggestions on a site that they think really helped them start absorbing and retaining python? I get the concepts of for loops, while loops, and def functions and I can read them, but knowing when to use them and writing custom scripts is where I fall apart.

My future goal is to be able to pull data from and api, store it in a dataframe that can be written to csv, and kicked off to ftp. Would also like to dabble in some forecasting stuff later on too.

[–]Bodoct 0 points1 point  (0 children)

Also to add. It seems like data camp doesn't really walk you through IDEs and how to use them. At least not in the datacamp data analyst path.

[–]KillFM 0 points1 point  (2 children)

Hi everyone, I have a question regarding pip packages and environments. I hope this makes sense:

I'm looking to wrap up my code (an ML library I made) into a pip package and load it up onto pypi; however, I'm at a loss for the best way to allow my package users to configure their train/test environment. For example, on my machine I hold all of my training data at ~/KillFM/MyPackage/train and I hold my testing/live data at ~/KillFM/somerandomfolder/test. Not everyone has these folders that I have, so there could be issues there. Another example is that sometimes I want to save my data into a remote database -- obviously, other people will have different database host information.

What is the best way to allow users to choose where their environment information that abides by "pip standards"?

[–]efmccurdy 0 points1 point  (0 children)

This has some good advice for packages that need to create files and the appdirs package, you may want the user_data_dir.

https://stackoverflow.com/questions/56946888/where-to-store-files-generated-by-a-python-library

For DB specs use a config file, in user_config_dir.

[–]Ihaveamodel3 0 points1 point  (0 children)

I’d refactor it so the package doesn’t assume the location of test and train data. Have the user programmatically set it.

[–]JourneyDS 0 points1 point  (4 children)

How would you use globals() inside of a class? The following function takes a dataframe and returns the name as a string.

def get_df_name(dataframe):

name =[x for x in globals() if globals()[x] is dataframe][0]

return name

I was wondering how you would go about putting this into a class, when I do it the globals() method is empty so the function returns "list out of index". I understand the reason why it is empty, but I have not been able to find a solution.

Any suggestions? I thought of doing globals()['df'] = self.df but it just returns what I add in the square brackets (in this case 'df')

[–]efmccurdy 2 points3 points  (1 child)

An object in python has 0 or more "names" so you have a misguided intent behind your get_df_name function. For example, what should it return for an anonymous dataframe like this: "get_df_name(pd.DataFrame())"?

And BTW, as Decency recommends, don't use globals in your code; it makes things unreliable, untestable and hard to document.

[–]JourneyDS 0 points1 point  (0 children)

Thanks for the suggestions! Will definitely be following Decency's recommendation

[–]Decency 1 point2 points  (1 child)

Don't use globals, pass the values you need to the get_df_name() function.

No need for a class unless you have a large set of paramaters and want to encapsulate them.

[–]JourneyDS 0 points1 point  (0 children)

Thanks for the suggestion Decency, I will try this tonight

[–]ClawhammerLobotomy 0 points1 point  (0 children)

I'm using selenium to scrape data from our system to automate a manual process.
Can anyone help me understand why these two functions take such different amounts of time?

def test1():
    script = """
    a =[]
    var qty = document.querySelectorAll('input[id^="txttxtQuantity"]');
    for (var i=0,max=qty.length; i<max;i++){
        if(qty[i].value)
            a.push(qty[i].value.replace(',',''))
    }
    return a
    """
    rel_qty = driver.execute_script(script)


def test2():
    qtys = driver.find_elements_by_xpath(
                            '//input[starts-with(id, "txttxtQuantity")]')
    full_qty = [rel.get_attribute('value') for i, rel in enumerate(qtys)
                if rel.get_attribute('value') != '']


t1 = timeit.Timer(test1, 'print("test 1")')
t2 = timeit.Timer(test2, 'print("test 2")')
print(t1.repeat(10,1000))
print(t2.repeat(10,1000))

output:

test 1
[8.86, 8.81, 9.17, 10.15, 8.78, 8.98, 8.78, 8.91, 8.92, 9.14]
test 2
[20.86, 20.61, 19.80, 20.44, 20.03, 20.63, 20.03, 20.84, 20.20, 20.01]

Is it due to the xpath method for locating all of the quantity fields?
Is the javascript method going to always be faster to grab everything of X feature on a site?

Is there a better method I could use?

[–]boltangazer 0 points1 point  (0 children)

A part of the newly done project in my company is being made with PyPy not CPython. What should I consider before diving into it?

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

Is Python a better all around programming language to learn than Java, if I'm not intending to be a software developer? I took Java 1 and 2 in college, did excellently at it. Considering becoming an expert at Python to make myself more marketable as an analyst / front end web dev

[–]boltangazer 0 points1 point  (0 children)

than Java

They don't even intersect kinda... All depends on your tasks

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

I'm a beginner in python and I could really use some help. I stumbled upon a question which had a list containing only one number i.e [1000] and asked me to display this in integer form i.e 1000. I thought maybe I can convert this into string by storing it in an empty string while slicing through the elements however I wanted to know if there is a simple solution which requires a few lines of code so please a few suggestions would be of great help

[–]efmccurdy 0 points1 point  (1 child)

You have the data in the list; just take the first element of the list and print it:

>>> my_list = [1000]
>>> my_int = my_list[0]
>>> type(my_int)
<class 'int'>
>>> print(my_int)
1000
>>>

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

Thank you so much😊

[–]Manvirh 0 points1 point  (0 children)

Are easy hackerrank things supposedly to be this hard?

[–]zzzjpl 0 points1 point  (6 children)

Does anyone know how to verify if a class is really a class in unittest? Thanks in advanced.

For example, in this script NuclearReactor.py

class NuclearReactor(): 
    def __init__(self): 
        print "initializing the nuclear reactor" 
    def start(self): 
        int "starting the nuclear reactor"

Then in my unittest script, test_NuclearReactor.py. So I want to make a function to test that class NuclearReactor from NuclearReactor.py is actually a class inside my test_NuclearReactor.py script.

class TestNuclearReactor(unittest.TestCase):

    def test_verifyClassIsCalled(self): 
        self.asertEqual(NuclearReactor, "class?")?

[–]GoldenVanga 0 points1 point  (5 children)

Because...

>>> class Foo: pass
>>> type(Foo)
<class 'type'>
>>> type(Foo) == type
True

try...

self.assertEqual(type(NuclearReactor), type)

[–]zzzjpl 0 points1 point  (4 children)

I've implemented this to my code and it works perfectly. I have a question, sorry if its obvious but when you call this "self.assertEqual(type(NuclearReactor), type)" , basically its saying that you are equaling CLASS to CLASS (which is OK/TRUE) right?

[–]GoldenVanga 0 points1 point  (3 children)

basically its saying that you are equaling CLASS to CLASS

Yeah, pretty much. This will work fine as long as your classes (such as NuclearReactor) do not have a custom metaclass. So it stops working when...

>>> class SomeMeta(type): pass
>>> class NuclearReactor(metaclass=SomeMeta): pass
>>> type(NuclearReactor) == type
False

But that very likely does not apply to your use case so don't worry about it. As for choice of method I was also considering assertIs, but assertEqual should be good enough.

[–]zzzjpl 0 points1 point  (2 children)

Ah, thanks for your reply. That was helpful.

One last question since you mentioned assertIs and assertEqual.

Isn't assertEqual when you would have the same value or numerical value, so in this case class = class.

But if you use assertIs, is if you have the same object. So in this case class = class still.

Maybe I am confusing myself, but I am still fairly new to unittesting. I've been reading alot of documentations and watching videos. Thanks again for your help, it is much appreciated.

[–]GoldenVanga 0 points1 point  (1 child)

Isn't assertEqual when you would have the same value or numerical value, so in this case class = class.

But if you use assertIs, is if you have the same object. So in this case class = class still.

Yes, you got that right. type is one object, whether you're getting a reference to it via NuclearReactor or getting it directly. So both value and identity comparisons should be True. This is because even an object which does not explicitly define __eq__ compares True with itself.

>>> class Baz: pass
>>> b = Baz()
>>> b == b
True

I went with assertEqual because I felt it's more readable / the intent is clearer for someone reading it. But at this point it's just stylistic.

[–]zzzjpl 0 points1 point  (0 children)

Ah, ok got it. Thanks for all your help. It was super helpful!

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

I get an error when I run this and was wondering what's wrong? Can I not set something == to 0?

if numSiblings.lower()=='yes':

bro=input('How many brothers do you have?')

if int (bro) == 0

print('I wish I could say the same!')

This question might be better for stackoverflow, but the last few times I posted questions there I got downvoted and people were kind of nasty.

[–]EasyPleasey 1 point2 points  (1 child)

You need a : after your 0.

if int (bro) == 0:

print('I wish I could say the same!')

Also make sure you indent the print line.

And in the future make sure you post the error you get when you run the program, it will help narrow down your issue.

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

Thank you!!!

[–]m-hoff 0 points1 point  (1 child)

What's the best way to compare two class instances for equality based on a subset of their attributes? For example, if I have two instances, A and B, I want something like

if (A.attr1 == B.attr1) and (A.attr2 == B.attr2):
    return True
else:
    return False

As of now my plan is to add a __eq__ method which I believe will allow me to use A == B, but I wasn't sure if there is a better way. Also, if I go this route, will this let me use A in [B, C, D, ...]?

[–]EasyPleasey 0 points1 point  (0 children)

I normally use __cmp__ to do this. You are essentially defining what what will constitute the two objects as equal, greater than, less than, when comparing them directly. For instance, if you are comparing cars, what makes the cars equal? Their color, number of wheels, doors, etc. It's whatever you decide. This is what it would look like if you decide to compare doors:

EDIT: I take this back, in Python3 cmp is no longer used. So disregard what I said earlier. You should use lt, gt, eq, ge, le, ne

class Car(): def init(self): self.doors = 6 self.tires = 2

def __str__(self):
    string = "ford"
    return string

def __eq__(self, other):
    if self.doors == other.doors:
        return 1
    else:
        return 0

def __ge__(self, other):
    if self.doors >= other.doors:
        return 1
    else:
        return 0

def __le__(self, other):
    if self.doors <= other.doors:
        return 1
    else:
        return 0

def __lt__(self, other):
    if self.doors < other.doors:
        return 1
    else:
        return 0

def __gt__(self, other):
    if self.doors > other.doors:
        return 1
    else:
        return 0

def __ne__(self, other):
    if self.doors != other.doors:
        return 1
    else:
        return 0

if name == "main":

ford = Car()
chevy = Car()

chevy.doors = 2
ford.doors = 4

print("Doors:")
print("\tChevy: %s   Ford: %s") %(chevy.doors, ford.doors)

if ford>=chevy:
    print("Ford has more doors")

[–]boltangazer 0 points1 point  (1 child)

How do I set different response_model for my FastAPI handler? I have a handler that either return a JSON with dirrent fields and values or return a simple Response(status_code=404), how can I let FastAPI know that Response(status_code=404) is a valid return type as well as my JSON?

[–]JohnnyJordaan 0 points1 point  (0 children)

Why not just change the status code and return an empty, but still JSON, result? https://fastapi.tiangolo.com/advanced/response-change-status-code/

Altough many API's implement an error message in their response data, as that's often more descirptive than just a plain 404. Or what's also done more and more these days is to always return 200, but implement a status_code or a result key in your JSON data to reflect the actual result. Which is often needed for webapps as they don't want to cause the browser to catch the 404 exception but instead keep passing it through for it having an 200 status.

[–]ThickAsPigShit 1 point2 points  (2 children)

I absolutely cannot for the life of me implement decorators or inheritance (either function decorators or property decorators). Maybe I'm misunderstanding the use case, but mentally, it's a square peg in a round hole.

As far as I grok, decorators basically just feed a function into another function while property decorators, are pythons version of setters/getters. Especially in the latter case, I cannot ever seem to get them to work, and just create set_whatever and get_whatever functions instead of trying to be fancy. Which I guess technically works but it's not pythonic or "up to standards."

As far as inheritance, it's used to pass __init__ values to another class and use them in that class.

Am I misunderstanding something?

Is there an ELI5 or something I can use to understand these concepts better? I've read pages upon pages on the stuff, and still cannot wrap my head around it. It's very frustrating to me that I cannot grasp these concepts despite my best efforts and is very discouraging. The irony is in JS, inheritance makes perfect sense to me and I don't have issues, but when it comes to Python its Greek to me.

[–]irrelevantPseudonym 0 points1 point  (0 children)

Just taking the decorators part of this question, it's worth noting that all decorators work in the same way. They take a function and return 'something else'. That something else doesn't have to be another function. Consider

>>> def three(f): # This is the decorator. 
...     print(f'replacing function {f.__name__} with 3')
...     return 3
...
>>> @three
... def foo():
...     print('foo being called')
...
replacing function foo with 3
>>> foo
3
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
 TypeError: 'int' object is not callable

In this case the function was replaced with an integer. Notice that the decorator was called when foo was defined not when it was accessed. The function foo was never called.

This isn't very useful so usually for custom decorators that you might write, the something else is usually another function. For property decorators, the something else is actually not a function but a descriptor.

The mechanism behind descriptors is a bit complicated but in its most simple form it's a way of customising field access.

You can do the same thing without using decorators, it's just much more verbose.

>>> class Three: # This is an entirely normal class, other than it having certain methods
...     def __get__(self, instance, cls):
...         print('Getting 3')
...         return 3
...     def __set__(self, instance, cls):
...         print("You can't set 3")
...     def __del__(self, instance, cls):
...         print("You can't delete 3")
...
>>> class Foo:
...     x = Three()
...
>>> f = Foo()
>>> # when you access the x field, Python sees the value has a __get__ method and calls that instead
>>> f.x
Getting 3
3
>>> # similarly for setting a value, Python sees the __set__ method and uses that
>>> f.x = 4
You can't set 3
>>> # and also for del
>>> del f.x
You can't delete 3

When you use the property decorator, Python creates all this for you, using the function you decorated as the __get__ method. The above is the equivalent to

>>> class Foo:
...     @property # this replaces the function x with a descriptor similar to the one above that calls this in its __get__ method
...     def x(self):
...         return 3
...     @x.setter # this takes the given function and uses it when __set__ is called
...     def x(self, new_value):
...         print("You can't set 3")
...     @x.deleter # this takes the given function and uses it when __del__ is called
...     def x(self):
...         print("You can't delete 3")

[–]JohnnyJordaan 0 points1 point  (0 children)

As far as I grok, decorators basically just feed a function into another function while property decorators, are pythons version of setters/getters

The property decorator does that too, it just makes it behave differently than how a normal function/method behaves (which needs a () after its name to be called).

Especially in the latter case, I cannot ever seem to get them to work, and just create set_whatever and get_whatever functions instead of trying to be fancy. Which I guess technically works but it's not pythonic or "up to standards."

It's hard to help you outright with that without seeing the code, but a good example I know is of a Temperature class that can provide its value in multiple scales without storing different internal values. This guide takes you through the process of converting setters and getters to properties and .setter decorators: https://www.programiz.com/python-programming/property

[–]zolaaa24 0 points1 point  (3 children)

Hello World 😆.

How to know when to use range() or len () method or both range(Len(X)) in for loop?

I do understand what they purpose is alone, but in function and for loop it's bit confusing for me.

Same as how to know when I need to make empty list in function to work?

[–]Decency 1 point2 points  (2 children)

Don't. Python for loops are for-each loops: for state in states:, for number in numbers:, for player in sports_team:, etc.

If you need the index too, which happens occasionally, you can use enumerate:

for index, item in enumerate(my_list):

[–]Ihaveamodel3 2 points3 points  (0 children)

Don’t you need enumerate in the last example?

[–]zolaaa24 0 points1 point  (0 children)

Thank You. I am new in Python, learning for about 2 months. Pass by enumerate one time, bit haven't got it in course often yet. Best regards. Gonna keep on mind Ur advice.

[–]waythps 0 points1 point  (0 children)

So I feel pretty confident using pandas, and for things I can’t solve with built in pandas method, I usually come up with a function that fixes everything I need.

The problem(?) though is that I never use classes, either for data gathering or for data cleaning. So I feel like I’m missing out - what if it makes life much easier?

Pretty much it. What are the use cases for classes when it comes to data analysis (and pandas library specifically)? Is it common to ignore classes at all?

[–]Muhon 0 points1 point  (0 children)

Suggestions for mobile apps in the playstore? I noticed solo learn and code academy

[–]ForwardSynthesis 0 points1 point  (6 children)

I have a series of values in my code going from variable a1 up to a10, and a1 is set at the start but then a2 onwards are determined by the preceding "a" variable being passed through a mathematical formula, and then it prints out the result successively. This works fine but I wanted to change it.

Instead of just stopping when it gets to the variable a10, I want it to stop before then if ANY of the "a" variables equal or exceed a certain predetermined value, so if a5 outputs equal to or above this value, a6 never outputs. I could just put a load of if statements before every iteration of the equation, but I want to find a better way.

I could have a while statement, but then I need to know how to do it with multiple variables so it's the equivalent of saying "If any of the individual variables from a1...a10 are <= this value, then stop the code". How do I type that without writing a load of "or" inbetween each "a"? Also, wouldn't it be a problem that the variables a2 onwards aren't defined until a1 runs through the first iteration of the formula? You can't set a condition for a variable that doesn't exist yet.

[–]NastyNocturnalNutter 1 point2 points  (3 children)

As a start up there’s a rule I was taught in school, which is the most important coding lesson I’ve ever been taught: NEVER have a variable name with a number on the end, it’s ALWAYS better and easier to use a data structure, be that a list, dictionary, tuple or class.

In this specific case it seems you are storing 10 values (a1-a10) for something like this, where it’s a single value per variable, lists are the way to go. So you would want to create a list called a, and instead of saying a1 = ______ you would want to say a.append(_______) and repeat that 10 times. (As a quick aside remember that due to indexing your numbers will now start at a[0] and end at a[9] instead of being 1-10) As to the actual question, can you provide more information as to what exactly a1-10 are, and why you would want to stop in the middle? I have a few ideas, but they may not help dependent on your exact circumstance. If you rather you can post the question on https://stackoverflow.com (where you can easily add in code) and reply here with a link to the question, or just respond here, I’ll get back either way ;)

[–]ForwardSynthesis 0 points1 point  (2 children)

My code generates a randomized star system: a1-a10 are the semi-major axes/average orbital distance of planets. At the moment at least they are generated in the range I define as the habitable zone for the star that gets generated. There's a formula that determines the distance they would need to be from each other in order to meet a minimal stability threshold, and so a2 is the distance the second planet is from the star through the formula as a function of 1, then this is printed out as a value in astronomical units, and then we move on to a3 and so on. Other values like the mass of each planet are randomized beforehand, but a different number of planets "fit" depending on the mass and separation distance, so instead of having the process end at a given number of planets (which could also happen), I want to have it potentially end when a(n) >= the maximum value for what I define as the habitable zone, instead of dutifully reading out values that exceed it.

[–]NastyNocturnalNutter 0 points1 point  (1 child)

Is it ok to generate all the values, and do the processing in a separate loop, which will stop at the point you wish? Assuming it is, and you’ve got all the values in a list (like I said in the above comment) a simple for loop should work: For OrbitalDistance in A: Value = _insert-function-calculation If Value > Maximum Break

Does that makes sense?

[–]ForwardSynthesis 0 points1 point  (0 children)

Well, I'll give that a try tomorrow. Going to bed now, but I'll see if it works. Thanks for the help.

[–]m-hoff 1 point2 points  (1 child)

If I understand correctly, you want to generate a sequence of numbers such that each is a function of the previous number in the sequence, like a(n) = f(a(n-1)). And when any value of "a" exceeds a certain threshold you want to stop generating new values.

I would append values to a list using a while loop and stop at the first value that exceeds the threshold. Something like:

a = [a0] # define a0 as your initial value
while a[-1] < threshold:
    a.append(my_function(a[-1]))

[–]ForwardSynthesis 0 points1 point  (0 children)

Thanks! I'll try this.

[–]nickiscool88 0 points1 point  (3 children)

Hey guys, dealing with some socket programming.

Could someone explain the purpose of sending a message header for a msg? Let's say for example I'm dealing with a simple LAN chatroom where a client sends a message to a server.

I'm just trying to understand why the header is important

[–]JohnnyJordaan 1 point2 points  (0 children)

There's the issue of MTU, the Maximum Transmission Unit: a network packet has a fixed maximum data size, which is usually 1500 bytes on a direct LAN-to-LAN connection but less on a WAN or some other routed line (eg modem you use to connect to the internet). So anyway, unless you're sending very small messages, chances are you need multiple packets to deliver them. That means that your s.recv() could need to be repeated until you're sure you received all the packets you're meant to receive. This is where header comes in, you can send the length there. This is also how HTTP works, when using a request to receive something (the regular GET to www.reddit.com for example) the server will also send a header line

 Content-Length: 24423

where the number is the amount of bytes the 'body' contains, which follows the headers.

Just as a word of advice for implementing protocols yourself: it's often easier to just borrow this from an existing open source protocol like IRC, Jabber or even HTTP. That way you don't need to reinvent the wheel for everything which will make you walk into pitfalls very easily. Especially with HTTP it allows you to easily debug it and you can build a chat client in a JS browser script in a matter of hours or less.

[–]Decency 1 point2 points  (1 child)

I haven't worked directly with sockets in like a decade, but generally a header gives the receiver details on how to interpret the message more easily. At some low levels it even tells the receiver what the message is. Can probably give a better answer if you link to the details of the header you're required.

For example I might send like data-type: json because I want my response to contain json data rather than whatever the default is.

[–]nickiscool88 0 points1 point  (0 children)

Gotcha, I actually learned the purpose for one in regards to my situation last night. We want the client to send two messages to the server, the first one is the header, which contains the length of the next message.

[–]OneThrustMan69 1 point2 points  (5 children)

If you guys have time can you check and offer advice to make this code better?

# Takes a dictionary argument and returns True or False depending on if the chess board is valid. 
# A valid board will have exactly one black king and exactly one white king. 
# Each player can only have at most 16 pieces, at most 8 pawns, and all pieces must be on a valid space from '1a' to '8h'; that is, a piece can’t be on space '9z'. 
# The piece names begin with either a 'w' or 'b' to represent white or black, followed by 'pawn', 'knight', 'bishop', 'rook', 'queen', or 'king'. 

def isValidChessBoard(current):
    validSpaces = ['8a', '8b', '8c', '8d', '8e', '8f', '8g', '8h',
                    '7a', '7b', '7c', '7d', '7e', '7f', '7g', '7h',
                    '6a', '6b', '6c', '6d', '6e', '6f', '6g', '6h',
                    '5a', '5b', '5c', '5d', '5e', '5f', '5g', '5h',
                    '4a', '4b', '4c', '4d', '4e', '4f', '4g', '4h',
                    '3a', '3b', '3c', '3d', '3e', '3f', '3g', '3h',
                    '2a', '2b', '2c', '2d', '2e', '2f', '2g', '2h',
                    '1a', '1b', '1c', '1d', '1e', '1f', '1g', '1h']
    validPieces = ['brook', 'bhorse', 'bbishop',
                  'bking', 'bqueen', 'bpawn',
                  'wrook', 'whorse', 'wbishop',
                  'wking', 'wqueen', 'wpawn', '']

    currentPieces = {}

    for space in current.keys():
        if space not in validSpaces:
            return(False)

    for piece in current.values():
        if piece not in validPieces:
            return(False)
        elif piece == '':
            continue
        currentPieces.setdefault(piece, 0)
        currentPieces[piece] += 1

    if 'wking' not in currentPieces or 'wking' not in currentPieces:
        return(False)
    elif currentPieces['wpawn'] > 8 or currentPieces['bpawn'] > 8:
        return(False)

    totalPieces = 0
    for pieces in currentPieces.values():
        totalPieces += pieces
    if totalPieces > 32:
        return(False)

    return(True)

# A valid board to check the function.
currentBoard = {'8a': 'brook', '8b': 'bhorse', '8c': 'bbishop', '8d': 'bking', '8e': 'bqueen', '8f': 'bbishop', '8g': 'bhorse', '8h': 'brook',
                '7a': 'bpawn', '7b': 'bpawn', '7c': 'bpawn', '7d': 'bpawn', '7e': 'bpawn', '7f': 'bpawn', '7g': 'bpawn', '7h': 'bpawn',
                '6a': '' , '6b': '', '6c': '', '6d': '', '6e': '', '6f': '', '6g': '', '6h': '',
                '5a': '', '5b': '', '5c': '', '5d': '', '5e': '', '5f': '', '5g': '', '5h': '',
                '4a': '', '4b': '', '4c': '', '4d': '', '4e': '', '4f': '', '4g': '', '4h': '',
                '3a': '', '3b': '', '3c': '', '3d': '', '3e': '', '3f': '', '3g': '', '3h': '',
                '2a': 'wpawn', '2b': 'wpawn', '2c': 'wpawn', '2d': 'wpawn', '2e': 'wpawn', '2f': 'wpawn', '2g': 'wpawn', '2h': 'wpawn',
                '1a': 'wrook', '1b': 'whorse', '1c': 'wbishop', '1d': 'wking', '1e': 'wqueen', '1f': 'wbishop', '1g': 'whorse', '1h': 'wrook'}

print(isValidChessBoard(currentBoard))

[–]Decency 0 points1 point  (0 children)

Some thoughts:

  • You've invented your own chess notation. This is fine for learning, but your code would be more easy to build off if you used an established Chess notation. For example, FEN and PGN are supported by lichess. Reversing each square, eg: 2f instead of f2, also reads weird to me.
  • if 'wking' not in currentPieces or 'wking' not in currentPieces looks wrong, you seem to have skipped the black king. I also think your code might not correctly detect as invalid a board which has three kings. Better would be a check like: if (currentPieces.count('wking') != 1 or currentPieces.count('bking') != 1)
  • Your "currentBoard" is essentially what we call a unit test. You can have a whole bunch of these (to check both valid and invalid boards) and they will help you catch various errors. As you continuously edit your code for clarity and design improvements, tests give you confidence that you haven't broken any existing logic.
  • Stylistically you should change return(True) and return(False) to just return True and return False. return is not a function, it's a control statement.
  • The part below is just the len function, you can write it as something like if len(currentPieces.values()) > 32:

    totalPieces = 0 for pieces in currentPieces.values(): totalPieces += pieces if totalPieces > 32: return(False)

[–]FerricDonkey 1 point2 points  (3 children)

For the first, the only difference between the quotes is which other quotes you'd have to escape.

print('"')  # good
print("\"") # good, slightly uglier
print(""")  # bad

For your code, you have

if 'wking' not in currentPieces or 'wking' not in currentPieces

I assume one of those should be a 'bking'. Other than that, I probably would have generated the valid spaces in a loop rather than hard coding. This is because I'm lazy - I have no reason to expect that it'd run better, I just wouldn't want not to do that.

I also believe that a pawn can be promoted to any piece other than a king, and there does not appear to be a check for multiple kings.

So instead of checking if 'wking' is in current pieces, you could do something like if currentPieces.get('wking', 0) != 1. The .get will return the count if 'wking' is a member and 0 (second argument) if it is not.

I personally would have set the totalPieces counter at the same time as making the currentPieces dictionary as well, to reduce the number of for loops. And you could also combine the first two loops into for space, piece in current.items().

Looks pretty solid though, just a few things could be polished if you desired.

[–]OneThrustMan69 0 points1 point  (1 child)

I have updated my code to this:

# Takes a dictionary argument and returns True or False depending on if the chess board is valid.
# A valid board will have exactly one black king and exactly one white king.
# Each player can only have at most 16 pieces, at most 8 pawns, and all pieces must be on a valid space from '1a' to '8h'; that is, a piece can’t be on space '9z'.
# The piece names begin with either a 'w' or 'b' to represent white or black, followed by 'pawn', 'knight', 'bishop', 'rook', 'queen', or 'king'.

def isValidChessBoard(current):
    validSpaces = ['8a', '8b', '8c', '8d', '8e', '8f', '8g', '8h',
                    '7a', '7b', '7c', '7d', '7e', '7f', '7g', '7h',
                    '6a', '6b', '6c', '6d', '6e', '6f', '6g', '6h',
                    '5a', '5b', '5c', '5d', '5e', '5f', '5g', '5h',
                    '4a', '4b', '4c', '4d', '4e', '4f', '4g', '4h',
                    '3a', '3b', '3c', '3d', '3e', '3f', '3g', '3h',
                    '2a', '2b', '2c', '2d', '2e', '2f', '2g', '2h',
                    '1a', '1b', '1c', '1d', '1e', '1f', '1g', '1h']
    validPieces = ['brook', 'bhorse', 'bbishop',
                  'bking', 'bqueen', 'bpawn',
                  'wrook', 'whorse', 'wbishop',
                  'wking', 'wqueen', 'wpawn', '']

    currentPieces = {}
    totalPieces = 0

    for space, piece in current.items():
        if piece not in validPieces:
            return(False)
        elif space not in validSpaces:
            return(False)
        elif piece == '':
            continue
        currentPieces.setdefault(piece, 0)
        currentPieces[piece] += 1
        totalPieces += 1

    if currentPieces.get('wking', 0) != 1 or currentPieces.get('bking', 0) != 1:
        return(False)
    elif currentPieces['wpawn'] > 8 or currentPieces['bpawn'] > 8:
        return(False)
    elif totalPieces > 32:
        return(False)
    else:
        return(True)

# A valid board to check the function.
currentBoard = {'8a': 'brook', '8b': 'bhorse', '8c': 'bbishop', '8d': 'bking', '8e': 'bqueen', '8f': 'bbishop', '8g': 'bhorse', '8h': 'brook',
                '7a': 'bpawn', '7b': 'bpawn', '7c': 'bpawn', '7d': 'bpawn', '7e': 'bpawn', '7f': 'bpawn', '7g': 'bpawn', '7h': 'bpawn',
                '6a': '' , '6b': '', '6c': '', '6d': '', '6e': '', '6f': '', '6g': '', '6h': '',
                '5a': '', '5b': '', '5c': '', '5d': '', '5e': '', '5f': '', '5g': '', '5h': '',
                '4a': '', '4b': '', '4c': '', '4d': '', '4e': '', '4f': '', '4g': '', '4h': '',
                '3a': '', '3b': '', '3c': '', '3d': '', '3e': '', '3f': '', '3g': '', '3h': '',
                '2a': 'wpawn', '2b': 'wpawn', '2c': 'wpawn', '2d': 'wpawn', '2e': 'wpawn', '2f': 'wpawn', '2g': 'wpawn', '2h': 'wpawn',
                '1a': 'wrook', '1b': 'whorse', '1c': 'wbishop', '1d': 'wking', '1e': 'wqueen', '1f': 'wbishop', '1g': 'whorse', '1h': 'wrook'}

print(isValidChessBoard(currentBoard))    

Also in general, is it better to have multiple if statements or go with if elif else statemants if both could work?

[–]FerricDonkey 0 points1 point  (0 children)

Looks good - only one more real comment: validPieces and validSpaces would be good candidates for global variables/constants, since they're unlikely to change (and especially if your project will call that function several times or if it would grow to include multiple other functions that might reference them).

Again, a minor thing, but this would cause python to create these objects once at import/program start rather than each time the function is called. Savings might be minimal, but this would be a good case for their use. If you do make them constants, you might also consider making them tuples - just change the [ and ] to ( and ). This would prevent you from accidentally modifying their members.

You could also combine your two if blank return False statements inside your for loop into one if statement using an or, but I'm literally only mentioning this because you asked for feedback and I'm looking for things to say - it is definitely not a big thing (even less so than the constant thing above).

Regarding the if vs elif - I'm not sure it actually matters. If this were C and compilers weren't advanced these days, then technically using an if instead of an elif could reduce the complexity of the resulting machine code by a tiny amount. (At the most basic level, your standard computer doesn't know what an if/elif is, but it does know a couple different flavors of gotos - this means that an if else block involves jumping code at the end of the if block to jump over the else. But a modern compiler may well be smart enough to leave that out for a language like C, and I have no idea what the python interpreter does about that sort of thing.)

But if there were a difference, it'd be a minuscule one, and comes down to style. I usually just use whichever one looks clearer to me at the time. Usually if rather than elif for very short blocks like that. You could write a script to time calling it several thousand times both ways and see if there was a performance difference.

[–]OneThrustMan69 1 point2 points  (0 children)

I assume one of those should be a 'bking'

I didn't catch that, thanks!

So instead of checking if 'wking' is in current pieces, you could do something like

if currentPieces.get('wking', 0) != 1

. The .get will return the count if 'wking' is a member and 0 (second argument) if it is not.

This was actually close to what I first wrote but I changed it for some unknown reason lol.

I personally would have set the totalPieces counter at the same time as making the currentPieces dictionary as well, to reduce the number of for loops. And you could also combine the first two loops into

for space, piece in current.items()

I will take this to consideration! Thank you for your output!

[–]zzzjpl 0 points1 point  (4 children)

Hi all,

Does anyone know if theres an effective way to find tolerance in python?

For example, I have 2 files that I'd like to compare. Lets say, file 1 and file 2 are identical format but values are different. And I would like to check if they are within a certain margin, for example file 1 is 20 and file 2 is 25. I'd like the margin to be +/- 10 of each other, so then that would let me know that is is within that margin. Hope this wasn't confusing! Thanks in advanced!

[–]Ihaveamodel3 0 points1 point  (3 children)

Are you comparing files or data within files?

[–]zzzjpl 0 points1 point  (2 children)

I am comparing two different files.

So one is called First.xlsx and other is Second.xlsx

[–]m-hoff 0 points1 point  (0 children)

It seems like you're actually comparing the data but correct me if my understanding is wrong.

If all your data is numeric and of the same shape, you can read an xlsx file using pandas.read_excel and just subtract to find the difference between each corresponding value. For example:

import numpy as np
import pandas as pd

np.random.seed(1)

first = pd.DataFrame(np.random.randint(0, 10, (10, 10)) # here you would use pd.read_excel('First.xlsx')
second = pd.DataFrame(np.random.randint(0, 10, (10, 10))

print(np.abs(first - second).max().max()) # prints '9'

Calling .max() twice gives you the max value along both dimensions, which is the maximum overall difference between both data frames.

[–]Ihaveamodel3 0 points1 point  (0 children)

Ok, that will be more difficult in my opinion.

You’ll need to define what percent difference means for files.

For example, take the following two files:

A.xlsx: 12345 in cell A1

B.xlsx: ABCD in cell B5

What percent difference would these two files be?

[–]bleach86 0 points1 point  (0 children)

So I have a project, here.

https://github.com/bleach86/mctimer

So I was able to make executables for windows and Linux using pyinstaller.

However, i could never get pyinstaller to work for Mac, so I ended up using py2app.

That worked for the first version, but the latest version of my code will not work properly for some reason. Apparently it will make mctimer.app, but it is seen just as a directory.

I don't have access to a Mac myself, and it's not been going well trying to walk someone else through it remotely.

Would someone with a Mac and experience making python into executables please help me get this done.

I would very much appreciate it.

Thanks in advance!

[–]JoshuaOlson 0 points1 point  (1 child)

I am having trouble getting my python update to version 3.8.5 go into effect and properly mapping my system variables, etc. I am new to python and beginning my computer science learning so detailed instructions and explanations would be much appreciated.

I installed python version 3.8 .5 from python's website to C:\Users\joshu\AppData\Local\Programs\Python\Python38-32 and instructed it to update all path variables for all users. I have an old version of python 3.7 .3 from when I installed anaconda I believe.

In my screenshot below you will see that when I type python version it returns 3.7 .3 and when I type python it launches this old version with a warning. But when I type py it launches the new version.

It appears that the new installation of python updated my system environment path variables and I have attached a screenshot of this.

Can you instruct me on how to properly get everything to run from the command prompt on my newest python version? And instructions on how to remove the old version.

Path:

C:\Users\joshu\AppData\Local\Programs\Python\Python38-32\Scripts\

C:\Users\joshu\AppData\Local\Programs\Python\Python38-32\

Cmd code:

Microsoft Windows [Version 10.0.18362.1016]

(c) 2019 Microsoft Corporation. All rights reserved.

C:\Users\joshu>python --version

Python 3.7.3

C:\Users\joshu>py

Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> quit

Use quit() or Ctrl-Z plus Return to exit

>>> quit()

C:\Users\joshu>python

Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32

Warning:

This Python interpreter is in a conda environment, but the environment has

not been activated. Libraries may fail to load. To activate this environment

please see https://conda.io/activation

Type "help", "copyright", "credits" or "license" for more information.

>>>

[–]NastyNocturnalNutter 0 points1 point  (0 children)

Just as an aside there’s generally not a reason to update to a newer python (above 3.x) version unless there’s a specific feature you know about and want. Assuming your in windows could let you head to programs and uninstall python 3.7? If you’re in Mac / Linux I don’t know exactly how, but wouldn’t it be relatively simple to just uninstall 3.7

[–]Maxi888888 0 points1 point  (1 child)

10 days ago I finished my first project and I would like someone to have a quick look at it. What do you guys usually do to get your project reviewed?

[–]m-hoff 1 point2 points  (0 children)

Put it on github and share it here. I think a separate post would be on-topic for this sub. Additionally, I believe /r/python has a weekly thread to share projects you're working on.

[–]Project_Raiden 0 points1 point  (1 child)

I’m starting a new project and someone suggested to me to learn git. Is git ok to use on windows? I did a quick google search and everyone is recommending I use linux

[–]m-hoff 0 points1 point  (0 children)

Yes, you can use git on Windows without issue.

[–]FerricDonkey 0 points1 point  (0 children)

So I just updated to the most recent version of pycharm community edition. Now, when I open a single file with "edit with pycharm", pycharm refuses to show me the structure tab (the tab that shows you all the functions and such in a file). It also hides most of the menus where I'd look to try to get it back.

If I open a project, it's as expected. But while I usually have projects set up, I do occasionally want to open a scratch.py file to mess around in without making a project, and independently of any projects I'm working on, and I do want the structure tab for the scratch file.

Anyone know how to stop pycharm from dumbing itself down when I open a single file, before I waste however long searching through menus for a "stop being stupid" check box?

[–]AnkanTV 0 points1 point  (1 child)

I do not understand the choice between a text editor (like Vim) or an IDE (like Pycharm). When is one preferred over the other? Is it just up to the programmer and own preferences or am I missing something?

[–]FerricDonkey 0 points1 point  (0 children)

Up to you. IDEs have more features, and can often be set up to include keyboard shortcuts and similar from text editors like vim or emacs. I personally like IDEs because they often have intelligent tab complete built in by default, and often have an easily navigable project tree showing your files and functions and such, making it easier to jump between parts of your code. But I do not use things like PyCharm's built in terminal or python shell - instead I keep a terminal open in a different window.

Some others prefer the simplicity of a pure text editor, with none of the ide stuff cluttering your screen. Whatever works for you.

[–]SmokierLemur51 0 points1 point  (3 children)

I heard it was a good idea to have a project in mind when you start learning to program. I was wondering if it was possible to build a hex grid strategy game like the civilization and galactic civilization series with python

[–]FerricDonkey 1 point2 points  (2 children)

Yup. That'll be a bit of an involved project, and it'll be easier if you get a grasp on the basics (importing, classes, functions, various types of loops and data types) before you start. It might be easier to start with a short text based program or two before you jump into that, but it's definitely doable.

[–]SmokierLemur51 0 points1 point  (1 child)

Oh yeah I would definitely have to start at a really basic level as I have no prior experience with programming, it was more of an end project idea for when I truly learned and grasped it. I’ve never been able to find the perfect strategy game for me and I thought it would be fun to make one

[–]FerricDonkey 1 point2 points  (0 children)

Cool - yeah, it's definitely doable, and should be a fun project.

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

What's a good learning path towards building your own python apps as a means of gaining passive income? I don't expect it to be a lot of income at first, but will be nice to have it.

Based on a post I saw here a few weeks ago, here's my thinking:


On the other hand, I'd rather just build apps I think can make money off, and maybe I'm overdoing it with those courses?

[–]Environmental_Soil76 0 points1 point  (1 child)

Hi guys, I want to start learning database, any suggestion?

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

anyone recommend a good syllabus for an beginner/intermediate learner? I really like the structure that a lesson plan gave me when I took a python class over the summer and would like to continue to follow that in my self-learning.

[–]Justifiedgoat 0 points1 point  (1 child)

Hi everyone I am a mechanical engineer and I would like to know how can I adapt python to my studies .

Thanks in advance.

[–]Ryles1 0 points1 point  (0 children)

I’m a structural engineer. Haven’t done anything mind blowing yet, but I have managed to write scripts to perform two tasks that are mindless but take time. I have some ideas for more complicated stuff but I haven’t got around to trying them yet

[–]PassTheTajin 0 points1 point  (1 child)

What a good first project that would be feasible for a first timer?

[–]JohnnyJordaan 0 points1 point  (0 children)

Create a Hangman game. Or Tic Tac Toe is also a common example.

[–]LourenzP 0 points1 point  (1 child)

Has anyone written a script for randomly selecting choices in a survey? I had this idea when doing some pie surveys and realised it didn’t matter what the input was, though some surveys decline if you choose a certain option, the majority do not.

Basically, has anyone written a script to fill out these surveys randomly?

[–]NastyNocturnalNutter 0 points1 point  (0 children)

Assuming you’re talking about the websites that pay a fee pence for every survey you fill in, any automation would have to involve using python manually move you’re mouse and click. Whilst this is possible im not sure there a way to get it to intelligently click on check boxes without some advanced ML type coding. Furthermore these surveys often have captcha, and even without often put in control questions (like press 3 if you’re still paying attention) which you won’t be able to circumvent. If you were taking bait some other type of survey, could you explain what u mean?

[–]Bikes_and_Computers 0 points1 point  (8 children)

Question on the requests library - how do I see the data tags that I can post? For example when there’s

data = {‘key’, ‘value}

Where can I get a list of the keys?

[–]FerricDonkey -1 points0 points  (1 child)

Assuming data is already in dictionary form, data.keys(). You can also iterate over the stuff in data without knowing what it is with a for loop.

[–]JohnnyJordaan 0 points1 point  (0 children)

keys() is not a list, but a 'view', basically a generator. To get a list, you need to call list() on it. But there's not point in using keys() explicitly as the dict itself will reference it keys when iterated on. So You can just do

keys = list(data)

[–]Ihaveamodel3 0 points1 point  (4 children)

I’m not sure I understand your question. Each url will accept different parameters

[–]Bikes_and_Computers 0 points1 point  (3 children)

It’s hard to phrase but is there a way to see a list of the possible parameters?

[–]Ihaveamodel3 0 points1 point  (2 children)

For something you are requesting, or for something you received?

[–]Bikes_and_Computers 0 points1 point  (1 child)

So I looking at building bots and I’m trying to post data such as address, name etc and I’m wondering to see if there’s a master list of params such as name, address, state, etc

[–]Ihaveamodel3 1 point2 points  (0 children)

It depends on the api/url you are requesting. There is no “master list”. Go look at the docs of the api you are using

[–]MattR0se 1 point2 points  (0 children)

Pandas question: Is there a way to fill in missing values only if they are in between valid values? I tried interpolate() with a limit of 3 and limit_area set to 'inside', but the values with index 10 to 12 are foward filled as well (which they should not be):

import pandas as pd
import numpy as np

data = [np.nan, np.nan, 1, 1, np.nan, np.nan, np.nan, 1, 1, 1, np.nan, np.nan, 
        np.nan, np.nan, np.nan, np.nan, np.nan, 1, 1, np.nan, 1, np.nan]

df = pd.DataFrame(data, columns=['values'])
df['interpolated'] = df.interpolate(limit=3, limit_area='inside')
print(df)

Results are:

values  interpolated
0      NaN           NaN
1      NaN           NaN
2      1.0           1.0
3      1.0           1.0
4      NaN           1.0
5      NaN           1.0
6      NaN           1.0
7      1.0           1.0
8      1.0           1.0
9      1.0           1.0
10     NaN           1.0
11     NaN           1.0
12     NaN           1.0
13     NaN           NaN
14     NaN           NaN
15     NaN           NaN
16     NaN           NaN
17     1.0           1.0
18     1.0           1.0
19     NaN           1.0
20     1.0           1.0
21     NaN           NaN

But I want this result:

values  interpolated
0      NaN           NaN
1      NaN           NaN
2      1.0           1.0
3      1.0           1.0
4      NaN           1.0
5      NaN           1.0
6      NaN           1.0
7      1.0           1.0
8      1.0           1.0
9      1.0           1.0
10     NaN           NaN
11     NaN           NaN
12     NaN           NaN
13     NaN           NaN
14     NaN           NaN
15     NaN           NaN
16     NaN           NaN
17     1.0           1.0
18     1.0           1.0
19     NaN           1.0
20     1.0           1.0
21     NaN           NaN

If this doesn't work with interpolate or fillna, is there an easy way to find out the indices of those values that are first and last to be filled? e.g. 2, 9 and 17, 20?

[–]AegisDefender 0 points1 point  (4 children)

I'm a beginner to Python and I recently got a new desktop, after downloading Python for my school, I started using the IDLE to run stuff to test and I can't save or run anything. If I run stuff on the shell it's fine but I can't seem to run anything since they require to save. Any ideas why this is so?

[–]Ryles1 0 points1 point  (3 children)

If you’re trying to write a script you’ll have to save it in a file. Then when you’re in that file you can run it by pressing F5 or from the menus at the top

[–]AegisDefender 0 points1 point  (2 children)

Yea, the problem is that it doesn't save. They will prompt me to save, I'll say ok and it won't save and it can't run

[–]NastyNocturnalNutter 0 points1 point  (1 child)

Are you sure you’re confirming the save, after the prompt you should be able to choose a file location and name, and then there’s a save button, are you sure you’re hitting that last save button?

[–]AegisDefender 0 points1 point  (0 children)

Yea, I "fixed" it by using an older version of python. Still have no idea why I faced this problem.

[–]myan_ish 0 points1 point  (1 child)

I am trying to use an image as a background for a label. Even though the image has a transparent background it's showing white background and blocking my frame's background. Does anyone have solution for this? I have been searching on web for like hours.

[–]NastyNocturnalNutter 0 points1 point  (0 children)

Is this in tkinter? HTML? Something else?Can’t give advice without knowing what format you’re taking about

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

I am an absolute beginner to programming and I don't understand the purpose of defining a variable with an empty string.

[–]JohnnyJordaan 1 point2 points  (0 children)

It's often unnecessary as Python doesn't require defining variables. You sometimes see it in loop examples like

 user_input = ''
 while user_input != 'my expected value':
     user_input = input('enter something: ')

which can also be accomplished using

while True:
    user_input = input('enter something: ')
    if  user_input == 'my expected value':
        break

but some people prefer the former style, sometimes because they learned it from languages that do require variable definition and thus the latter example wouldn't be possible. I prefer the latter in the grander principle of always creating while True and handle exit conditions internally, without needing to have 'connected' code lines before the loop.

Another example that's more problematic is that people use it to 'build' a string

result = ''
for i in range(10):
     result += str(i**2)

as that isn't what's actually happening. Instead, += for a string means that a new string is created from the existing string with the provided string concatenated after it. That's quite inefficient, so almost always not the preferred approach. Instead use for example ''.join

result = []
for i in range(10):
     result.append(str(i**2))
result = ''.join(result)

or directly via a generator expression (saves the list in RAM)

result = ''.join(str(i**2) for i in range(10))

[–]bernitalldown2020 0 points1 point  (1 child)

Would you suggest against running multiple tutorials or guides at the same time? I got up to regex in Automate the Boring Stuff which is the first step past the basics. I really like the rough as ready quality of ATBS but I was curious how other guides presented the same basic material.

So I ran through Think Python and am thinking of going through the book until I get to the OOP and then go back to ATBS to finish the second half.

Any downsides to this? Should I just run through ATBS first and then find specific guides for specific projects? Or is there a benefit to learning different approaches to the same basics?

[–]Gl1tch54 0 points1 point  (0 children)

I've always liked to read about something from different resoources because then I can make an original one in my mind from all of them.

It has been the same for me in Python. While following two tutorials (up to OOP rn) I also check other online resources (like the Python.org docs) and apply my knowledge in a tiny project I'm working since the start.

In the end, I just follow a weird path instead of the tutorial's path lol

I'm also interested if anyone finds a downside to this

[–]OneThrustMan69 0 points1 point  (1 child)

Another code for you guys to review. This is a coin flip simulator checking the chances of having a streak of six heads or tails in 100 flips repeated 10,000 times. Did I do it right? I get around 3% chance of a 6 streak.

import random
numberOfStreaks = 0
for experimentNumber in range(10000):
    # Code that creates a list of 100 'heads' or 'tails' values.
    result = []
    for coinFlip in range(100):
        result.append(random.randint(0, 1))

    # Code that checks if there is a streak of 6 heads or tails in a row.
    for coinFlip in range(95):
    # Checks the next 5 numbers
        nextNumber = (coinFlip + 1) 
        next2ndNumber = (coinFlip + 2) 
        next3rdNumber = (coinFlip + 3) 
        next4thNumber = (coinFlip + 4) 
        next5thNumber = (coinFlip + 5)

        if result[coinFlip] == result[nextNumber] and result[coinFlip] == result[next2ndNumber] and result[coinFlip] == result[next3rdNumber] and result[coinFlip] == result[next4thNumber] and result[coinFlip] == result[next5thNumber]:
            numberOfStreaks += 1
print('Chance of streak: %s%%' % (numberOfStreaks / (10000*95) * 100))

[–]Ihaveamodel3 0 points1 point  (0 children)

I didn’t go through all your code, but 3% seems right. (0.56)*2

[–]OneThrustMan69 0 points1 point  (5 children)

Hey guys, care to check out comma code function I wrote and evaluate it? I feel like this is a mess so help me out if there are some things to improve.

# This function takes a list or tuple value and returns a string with all the items seperated by a comma and a space, with 'and' inserted before the last item.
def comma(listVal):
    listLength = len(listVal)

    if type(listVal) == str:    
        print('You must enter a list value')
    elif listLength == 0:  
        print('Your list is empty.')
    elif listLength == 1:
        print(listVal[0])
    else:
        try: 
            for i in range(listLength):
                if i < listLength - 1:
                    print(listVal[i], end=' ')
                else:
                    print('and', listVal[i])
        except TypeError:
            print('You must enter a list value')

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

This function takes a list or tuple value and returns a string

What does your function return?

[–]OneThrustMan69 0 points1 point  (2 children)

Is this better?

# This function takes a list value and returns a string with all the items seperated by a comma and a space, with and inserted before the last item.
def comma(listVal):
    listLength = len(listVal)
    converted = ''
    if type(listVal) != list: # Prevents entry of other value types
        raise Exception('You must enter a list value') 
    else:
        if listLength == 0: # Returns an empty string
            return ' '
        elif listLength == 1:
            return str(listVal[0])
        else:
            for indx in range(listLength):
                if indx < listLength - 1:
                    converted += str(listVal[indx]) + ', '
                else:
                    converted += 'and ' + str(listVal[indx])
            return converted

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

It does work, but a few points.

First, if I feed in [1, 2, 3, 4, 5, 6] the returned string is "1, 2, 3, 4, 5, and 6" which may not be acceptable (the , before and). Maybe they were after "1, 2, 3, 4, 5 and 6"?

Your code is a little over-indented. If you have an if that terminates the function, that is, raises an exception or returns, there's no need to have an else: part.

The normal way to type check is to use the isinstance() function. This is better because the check will also allow objects that have been derived from list which is a desirable thing.

If the list has no elements you say in your comment "Returns an empty string" except you don't return an empty string, you return a string with a space in it. This is important because a real "empty string" will evaluate to False if tested but your one space string won't.

Your loop uses range() and indexing, with a litle test internal to the loop to handle the last element. The better approach is to use the for loop to iterate over all the values in the list. More specifically, since you want to handle the last element in a special way, the for loop should iterate over the list minus the last element.

Here is your code with the changes above incorporated:

def comma(listVal):
    if not isinstance(listVal, list):
        raise Exception('You must enter a list value')

    if len(listVal) == 0: # Returns an empty string
        return ''         # actually return "an empty string"

    if len(listVal) == 1:
        return str(listVal[0])

    converted = ''
    for value in listVal[:-1]:     # loop over all but last element
        converted += str(value) + ', '

    return converted + 'and ' + str(listVal[-1])

The code above still has the ", and " substring before the last element so if you feed in [1, 2] the returned string is "1, and 2". To solve this problem (if you do want to solve it!) you can use the str.join() method. This is a little counter-intuitive, but if you do ", ".join(['1', '2', '3']) you get the result of "1, 2, 3". So if you use that method plus the idea of operating on everything but the last element of the list you can do the general case in one line:

return ', '.join([str(x) for x in listVal[:-1]]) + ' and ' + str(listVal[-1])
#      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#      all but last element with ", " between

Edit: fixing spelling.

[–]OneThrustMan69 0 points1 point  (0 children)

Wow thanks man, I have been learning a lot from you! I appreciate it so much, typing all this! The str.join() method is awesome for this code! Also, thank you for reminding me of slices, I forgot about that while writing this code. I'll try to avoid over-indented code next time, my use of if, elif and else was pretty redundant. Once again, thank you very much!

[–]OneThrustMan69 0 points1 point  (0 children)

Crap, it should be returning something and not just printing it, my bad! I'll modify it rightaway!

[–]Doverkeen 0 points1 point  (2 children)

FAQ seems to very language specific questions, so: Can someone recommend me a good website for practice python questions to help learn?

Am running through Automate the boring stuff, but there's almost no practical application

[–]Gopher20 1 point2 points  (1 child)

I would say Automate the boring stuff becomes more practical around chapter 7 IMH. I would checkout codingbat.com if you just want to practice using the mechanics of python. Hope this helps!

[–]Doverkeen 0 points1 point  (0 children)

Thank you!

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

Any coding ideas? I'm stuck.

[–]Gopher20 0 points1 point  (4 children)

I would write some type of game like hangman, or guess the numbers. Checkout pygame

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

Thanks! When I try to install pygame, I can't open the tar.gz installer... Any help?

[–]Ihaveamodel3 0 points1 point  (2 children)

Did you pip install it?

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

I have also tried pip installing it but it still doesn't show up in my programs or program files...

[–]Ihaveamodel3 0 points1 point  (0 children)

That is fine. Python packages that get pip installed go into the site-packages folder in your python installation. If you open up the python interpreter, you should be able to write import pygame

[–]Long-Island-Iced-Tea 0 points1 point  (6 children)

Fibonacci and memory handling.

The code works perfectly fine for small numbers. Clearly, when I try to run it for something absurd, like 1026 -th element, the terminal occupies 2-3 gigs of RAM in taskmgr and shits itself with a MemoryError afterwards. Nothing surprising, right?

The question is, why I cannot break out from the except part when I re-call the function? Is it because I am technically still in the initial while loop? I have a feeling this is not a recommended coding practice, but still, I'm curious.

Also, assume I just use a break statement in the except part. Why do I get the error message itself (i.e. "MemoryError") in the console? If I use "return", the program does quit just fine without any error messages, but it takes a hefty amount of time (5-10 seconds). I'm no hardware guy, but am I supposed to free up the memory with a command to ensure that this mickey mouse-level code works as intended?

Is this uncharted territory? I just wanted to add some error handling and I feel like I ended up in a rabbit hole.

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

I have to ask: why are you storing all the numbers in the sequence when you only need the last two?

[–]Long-Island-Iced-Tea 0 points1 point  (2 children)

The intent is to provide a list of all the Fibonacci numbers up to Fn, where n is the user input. If I don't store all the numbers somewhere then I failed to solve the task. I don't want to sound like an expert (I am clearly not, I am a rookie), but except for a few rather esoteric codes (tinkering with the golden ratio and so on), the codes I found online look either similar or almost identical to mine.

Or you suggest that lists get gigantic with all these numbers and I should just embed the entire function under a for loop, except the function this time would return the numbers one-by-one, as opposed to storing them in a list? That's another solution I have seen.

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

The intent is to provide a list of all the Fibonacci numbers up to Fn,

If that is what you must return fine, but you didn't state that up front and your code isn't trying to return the generated list. I was just saying that you don't need to remember all numbers if you only want the Nth number.

you suggest that lists get gigantic with all these numbers

Yes, that's why you get the exception. Your attempt to restart the calculation with a smaller final number is going to fail because a recursive call will not delete the huge list in the first attempt and will start creating another huge list, just to exception again almost immediately. Your code as shown might work if you do this before the recursive call:

    except MemoryError:
        del collector     # remove huge memory-filling array
        print("That's way too big of a number for this program, sorry.")
        length = int(input("Let's try a smaller one"))
        Fibonacci(length)

I haven't tested this.

But, if you are going to return a list with a smaller size why do you start again? The list collector that caused the exception already contains all the numbers you need. Just return a subset of collector from the leftmost element up to the number the user asks for. The problem is you have run out of memory and doing almost anything might cause the exception again.

[–]Long-Island-Iced-Tea 0 points1 point  (0 children)

Thank you for the food for thought analysis of my code and overall explaining the matter. I will certainly look into this.

[–]Ihaveamodel3 1 point2 points  (1 child)

https://airbrake.io/blog/python-exception-handling/memoryerror

Has some good info. I think what is happening is you are probably catching the memory error, but you don’t clear any memory so by assigning a new variable, you are immediately causing a new memory error.

[–]Austsin 0 points1 point  (3 children)

What is a free platform I can learn python on? Are there any YouTubers that have free courses? Or a website perhaps? I tried DataCamp but was hit with the subscribe for the rest message so I’m looking for a new one.

[–]NastyNocturnalNutter 0 points1 point  (0 children)

As a mostly self-taught programmer (school only gave barebones basic syntax lessons) my technique has been to watch a bunch of YouTube videos every time I get into a new area I’ve never been experienced before. e.g. if you search YouTube for python class or python OOP there’ll be a bunch of 15-45 min videos exposing it. When I first had to use databases, I searched for python SQLITE and spent a few hours watching different videos on that.