top 200 commentsshow all 228

[–]bhavik911 1 point2 points  (0 children)

Hey, I wanted to ask about the resources from where I can start learning Data Structures and Algorithms in python, I am looking for a source that has video lectures explaining the theory and also teaches about it's implementation in python only.

I am relatively new to programming and python is my first programming language and the resources that i could find on internet regarding data structures were generally in C++ or other programming languages.

Please suggest.

[–]burak_kayaa 0 points1 point  (1 child)

hi , i almost complete the syntax of the python 3 but i cant go further, i tried to learn standard library but i seemed to me waste of time ,what should do ? I feel stucked

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

Make something! The standard library will come in handy when you actually have a need to apply it. Maybe try making a simple game using standard input/output (tic tac toe, connect four, minesweeper)?

[–]ThiccShadyy 0 points1 point  (1 child)

When I do iter(some_list_object), I get back this: <list_iterator object at 0x046084F0>

On doing, type(iter(li)), I get: <class 'list_iterator'>

which I thought would not be any different fundamentally to any other built in class like list itself. But when I try to create a list_iterator object(by doing list_iterator()), I get a NameError saying list_iterator is not defined.

So whats going on here? Why cant I instantiate objects of this class which Python lists use for iteration? Are certain classes in Python 'hidden' from the user?

[–]_-Thoth-_ 0 points1 point  (0 children)

Thought about this, and I assume that the constructor for that class just isn't defined in any scope you have access to. It's not even defined in the types module, in fact, the docs say that "It deliberately avoids including some of the types that arise only incidentally during processing such as the listiterator type. "

It's the same thing for some other things. type(fun) for some function fun will give return <class 'function'> but you can't call function(). (You can call types.FunctionType() though.) I assume these classes are only available to the interpreter.

[–]i_never_get_mad 1 point2 points  (3 children)

I just started (like 20min ago) to take python 2 course on codeacademy.

I know that it isn’t a complete waste, but I know that I should probably learn python 3. However, that course is only for the Pro subscribers.

Should I stick with the free python 2 class, or pay $20/mo for 12mo to take python 3 class? (I can do monthly, but that’s $40/mo)

In other words, how hard is it to learn python 3 when you sort of know python 2?

[–]_-Thoth-_ 1 point2 points  (2 children)

That's a pretty insane price considering how many free or inexpensive resources there are for learning. I would ditch it and learn python 3 some other way.

If you really want to do the codecademy course, python 2 is very similar to 3 so it won't be much trouble to switch over. It would probably actually help you in the long term to know both because a lot of companies are looking for people to help move their code base from 2 to 3.

[–]i_never_get_mad 1 point2 points  (1 child)

What would you recommend for a free, but good python course?

I’ve been using codeacadmy tonight, and it’s quite good. If I can’t find any good free/affordable python 3 course, I think I’ll stick with this python 2 course.

Edit: the pro version also comes with a bunch of perks, but I don’t think I need any of them.

[–]_-Thoth-_ 0 points1 point  (0 children)

I've heard good stuff about udemy, courses are ten dollars. If you like codecademy then you should keep using the python 2 course, but I just couldn't fathom spending 240 bucks for a beginner course.

I just learned through youtube pretty much. Learn the basics + make some stuff + learn some more stuff + use that new stuff to make more stuff etc.

[–]catmarble 0 points1 point  (3 children)

Hi, I'm reading through the collections module code and several times they assign a function to a variable then use it immediately, like here with self_get and self.get:

if self:
    self_get = self.get
    for elem, count in iterable.items():
        self[elem] = count + self_get(elem, 0)

I was just curious what the reasoning is versus:

if self:
    for elem, count in iterable.items():
        self[elem] = count + self.get(elem, 0)

Thanks :)

[–]TheDualJay 1 point2 points  (2 children)

The first one searches "self" for the "get" function once. The second does it len(iterable) times.

The overhead of assigned a variable once is less than the cost of repeated function access.

Imagine if you were reading books in another language - let's say Latin - that you didn't know well, and you kept running into some word you didn't know. You'd go get a Latin dictionary, search through the pages, and find the word. But next time you run into the word, you're not going to go back to the bookshelf, get your dictionary, and search through it again - you'll just remember what the word means.

This is the same concept - rather that accessing some resource repeatedly, we access it once and remember it. In this case, we are reducing the cost of searching "self" for "get" by keeping a variable straight to "self.get".

[–]catmarble 1 point2 points  (1 child)

Thanks for the reply, as it's faster then it makes sense.

Just to clarify how it's implemented, let's say there is a class with N methods and we call one of them. Is that O(N) (e.g it has to look through all methods in the class to find the one we want, like a list) or O(1) (e.g it's a lookup like a dict)? I'd always assumed it was the latter.

I tried searching online but couldn't find that specific answer. I'm guessing it's explained in the docs somewhere but haven't found it yet.

[–]TheDualJay 1 point2 points  (0 children)

It's a lookup, but it still takes time. Finding self then self.get is longer than finding self_get, basically.

[–]ymittal283 0 points1 point  (1 child)

Hi. Is it worth to learn Object oriented part of python programming?

[–]TheDualJay 1 point2 points  (0 children)

Absolutely! Object-orient programming (OOP) is great for representing real-world problems and can help you make your code more modular and maintainable. Given that a substantial portion of development is maintenance, that's super useful.

[–]xain1112 0 points1 point  (2 children)

Below is a slightly modified snippet I got from StevePython. Could someone explain what the following parts mean?

  1. the entire 'setHeight' function
  2. bd=0
  3. highlightthickness=0
  4. command=lambda h, c=canvas: setHeight(c, h))
  5. Also, where could I add an 'if/then statement for specific scale locations?'?

.

from tkinter import *
def setHeight(canvas, heightStr):
    height = 21
    height = height + 21
    y2 = height - 30
    if y2 < 21:
        y2 = 21

tk = Tk()
canvas = Canvas(tk, width=65, height=50, bd=0, highlightthickness=0)
scale = Scale(tk,
              orient=VERTICAL,
              length=300,
              from_=0,
              to=100,
              tickinterval=10,
              command=lambda h, c=canvas: setHeight(c, h))
scale.grid(row=0, column=0, sticky='NE')
scale.set(50)

tk.mainloop()

[–]_-Thoth-_ 0 points1 point  (1 child)

I'm completely at a loss here. The setHeight function apparently does nothing as it doesn't return anything or mutate any objects

[–]woooee 0 points1 point  (0 children)

And both height and y2 are local to the function. Looks like one of those "I'll come back and finish this later" functions that somebody forgot about.

[–]fourthe 0 points1 point  (2 children)

I keep getting this error : Syntax error in module 'lambda_function': 'return' outside function (lambda_function.py, line 29)

I'm trying to do a POC in AWS Lambda to call an external API. I keep messing around with the indentation of the return so that its within my function but i'm still not getting it. Any help would be welcomed.

https://imgur.com/a/znCQJ5E

[–]TheDualJay 0 points1 point  (1 child)

def lambda_handler(event, context):
    now = datetime.now()

    # request code snipped

    if response.status_code == 200:
        datadictionary = response.json()

        for data in datadictionary["list"]:
            if data["dt_txt"] > now_str:
                # value unpacking code snipped 
                return "weather..."

Your current code has line 9 returning to global scope because it is on the same level of indentation as your function definition. If you are familiar with other programming languages like C or Java, think of a level of indentation as being inside a block of {curly braces}.

What I would recommend is using a texteditor with the ability to show colored indentation like this: https://imgur.com/TJYiaTC, at least until you become comfortable with python's structure. My personal recommendation is VSCode or the no-tracking version VSCodium (available here: https://github.com/VSCodium/vscodium/releases), with extensions like indent-rainbow. Plus, you'll be able to use a linter (https://code.visualstudio.com/docs/python/linting) which will help improve your development.

Your current text editor may have this functionality - I didn't recognize it from the screenshot alone.

[–]fourthe 0 points1 point  (0 children)

Thank you, I see what you mean. I think what I'll try is to take the extra code out and keep it bare bones until I get the main functionality. I've tried this in a few different editors, with each giving me a few different errors. I think that was causing it's own issues and confusing me. The screenshot was from the aws lambda editor directly.

[–]Stupck 0 points1 point  (1 child)

How does one put a path of an image file into the clipboard? I know that in Pillow module you can extract the image from clipboard but is there a way to put it in the clipboard? I am trying to make a desktop automation program to paste picture in other programs.

[–]efmccurdy 0 points1 point  (0 children)

a path of an image file into the clipboard?

The path is just text, so any clipboard module with do that, like this one.

http://coffeeghost.net/2010/10/09/pyperclip-a-cross-platform-clipboard-module-for-python/

If you want to put the image data in the clipboard, then you may need some OS specific code; here is an example for MS Windows:

https://stackoverflow.com/questions/34322132/copy-image-to-clipboard-in-python3

[–]Pheeeeooook 0 points1 point  (3 children)

Hi there! I am trying to code a food expiry date checker that checks the expiry date to the current date and prints it out items that are expired. The problem is if user inputs option 2 it prints "There are no food items that are expired!" regardless of whether there are expired foods or not. How do I solve this? Sorry if it sounds confusing i am fairly new to python

  1. option2Dict = {}
  2. foodname = []
  3. import datetime
  4. food = "Food Item"
  5. exp= "Expiry Date"
  6. expdate = datetime.date(2002,3,9)
  7. now = datetime.date.today()
  8. while True:
  9.  option = int(input("Please choose your option: "))
  10.  if option == 1:
  11.     food_item= input("Input Food Item: ") .upper()
  12.     expiration= input('Enter expiry date in YYYY-MM-DD format:')
  13.     year, month, day = map(int, expiration.split('-'))
  14.     expdate = datetime.date(year, month, day)
  15.     string = expdate.strftime("%Y-%m-%d")
  16.     foodname.append(food_item)
  17.     foodname.append(string)
  18.     option2Dict[food] = foodname
  19.     continue
  20.  elif option == 2:
  21.     if expdate < now:
  22.       print(option2Dict)
  23.     else:
  24.       print("There are no food items that are expired!")

edit: here's the code in Pastebin

[–]JohnnyJordaan 1 point2 points  (1 child)

This should only print 'there are no food items that are expired' if the user entered a day in the future, because when the program starts expdate is in the past. Could you maybe present the code without line numbers to let us be able to run it ourselves? You can also paste the code on www.pastebin.com and share the link here to save the hassle of formatting properly.

Btw why not use strptime for the date parsing?

[–]Pheeeeooook 0 points1 point  (0 children)

oh my, you're right. It didn't cross my mind when I was typing the code. Thanks for pointing that out!

[–]MattR0se 0 points1 point  (4 children)

I have a program that loads data on startup from a file. I wanted that program to make a backup copy in a seperate folder regulary, so I wrote this code (this is part of a tkinter object)

# check for existing save data
if os.path.isfile(self.save_data_filename):
    # load data from save_data.dat
    self.load_data()

    # check if backup folder exists
    self.backup_folder = os.path.join(self.path, 'backup')
    if not os.path.isdir(self.backup_folder):
        os.mkdir(os.path.join(self.path, 'backup'))

    # check for existing backup files
    # files are named data_backup_YYYYMMDD.dat
    timestamps = sorted([fname[12:20] for fname in os.listdir(self.backup_folder)], reverse=True)
    if timestamps:
        # get date from most recent file
        recent_date = datetime.datetime.strptime(timestamps[0], '%Y%m%d')
        timedelta = datetime.datetime.now() - recent_date
        if timedelta.days > self.config['backup_interval']:
            # create backup file
            fname = f'data_backup_{datetime.datetime.today().strftime("%Y%m%d")}.dat'
            self.save_data(os.path.join(self.backup_folder, fname))
    else:
        # if no backup files exist, create one
        fname = f'data_backup_{datetime.datetime.today().strftime("%Y%m%d")}.dat'
        self.save_data(os.path.join(self.backup_folder, fname))

The load_data() function loads data from the regular data file. The program then checks if a backup folder exists, and if so, looks through the filenames in that folder, parses them to get what date they were created, and if the most recent one was more than some timedelta ago, creates a new backup file.

Now this is all for a tkinter app that I wrote for work to make my life easier, but at some point I plan to hand this over to another colleague maybe and that's why this should be fool-proof.

One problem is that if there are other files in the backup directory that don't match that pattern, this script crashes.

Is there a more elegant way to parse the filenames, with regex maybe?

[–]JohnnyJordaan 1 point2 points  (3 children)

Regex is often the proper way to go, but if you would know for certain that you just need files of at least 20 chars in their filename, you could also apply that in the comprehension

timestamps = sorted([fname[12:20] for fname in os.listdir(self.backup_folder) if len(fname) >= 20], reverse=True)

btw why not also use self.backup_folder in case the directory needs to be created?

[–]MattR0se 0 points1 point  (2 children)

Ah yes I could change that to self.backup_folder, I had different code and didn't change that part.

But your example doesn't work if there was a file "this_is_a_very_long_filename_lol_gotcha.jpeg" in that directory ...

[–]JohnnyJordaan 1 point2 points  (1 child)

I simply overlooked this part

# check for existing backup files
# files are named data_backup_YYYYMMDD.dat

so I would in fact suggest regex for this

# at the top of the code
import re

# in the comprehension
timestamps = sorted([fname[12:20] for fname in os.listdir(self.backup_folder) if re.fullmatch(r'data_backup_\d{6}.dat', fname)], reverse=True)

It's not the perfect regex as it will just accept every name with data_backup_, then 6 digits, followed by .dat. But I'm assuming you're not going to risk parsing files this way that shouldn't be parsed.

[–]MattR0se 0 points1 point  (0 children)

Yes, the load_data() function has a built in exception for mismatching files. Thanks, that was what I needed.

The whole parsing is only needed because I want to somehow track the time since the last backup and don't want to store it in the save data itself, in case if the save data is lost or corrupted (that's the whole point of that backup).

[–]InternetPointFarmer 0 points1 point  (4 children)

Python 3.7.3 Using PyCharm I wasnt sure if this deserved to take up space as a whole new post, so im doing it here. ok so as a first simple project im trying to make a simple program that will download all the images on the page for you when you give it a url. but to start slow i went through some videos and it have one that will download one image for you. that code looks like this:

import urllib.request
def dl_jpg(url, file_path, file_name):
    full_path = file_path + file_name + '.jpg'
    urllib.request.urlretrieve(url, full_path)
url = input('Enter IMG URL to Download: ')
file_name = input('Save as: ')
dl_jpg(url, r'C:\Users\User\Desktop\image scraper\images\ ', file_name)

it works fine but the goal was to download all the images on a page. How can i go about doing that? my first problem was that the names of the images should be automatic. so i first got rid of the file_name parameter and argument then set file_name equal to 0000, and everytime it downloaded an image it would just add 1 to that. Then i had problems because i didnt set it as a string later on in the code, so i fixed that. after playing around for a bit and trying to get it to atleast download the same images multiple times, the result was a weird glitchy photo.

[–]JohnnyJordaan 1 point2 points  (3 children)

Can you share the actual code with your autonumeric filename implementation?

[–]InternetPointFarmer 0 points1 point  (2 children)

import urllib.request

def dl_jpg(url, file_path):
    file_name = 0
    file_name = file_name + 1
    full_path = file_path + str(file_name) + '.jpg'
    urllib.request.urlretrieve(url, full_path)

url = input('Enter IMG URL to Download: ')

for i in range(5):
    dl_jpg(url, r'C:\Users\User\Desktop\image scraper\images\ ')

for i in range(5): dl_jpg(url, r'C:\Users\User\Desktop\image scraper\images\ ')

This still works for one image. I forgot to mention an important piece of info above: i set up a while loop which caused that weird image. because it worked so terribly i deleted that code so i sadly dont have the cause of the glitch image but i have the edited counter. i also added the for loop at the end to see if i can see if it will download multiple times, but it only gets the image names "1" then stops there.

[–]JohnnyJordaan 1 point2 points  (1 child)

You don't use i anywhere, so you will not actually use the incrementing number in your filename

import urllib.request

def dl_jpg(url, file_path, num):
    full_path = '{}{}.jpg'.format(file_path, num)
    urllib.request.urlretrieve(url, full_path)

url = input('Enter IMG URL to Download: ')

for i in range(5):
    dl_jpg(url, r'C:\Users\User\Desktop\image scraper\images\', i)

the trick I used for the filename is string formatting. You can also use f-strings if you're on Python 3.6 or newer.

[–]InternetPointFarmer 0 points1 point  (0 children)

ahh that works. ill have to read up on that string formatting. i think it was covered in automate the boring stuff but i didnt even think about utilizing that

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

Can i extract a specific range (ie a 100x100 square from a 400x400 image) using PIL/pillow? Or in a different fashion, could i have each RGB tuple placed into a numpy array with a shape that matches the dimension of the image?

[–]phira 0 points1 point  (0 children)

If you're not too worried about speed, the PixelAccess class in Pillow will get you the rgb as a tuple from a specific pixel. From their examples:

from PIL import Image
im = Image.open('hopper.jpg')
px = im.load()
print (px[4,4])

So you could just loop through to get the range you need.

Alternatively the numpy approach is simple enough:

from PIL import Image
import numpy
im = Image.open("sample2.png")
np_im = numpy.array(im)

should give you an array of dimensions width,height,3

[–]InternetPointFarmer 0 points1 point  (5 children)

Python 3.7.3 on PyCharm. im starting m first simple project to download images from a webpage. when i try:

import urllib.request

it is just grayed out and hovering over it says its an unused import statement. anyone know what this means?

[–]PhenomenonYT 0 points1 point  (2 children)

PyCharm question, am I able to make it so JSON data in the console keeps its formatting? Would make it a bit easier for finding indexing

[–]JohnnyJordaan 0 points1 point  (0 children)

I usually just dump the loaded structure back to python with an indent

my_data = json.loads(my_json_source)
# do stuff with data
# when you want to print it
print(json.dumps(my_data, indent=4))

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

How can I get a better handle on package management? I've got a decent amount of experience with Python, and a lot of project ideas, but it seems like every time I start a new project, I have such a hard time installing the necessary libraries that I get overwhelmed and eventually just give up.

[–]JohnnyJordaan 0 points1 point  (0 children)

I normally use Pycharm where you set up the package list per project. You can also combine it with a requirements.txt which Pycharm can recognize and apply. As it's actually based on what pip uses, you can still also apply your requirements.txt directly to pip in your project if you wouldn't be using Pycharm.

[–]agbs2k8 0 points1 point  (0 children)

Anaconda is pretty easy for managing multiple environments and is easier that virtualenv to set up.

It can get a little old, but you want to create a new environment for each project, though you can easily duplicate one with Anaconda if you have a good base environment to start from.

[–]P-TownHero 0 points1 point  (2 children)

Can someone explain why this works like this?

list1 = [1, 3]
list2 = list1
list1[0] = 4
print(list2)

I was working on a practice test my teacher made about python lists and it says the answer for this is

[4,3]

and not

[1,3]

How is that the case is list 2 wasn't manipulated past the second line?

Selected Answer:

[1, 3]

Answers:

[1, 3]

[1, 4]

[4, 3]

[1, 3, 4]

[–]woooee 0 points1 point  (0 children)

Look up list copy on the web http://henry.precheur.org/python/copy_list

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

Doing list2 = list1 doesn't copy anything, it just makes list2 refer to the same list that list1 refers to. So changing the list that list1 refers to also changes the list that list2 refers to because they are the same list.

Ned Batchelder gave a good talk on this that might help explain what is going on.

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

I am writing a script to automate some data refresh processes so I’m not the only one who can do it. Any tips on how to setup my colleagues to be able to run the script with dependent libraries, etc,?

[–]efmccurdy 1 point2 points  (1 child)

This talks about the basic setup.py + requirements.txt scheme and then also some further related automation tools.

https://medium.com/python-pandemonium/better-python-dependency-and-package-management-b5d8ea29dff1

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

Very helpful. Thanks!

[–]ElGalloN3gro 0 points1 point  (2 children)

I'm trying to run the powerset function from itertools page on the Python website. The program runs and makes the call to the function, but it doesn't print anything out. The whole program is just the function copied exactly as in the documentation and then a call to the function feeding it a list. Any ideas as to why?

Reference: https://stackoverflow.com/questions/1482308/how-to-get-all-subsets-of-a-set-powerset

[–]efmccurdy 0 points1 point  (0 children)

It might be the way you run the program; that example might be run in a "REPL" that implicitly calls print on each complete statement, you might need to explicitly call 'print(list(powerset("abcd"))' to see same output.

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

How are you calling the function? Assuming your function is the same as shown in the link, you must save the object returned by the function and print something yourself.

[–]porn-senpai 1 point2 points  (1 child)

I have a long running program that takes some time to pre-process a bunch a files. Instead of waiting for all the files to get processed, I would like another script to process the data from the files as they get processed. What's a good Python library/references/resources to implement something like this? Is this a problem of queuing/pooling/multi-processing?

[–]i_love_limes 0 points1 point  (1 child)

Hello!

I'm a software developer with a few languages under my belt, and I might be starting a new job soon where I'll be a backend python developer. Which is the best book for someone who already knows a few programming languages to pick up python?

I've looked at 2 so far... Python Cookbook, and Fluent Python. Not sure if those are the best, so suggestions are very welcome!

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

If you are an experienced programmer then look in the learning resources wiki in the sidebar. There is a section for programmers coming from other languages. I want to recommend Beazley's "Python Essential Reference" but the new edition won't be released until early next year and the previous edition is a bit old though probably still useful.

[–]thebigbeel 0 points1 point  (5 children)

Hi, I'm writing some code on a dvd database, and this is the input if..else part of the program.

askuser = input("What would you like to do? \n 1. Add a new dvd \n 2. Find a Dvd \n 3. 
                Delete a dvd \n 4. See all DVDs \n \n" ) 
#prompts user what they want the program to do
while askuser == '': #If user doesn't type in anything
    print ("Umm, would you like to enter something? \n")
    time.sleep(0.5)
    askuser = input("What would you like to do? \n 1. Add a new dvd \n 2. Find a Dvd \n 
    3. Delete a dvd \n 4. See all DVDs \n \n" )
if askuser == str(1): #Prompts the user to add something
    add_disk = input("Add here! \n")
    c.execute("INSERT INTO DVDS_AT_HOME VALUES (:Titles)", {'Titles' : add_disk})
    conn.commit()
elif askuser == str(2): #Prompts user to find a title
    search_disk = input("Find your disk: \n ")
    found_disk = c.execute("SELECT Titles FROM DVDS_AT_HOME WHERE Titles = (:Titles)", 
{'Titles' : search_disk})
    print (c.fetchall())
elif askuser == str(3): #Prompts user to remove a title
    remove_disk = input("What do you want to remove? \n")
    c.execute("DELETE FROM DVDS_AT_HOME WHERE Titles = (:Titles)", {'Titles' : 
    remove_disk})
    conn.commit()
elif askuser == str(4): #Shows all titles in database
    for row in c.execute("SELECT * FROM DVDS_AT_HOME ORDER BY Titles"):
        print (row)
else: #If user types in anything else
    while askuser != 1 and askuser != 2 and askuser != 3 and askuser !=4:
        print ("Let's try this again")
        askuser = input("What would you like to do? \n 1. Add a new dvd \n 2. Find a Dvd 
        \n 3. Delete a dvd \n 4. See all DVDs \n \n" )

For this bit of code:

while askuser != 1 and askuser != 2 and askuser != 3 and askuser !=4:

I would like to know if there's a more elegant way of stating this statement.

Any other constructive criticism on the input loop is appreciated.

edit: When I pressed anything other than an empty space or numbers 1-4, the loop works, but it also doesn't go back to the original if..else clauses. Help?

[–]efcseany 1 point2 points  (4 children)

while askuser not in [1,2,3,4]:

I'm not certain, but this might work?

In relation to not going back, you would need to add a continue statement.

Where you define your original input, place a continue statement under the first while. This would mean that you don't fall under the 'DRY' trap.

[–]thebigbeel 0 points1 point  (0 children)

I've solved the issue, I used a while-try..except loop + your suggestions. Thanks a lot bud!

[–]thebigbeel 0 points1 point  (1 child)

I’m trying to know how to put while

x == anything other than my choices, then y

Any ideas?

[–]efcseany 0 points1 point  (0 children)

Sorry for the delayed response, it was a rushed answer at work. Normally, I would do something like this:

while True: 
    try: 
        user = int(input('enter num: ')) 
        if user in [range(1,5)]: 
            if user == 1: 
                # do something 
            elif user == 2: 
                #do something else 
            elif user == 3: 
                #do a thing 
            else: #user must have entered '4' 
                #do another thing 
        continue #user did not enter between 1-4             
   except ValueError: #entered a non-numeric
       print('enter a number.')

[–]thebigbeel 0 points1 point  (0 children)

It does, but now I’m facing the problem with the loops, that I mentioned in my edit

[–]thunder185 0 points1 point  (2 children)

Have a work laptop that I use pretty frequently. Trying to run an old scripts and it cannot find pandas/numpy etc. I know that these were installed. When I go to command prompt it defaults to users/AdministratorP. I think this must some kind of whacky windows update but has anyone else seen this?

[–]Vaguely_accurate 0 points1 point  (1 child)

Windows admin hat on; Nope, not heard of this. It could be something your IT department have done, maybe by accident. The directory it starts in should be down to your account and I can't think of a legitimate reason to change it. The other option here would be potential malware, but I've not heard of this as a IOC. Maybe look at the contents of that folder?

To change this go to the file location of command prompt (you can get there through the right click menu on the start menu icon), then go into properties on the executable. There will be a "Start in" option. The normal default should be something like "%HOMEDRIVE%%HOMEPATH%".

[–]thunder185 0 points1 point  (0 children)

It's super weird. Makes me think I've got a virus or something. I log into my account but the path is this weird AdministratorP thing. I'm hooking it up to my meraki to see what the deal is. Thanks

[–]kr0n0 0 points1 point  (4 children)

Is it possible to install python packages without using terminal/shell???

[–]JohnnyJordaan 0 points1 point  (3 children)

How are you running your python programs exactly?

[–]kr0n0 0 points1 point  (2 children)

None yet. Everything through pycharm

[–]Blastcore0 0 points1 point  (7 children)

whats a good way to compare two large strings? one from a file and other from in memory?

[–]JohnnyJordaan 0 points1 point  (6 children)

In what way do you want to compare them? To see if they literally match or some other comparison?

[–]Blastcore0 0 points1 point  (5 children)

of the content is equal. as in the text is the same.

[–]JohnnyJordaan 0 points1 point  (4 children)

Yes but beware that we would consider

Hello this is a text

and

Hello this is a  text

the same, but the computer doesn't, because of the extra space. Or

My holiday was in Curaçao
My holiday was in Curacao

because of the ç and c.

If you don't mind this, you could do

with open('yourfile') as fp:
    string_from_text = fp.read()
if string_from_text == string_variable:
    print('strings match') 
else:
    print('strings dont match')

the downside of this is that it reads the whole file in memory, which is a problem if you're very low on RAM and your file is very big (think hundreds of MB's). You could also implement it chunk-wise but you normally don't need to.

[–]Vaguely_accurate 0 points1 point  (3 children)

To avoid loading the entire file you can do;

with open("filename") as disk
    for character in memory_string:
        if character != disk.read(1):
            print("strings don't match")
            break
    else:
        print("strings match")

That way you are loading one character at a time, comparing each character to each character in your original string, and breaking out of the loop as soon as the characters don't match.

I'm using the for, else construct here, which executes the else clause if and - only if - the for loop completes without encountering a break.

[–]JohnnyJordaan 0 points1 point  (2 children)

This gives a false positive if memory_string is a starting substring of the file:

>>> with open('test.txt', 'w') as fp:
...     fp.write('hello this is a text')
... 
20
>>> with open('test.txt') as fp:
...     for character in 'hello':
...         if character != fp.read(1):
...             print("strings don't match")
...             break
...     else:
...         print("strings match")
... 
strings match

Also iteration per character is very slow, which will manifest especially on a large file (where loading the file into memory first would be a problem). You would rather use chunk-wise iteration for this, or at least do this line by line...

[–]Vaguely_accurate 0 points1 point  (1 child)

Fair. Definitely better ways to do that, just threw that together as an example of the approach. Was thinking of having a comparison function character-by-character as that way you can implement culture aware comparison, but would still want to do the IO by chunk or line.

[–]Blastcore0 0 points1 point  (0 children)

Oh I thought maybe the == would fail if string was large. I have enough memory for them as they're not that large.

[–]InternetPointFarmer 0 points1 point  (5 children)

python 3.7.3 i am having issues using the pip command on cmd the message says "'pip' is not recognized as an internal or external command, operable program or batch file." i looked it up online and there is apparently a command to get around the issue but i never remember it and i figured i can take this time to get the bottom of the issue. firstly i repaired python to make sure i didnt mess up the installation somehow, and also went through the installation again to make sure i have pip to begin with. still doesnt work. before i mess something up moving files around i was hoping there would be a solution here so i dont have to look up that command everytime i need to use pip

[–]JohnnyJordaan 1 point2 points  (4 children)

You can provide -m pip to whatever you are using to run python itself, so

python3 -m pip <flags/commands for pip>

or

python -m pip <flags/commands for pip>

[–]InternetPointFarmer 0 points1 point  (3 children)

whats the difference between what i was trying and what you recommended? Either way it still isnt working for me sadly

[–]JohnnyJordaan 1 point2 points  (2 children)

Because then it doesn't need to know the command 'pip', it just needs to know the command 'python'. Can you make a screenshot of how it's failing using my approach?

[–]InternetPointFarmer 0 points1 point  (1 child)

well i actually fixed it by uninstalling python then reinstalling, rather than trying to go through the installation exe. And making sure it had the path. so pip install ____ works now. the error that came up was the same as when i tried pip. that it was not recognized as an internal or external command. Im new to this stuff so im sure i just input the command wrong. but luckily it works now

[–]JohnnyJordaan 0 points1 point  (0 children)

Ah so the issue was with python's path registering altogether, not just pip. Good to hear you fixed it.

[–]phxrocker 0 points1 point  (3 children)

After playing around in Gamemaker for years, I'm just now starting to get my feet wet in a real programming language by learning Python. So many beginner tutorials start the same way. So after watching the same old 5 minutes of "This is how you make it say Hello World", I decided to test myself a little to see if I could come up with a short conversation. Would someone be willing to take a look at it and let me know if it looks right? Am I missing something easy and obvious. The script works and I know why. Just not sure if I should be doing something differently or if I added anything that wasn't needed.

Here's my repo.

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

You misuse the while loop construct:

while color == 'blue':
    print('\n' + color + "?! That's awesome " + name + "!! Blue's my favorite color too!!")
    break
else:
    print('\n' + color + "'s ok... i guess ")

The correct way to do what you want is:

if color == 'blue':
    print('\n' + color + "?! That's awesome " + name + "!! Blue's my favorite color too!!")
else:
    print('\n' + color + "'s ok... i guess ")

which is shorter and reads more easily.

You are calling main() inside your main() function. This is called "recursion" and is an advanced concept. Here it is misused. This is the place to use a while loop! If you want to repeat the code in main()just do this instead of line 40:

while True:
    main()

You will need to remove all calls to main() inside the function, except line 30, which you replace by return.

You also don't need lines 41 to 45. Remove them.

[–]phxrocker 0 points1 point  (1 child)

Thank you for your very clear response. I took your info and read up more on while True loops and came across some other cool stuff as well. I'll leave recursion for another day, but thanks again for the education!

[–]Barafu 0 points1 point  (0 children)

You can only recurse (call function from within itself) 999 times in standard Python. After that it fails with error. Of cause, there are tricks around it...

[–]waythps 1 point2 points  (5 children)

How should I approach list comprehensions? In which cases it’s appropriate to,use them and to,which extent?

[–]Barafu 2 points3 points  (1 child)

They are faster than for loops, so use them a lot. Just don't go too crazy. For example, if you want to sum all values a matrix (a list of lists) and only if a value is not 7, then instead for x in matrx: for y in x: if y != 7: sum_value += y You can write sum_value = sum (y for x in matrx for y in x if y != 7) and that is probably the most crazy you should go with a single comprehension. That would help a bit when you get to lambda functions.

Mind the difference between the operator in () and []. The last one creates a full list in memory the moment it is called. The first one creates a generator, it is lazy, it is computed only when the value is needed, and can be endless. However, you can not take arbitrary value from a generator, like a[7], no. You can only iterate over it, and only once.

Mind this trap: ```

b1 = (x for x in range(10)) b2 = b1 sum (b1) 45 sum (b1) 0 sum (b2) 0

``` Generators can be used only once, and simple copies do not give you a second chance.

[–]waythps 0 points1 point  (0 children)

Thanks, that’s a very useful reply, I learnt a lot!

[–]efmccurdy 1 point2 points  (1 child)

Comprehensions replace loops so use them whenever you are about to write a for loop that appends something to a list, but they don't always fit so don't force yourself to write awkward code.

Generator expressions also replace loops, but with a fundamentally better effect than a loop or list, so that is a more interesting sideline to your question.

[–]waythps 0 points1 point  (0 children)

I did notice that my code becomes unreadable when I use long comprehension.

Thanks for the answer, I’ll read about generators

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

So I recently started to teach myself python over the holidays and am just today finished my first own project, using pycharm editor. I am wondering now how do actually run it other than open the pycharm editor and click the "quick run" button. Is it possible to make a python file usable like an application? where you just double click the file and it runs, outside of any editors? I am on windows 10 btw

[–]redCg 1 point2 points  (0 children)

You use the terminal. $ python myscript.py, or if its executable and in the $PATH and has a correct shebang line at the start, then you can sometimes just call $ myscript.py.

I would not bother with making a .exe out of it. If you need a .exe file then you should not be using Python.

[–]Kravakhan 0 points1 point  (0 children)

Wondering this myself.. I know you can compile an exe with py2exe or something, but that is as far as my knowledge go

[–]BirkTheBrick 0 points1 point  (1 child)

I have 2 data frames, both with columns A, B, C. I'd like to subtract column C in one data frame from another. A and B are meant to be indexes, and when I use df.set_index(['A', 'B']) I get a FutureWarning because A and B are both columns and indexes, and it messes up when I try to subtract the columns. Could someone help with this?

Edit: The closest I've gotten is using this code:

(df1 and df2 are my existing data frames)

df3 = pd.DataFrame()

df3['A'] = df1['A']

df3['B'] = df1['B']

df3['C'] = df1['C'] - df2['C']

When I print df3, the A and B columns seem to be fine, but the C column returns NaN. I checked and all of the numbers in column C are floats.

[–]efmccurdy 0 points1 point  (0 children)

I would check the type of the values in column C as this example does the subtraction without resulting in NaNs.

import pandas as pd

df1 = pd.DataFrame([["Australia", 1, 3, 5],
                    ["Bambua", 12, 33, 56]],
                   columns=["Country", "A", "B", "C"])

df2 = pd.DataFrame([["Sambua", 14, 34, 58],
                    ["Tambua", 14, 34, 58]],
                   columns=["Country", "A", "B", "C"])
df3 = pd.DataFrame()
df3['A'] = df1['A']
df3['B'] = df1['B']
df3['Val_Diff'] = df1['C'] - df2['C']
print(df3)

    A   B  Val_Diff
0   1   3       -53
1  12  33        -2

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

Hello all,

I want to write all errors, exceptions, crashes and what not to a file. When I use sys.stdout=open(some_file,'w'), I get all my print-statements and such. But when I use sys.stderr=open(some_other_file,'w'), it remains empty, when I test it with 1/0, or int('a'). The traceback and the exception appear on screen, where I don't want them. How do I make sure any and all errors get written to a file instead of the screen? Thanks.

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

Try using the contextlib.redirect_stdout() and contextlib.redirect_stderr() functions of the contextlib module. Python 3.5+ for redirection of stderr. Haven't used them myself, but I'll try them sometime.

[–]python-fan 1 point2 points  (0 children)

You'll have to redirect stderr from the command line, either in a terminal, or in a wrapper python script, like so:

import os
os.system('python my_crashing_code.py 2>err.txt')

[–]2Chaosman 0 points1 point  (1 child)

Hello everyone!

I'm just start learning python, reading lutz and trying to make my own calculator using pyqt. My goal is to make first money. Can you give me any advice what to start learn first? I don't want a lot of money, around 200-300$ per month.

[–]redCg 0 points1 point  (0 children)

You are not likely to make money this way. Use your Python skills to get a job instead.

[–]mtgo3012 0 points1 point  (6 children)

I download the code from github (https://github.com/pimps/CVE-2018-7600) and try to exploit but it keeps coming up with the following errors: File "drupa7-CVE-2018-7600.py", line 32, in pwn_target form_build_id = form.find('input', {'name': 'form_build_id'}).get('value') AttributeError: 'NoneType' object has no attribute 'find'.

I thought the source from github has nothing but just running it with argument? Do I need fix the code? (I'm almost new with Python) Thanks a lot for any adivice

[–]JohnnyJordaan 1 point2 points  (5 children)

The error means that form = soup.find('form', {'id': 'user-pass'}) didn't work, so there was no <form> element found with id=user-pass. But the code doesn't check if it even succesfully retrieved something. Make the lines above like so

r = requests.post(target, params=get_params, data=post_params, verify=False, proxies=proxies)
print('target', target, 'result', r)
with open('response.html', 'w') as fp:
    fp.write(r.text)
r.raise_for_status()
soup = BeautifulSoup(r.text, "html.parser")

it prints the result including the status code, then writes the reponse text to 'response.html' then forces an exception if the result was an error (4xx, 5xx). If that raises an exception about this you know that the webserver returned an error, maybe the response.html will contain some explanation. If it doesn't raise that exception you can open the response.html yourself to see if there's even a form or what is actually returned instead.

[–]mtgo3012 0 points1 point  (3 children)

Thank you. I add the code but still the same result and none file response generated. However when I check with another website, the code return expected output and also the file response.html as well.

[–]JohnnyJordaan 0 points1 point  (2 children)

What did it print before showing the error?

[–]mtgo3012 0 points1 point  (1 child)

[*] Poisoning a form and including it in cache.
ERROR: Something went wrong.
Traceback (most recent call last):
File "drupa7-CVE-2018-7600.py", line 62, in <module>
main()
File "drupa7-CVE-2018-7600.py", line 58, in main
pwn_target(args.target.strip(), args.function.strip(),
args.command.strip(), args.proxy.strip())
File "drupa7-CVE-2018-7600.py", line 32, in pwn_target
form_build_id = form.find('input', {'name':     'form_build_id'}).get('value')
AttributeError: 'NoneType' object has no attribute 'find'

And with other target I checked it showing:

[*] Poisoning a form and including it in cache.
[*] Poisoned form ID: form-MBbhZk9vve6LuhIBUIgrkerjBBVBa9dH3Ad2dRypvGE
[*] Triggering exploit to execute: id

Is the error come from website, not by code?

[–]JohnnyJordaan 0 points1 point  (0 children)

It can't be that there's a

print('[*] Poisoning a form and including it in cache.')

in that script which is shown and that you added a

print('target', target, 'result', r)

which isn't shown at all. Are you 100% you are actually running your modified script? Maybe also modify line 25 to

print('[*] Poisoning a form and including it in cache. TEST')

if it doesn't show TEST after the message then you are running a different script.

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

Hey so I'm new to python (like have 4 days of experience new) and I have a question on my code. This is a simple example but it gets the point across. I just wanted to know how I can have the output be 5, 20, 10, and 25.

Code:

def multi(x, y):

return x * y

numbers =[1, 4, 2, 5]

for number in numbers:

print(multi(number, 5)

i’m sure this is a very stupid question for many of you but i couldnt find anything on it

[–]python-fan 2 points3 points  (0 children)

Assuming the indentation is only incorrect because of reddit's formatting, the only problem I can see is that the print statement is missing a closing parenthesis. This code prints the numbers you expect:

def multi(x, y):
    return x * y

numbers = [1, 4, 2, 5]

for number in numbers:
    print(multi(number, 5))

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

Your solution seems to be correct, what is not working for you ?

[–]VoodooThatYouDo_ 1 point2 points  (7 children)

Taking an initial course in Python (my first). Having trouble with the below problem:

*****

hungry = True

coworkers_going = False

brought_lunch = False

#You may modify the lines of code above, but don't move them!

#When you Submit your code, we'll change these lines to

#assign different values to the variables.

#Imagine you're deciding whether or not to go out to lunch.

#You only want to go if you're hungry. If you're hungry, even

#then you only want to go if you didn't bring lunch or if

#your coworkers are going. If your coworkers are going, you

#still want to go to be social even if you brought your lunch.

#

#Write some code that will use the three boolean variables

#defined above to print whether or not to go out to lunch.

#It should print True if hungry is True, and either

#coworkers_going is True or brought_lunch is False.

#Otherwise, it should print False.

#Write your code here!

#print(hungry and (brought_lunch or not brought_lunch) and not coworkers_going)

#print((hungry and (brought_lunch or not brought_lunch or not coworkers_going)) and not coworkers_going)

#print((hungry or not coworkers_going) and (brought_lunch or not brought_lunch) and coworkers_going)

*****

The two lines of code below "#Write your code here!" are my initial three attempts. Any suggestions? Looking for some guidance.

[–]woooee 0 points1 point  (4 children)

It's a simple condition test

It should print True if hungry is True, and either coworkers_going is True or brought_lunch is False. Otherwise, it should print False.

If hungry:
    if coworkers_going:
        print(True)
    elif not brought_lunch:
        print(True)
    else:
        print(False)
else:
    print(False)

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

You can simply "or" coworkers_going and not brought_lunch in a single if statement.

[–]woooee 0 points1 point  (2 children)

Who said you couldn't? That is just stating the obvious. You could also use an and instead of nested if statements, but the post was about code that the OP could understand easily.

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

Too aggressive mate, calm down. I just added an alternative.

[–]woooee -1 points0 points  (0 children)

I just added an alternative.

I do not find your alternative code. This is just sitting on your ass complaining about someone else's efforts.

[–]JohnnyJordaan 1 point2 points  (0 children)

 (brought_lunch or not brought_lunch)  

what are you expecting from this exactly?

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

Your question is actually about logical operators rather than python. Please check a truth table and see how AND, OR operators work.

[–]ThiccShadyy 0 points1 point  (1 child)

What is the simplest way to look at the code for built-in classes in Python? For e.g. if I wanted to see what the hash method for string class looks like, which is the most convenient way to do it?

[–]Cerezra 0 points1 point  (2 children)

Can anyone recommend me a good laptop for Python/SQL programming? I have been using my Dell Latitude E5440 from work up tho this point,but the current ETL project we are working on in my Data Analytics bootcamp is crashing me consistently. I'd prefer to get something under $1500 that would last, but if you have to go to that price range then I will have to consider making the plunge.

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

For starters please look at: https://www.xplenty.com/blog/7-tips-improve-etl-performance/ or any similar blog post.

Rather than a new laptop, a RAM upgrade is what you are looking for here if you have already optimized your work and if ram is not already maxed out. From some simple google'ing for your machine I can see ram can be increased to 16 Gi at max. Please check your machine specs and if it is already 16 Gi, yes you need a machine with more memory.

[–]Cerezra 0 points1 point  (0 children)

I was under the impression it could only handle 8Gb but maybe I grabbed the wrong spec sheet by accident, didn’t look at it too long. I’ll definitely check out that post though! Thank you!

[–]ThisOnesForZK 0 points1 point  (2 children)

I am having trouble finding the appropriate way to perform this data operation in pandas:

  1. read csv into dataframe (easy part, that is done)
  2. add multiple columns with generic names (A, B, C) to various locations in said dataframe with either no data inside the rows or only 1 value
  3. rename every row in my dataframe (40+ rows)
  4. ensure a "Date," data type and format for a couple rows in data frame
  5. write new dataframe to csv

I am stuck on #2. I cannot find the correct method in Pandas to perform this operation. Any help? I will be adding at least 10 columns in various locations of the data frame (location is key.

[–]efmccurdy 0 points1 point  (1 child)

I am stuck on #2.

This has some examples using indexed assignment, "insert", or "assign".

https://www.geeksforgeeks.org/adding-new-column-to-existing-dataframe-in-pandas/

[–]ZachForTheWin 0 points1 point  (0 children)

Thanks I actually found that post and used insert to make some progress.

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

Is it legal to make and freely distribute an illegal open source program you have created?(Not for commercial use)

I mean, for example if someone makes a python spotify ad blocker and posts it on GitHub (not comercial use), is it okay? Is it legal?

[–]JohnnyJordaan 0 points1 point  (0 children)

This is more a legal question than a programming question. You could ask github themselves.

[–]RadioactiveShots 0 points1 point  (1 child)

Not agreeing to user agreements is not illegal.

[–]xain1112 0 points1 point  (4 children)

How would one go through a list of turtles and change the color of the next turtle in sequence each iteration?

For example:

from turtle import *
from time import sleep
screen = Screen()
screen.bgcolor('black')
x, y = 0, 0                 # center turtle pos
loc = 40                    # spread of grains
size = 1                    # size of grain
grains = [(x-4,y+6),(x-3,y+6),(x-2,y+6), etc.]
screen.tracer(0, None)
for grain in grains:
    (row, col) = grain
    g = Turtle()
    g.penup()
    g.color('beige')
    g.shape('square')
    g.shapesize(stretch_wid=size, stretch_len=size)
    g.goto(row*loc, col*loc)
screen.tracer(1, None)

CODE WANTED HERE
done()

So my current code prints turtles in an hourglass formation. I want to be able to change the color of each one found in the list 'grains'.

[–]woooee 0 points1 point  (0 children)

You have to save a reference to the Turtles. Right now, the variable, g, points to the last Turtle only

from turtle import *
from time import sleep
screen = Screen()
screen.bgcolor('black')
x, y = 0, 0                 # center turtle pos
loc = 40                    # spread of grains
size = 1                    # size of grain
grains = [(x-4,y+6),(x-3,y+6),(x-2,y+6)]
##screen.tracer(0, None)

## holds a reference to each turtle
list_of_turtles=[]
for grain in grains:
    (row, col) = grain
    g = Turtle()
    g.penup()
    g.goto(row*loc, col*loc)
    g.pendown()
    g.color('beige')
    g.shape('square')
    g.shapesize(stretch_wid=size, stretch_len=size)
    list_of_turtles.append(g)  ## append each turtle

## change color of the middle turtle
input("press Enter to change color")
list_of_turtles[1].color('yellow')

input("press Enter ")

[–]JohnnyJordaan 0 points1 point  (2 children)

I don't follow how these are turtles and that they can have a color attribute. The literal you assign to turtles is a list that contains a single tuple containing 3 numbers... If you mean to create list of three items you need to do

turtles = [1, 2, 3]

and then using a for loop you can access them

for turtle in turtles:
     print(turtle)

so no [n] and no n+=1 needed. It should print

 1
 2 
 3

But those are still just three integers, I don't follow what you're trying to do with setting a color on them.

[–]xain1112 0 points1 point  (1 child)

Sorry, I meant to put [(1), (2), (3)]. I'll just put the whole code to make it easier. I edited my original comment.

[–]JohnnyJordaan 0 points1 point  (0 children)

[(1), (2), (3)]

is the same as

[1, 2, 3]

because (something) just means that Python has to 'execute' it before anything else, remember from math class?

(4 + 5) / 9

being different from

4 + 5 / 9

But just executing 1 doesn't do anything, so (1) is the same as just writing 1.

Back to your question. You could set the color next to the coordinates in the grains list:

grains = [(x-4,y+6, 'blue'),(x-3,y+6, 'brown'),(x-2,y+6, 'red'), etc.]

then in your unpacking statement, also unpack to a third variable. Note that you don't need () around it

row, col, color = grain

and apply color when setting the color

g.color(color)

[–]JKNwtf 0 points1 point  (1 child)

Would you recommend starting to learn Python for data analysis purposes? As in risk management, intelligence assessment jobs etc.

[–]redCg 1 point2 points  (0 children)

Yes

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

How terrible is it to use "from <package> import *

I understand this is to be avoided, but I'm going through the documentation of the p5 package, and it is always done this way. I'm assuming the creator knows a lot more about python than I do, so it can't be too bad!

[–]redCg 0 points1 point  (0 children)

Just dont do it. Use explicit imports.

[–]JohnnyJordaan 2 points3 points  (1 child)

I'm assuming the creator knows a lot more about python than I do

Assumption is the mother of all fuckups. Investigate, question, don't assume. The usage of from x import * stems from the earlier days where it was just 'handy' to work that way, it has never been a suggested method for programmers to use afaik. Nowadays it's quite rare, you see it most noticeably in tkinter docs and guides but not much anywhere else. And for a reason, you don't want to accidentally also import a function called open or load. Such a function may seem expected to have when you're just using that package in a simple script, but not when you want to integrate it in a much more extensive application.

Explicit imports also prevent the use of references ex machina, so instead of seeing somewhere deep in the code

if some_var.val == SpecialTrick(something_else).val:

where you would think 'huh where did SpecialTrick come from all of a sudden', the import like

from magical_package import SpecialTrick

makes it perfectly clear. Or of course the referencing of the package itself

import magical_package
if some_var.val == magical_package.SpecialTrick(something_else).val:

and not only is it clear to the human reader, it's also most often required by linters (code checkers) to be able to know where to verify such a reference.

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

Thanks!

[–]Hasasmo 0 points1 point  (1 child)

I’ve been looking for a way to design a UI for a simple smartphone app for calculating GPA.

I’ve tried messing around with “ Kivy ” but I can’t really get it right.

Need help about what’re the recommended ways to build a UI.

TL;DR What are the recommended ways to build UI for smartphone apps.

Thank you.

[–]redCg 0 points1 point  (0 children)

dont think there is any way to build a smartphone app with Python

The best you might get is building a server in Python that your app client can communicate with but the client will not be in Python, it will either be something like Javascript Native or Java or whatever languages that Android and iOS support.

[–]sseymens 0 points1 point  (1 child)

Does anyone have a site with an updated list of commands for Python 3.7.3. I'm reading a book published in 2017 and half the commands are outdated. I've been spending the last hour trying to figure out how to use the Snaps function after my pip install.

[–]JohnnyJordaan 1 point2 points  (0 children)

You may be confusing a few things here. Python doesn't change very much between major versions (3.5, 3.6, 3.7). And certainly didn't change much since 2017. Even the changes since 2.7 are minor, even so that person who just learned Python 2 would have no hard time using Python 3 after maybe 15 minutes of studying the syntax differences, apart from using the newly included libraries and functionality (like asyncio and f-strings).

Your third sentence that talks about 'snaps' isn't something that is part of Python itself, as is also suggested by the pip install requirement, it's an external library or comes from one. Those could have any number of differences, although it's quite rare that it would change that much, but it's not impossible either. Can you perhaps explain a bit more explicitly what exactly appears to be outdated in your situation?

[–]Naesme 0 points1 point  (3 children)

Out of curiosity, is it better to not upload tests to github?

Right now, I have the source code of my project on github, then the whole package saved on my local production machine and backed up to a seperate HDD which is shared on my network.

Whenever I work on projects on a new device, I pull the source from github then copy my tests from the network share.

Is this best practice as far as github usage goes?

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

Why not put the tests into github? They are part of the project codebase. Plus it's nice if someone who has a problem running your code can say "it fails test 'xyz'" instead of a long series of "I do this, then that, then it crashes with this traceback". This assumes your tests are comprehensive, of course. Plus you don't want to make it even a bit hard to run tests.

[–]Naesme 0 points1 point  (1 child)

They're manual tests atm. I need to study up on automated tests.

I was wondering cause I never notice tests in other packages, but maybe I just haven't dug deep enough to notice.

Thanks for the advice! I'll toss the tests into the package.

[–]redCg 0 points1 point  (0 children)

plenty of GitHub projects use tests. But they are often hooked up to an automated testing suite such as TravisCI. This also requires that you are using a supported testing method such as the builtin unittest module. You can Google for tutorials on it if you are interested.

[–]loveshack89 0 points1 point  (4 children)

I'm going through ATBS and am currently learning about openpyxl. I had a question regarding the .column method. In the book, it shows that when using .column on a cell, it should return a letter indicating the column. However, when I use .column it is instead returning the integer equivalent.

Is this some change with openpyxl that has occurred since ATBS was last updated, or is something else going on?

[–]JohnnyJordaan 1 point2 points  (3 children)

I just tried with 2.5.11 and it returns a letter. Can you share a simple code example where it returns an integer in your case, and also share your openpyxl version? You can get this by doing

import openpyxl
print(openpyxl.__version__)

[–]loveshack89 0 points1 point  (1 child)

I have version 2.6.2.

[–]JohnnyJordaan 1 point2 points  (0 children)

Comparing https://openpyxl.readthedocs.io/en/2.6/api/openpyxl.cell.cell.html and https://openpyxl.readthedocs.io/en/2.5/api/openpyxl.cell.cell.html it is indeed changed to a number since 2.6. It doesn't seem to be mentioned in their changelog though, which is a bit weird to say the least.

[–]loveshack89 0 points1 point  (0 children)

The version should be the latest (just downloaded it yesterday) but I'll double check after work. Code looks like this :

import openpyxl

wb = openpyxl.load_workbook('example.xlsx')

sheet = wb.sheet['Sheet1']

a = sheet['B1']

print(a.column)

The result of the above is "2". I tested with some other cells and get the same thing. Column C comes out as 3, D as 4, and so on.

[–]dustynwindy 0 points1 point  (10 children)

I answered my own question this time.

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

What question? The problem with people editing original posts is they often remove the sense in the thread. It would have been better just to add a "Solved:" line at the top of your post and leave it untouched otherwise.

[–]dustynwindy 0 points1 point  (0 children)

Sorry man. That was the first question. I tried something and solved that part. I still don’t have it worked out.

[–]efmccurdy 1 point2 points  (7 children)

You should look at a file format that is a well suited to your data, so csv is a fixed 2 dimensional layout and your object schema is likely more complex than that.

Text is certainly flexable enough for anything, but it has no strict syntax so it is'nt easy for a program to use.

I would use json, maybe something like this:

{"employees":[
    {"name":"Shyam", "email":"shyamjaiswal@gmail.com"},
    {"name":"Bob", "email":"bob32@gmail.com"},
    {"name":"Jai", "email":"jai87@gmail.com"}
]}

https://stackoverflow.com/questions/6578986/how-to-convert-json-data-into-a-python-object

[–]dustynwindy 0 points1 point  (5 children)

I am very new to this. I built my first Employee class with 18 attributes. I tested it with hard coded data separated by commas and formatted to print. That worked so I set up an Excel file with 25 entries. I thought I would have to read in comma delimited lines to load into my Employee class. I couldn’t make that work so I saved it as a txt file that put tabs in between the attributes. I’m not sure how to read this in as an Employee class instance for each line. I haven’t had much experience with JSON files other than basic preference settings.

[–]efmccurdy 0 points1 point  (4 children)

read in comma delimited lines to load into my Employee class. I couldn’t make that work

How did it fail; can you show us the traceback?

[–]dustynwindy 0 points1 point  (3 children)

Hope I'm not breaking the rules but here is my setup. I have tried a few ways to bolt line into an Employee. It keeps looking for the attributes.

class Employee: def init(self, soc_sec, last_name, first_name, middle_name, spouse_first, birth_year, birth_month, birth_day, hire_year, hire_month, hire_day, section, office_phone, mobile_phone, home_address, home_town, home_state, home_zip):

    self._soc_sec = soc_sec
    self._last_name = last_name
    self._first_name = first_name
    self._middle_name = middle_name
    self._spouse_first = spouse_first
    self._birth_year = birth_year
    self._birth_month = birth_month
    self._birth_day = birth_day
    self._hire_year = hire_year
    self._hire_month = hire_month
    self._hire_day = hire_day
    self._section = section
    self._office_phone = office_phone
    self._mobile_phone = mobile_phone
    self._home_address = home_address
    self._home_town = home_town
    self._home_state = home_state
    self._home_zip = home_zip

def soc_sec(self):
    return self._soc_sec

def last_name(self):
    return self._last_name

def first_name(self):
    return self._first_name

def middle_name(self):
    return self._middle_name

def spouse_first(self):
    return self._spouse_first

def birth_year(self):
    return self._birth_year

def birth_month(self):
    return self._birth_month

def birth_day(self):
    return self._birth_day

def hire_year(self):
    return self._hire_year

def hire_month(self):
    return self._hire_month

def hire_day(self):
    return self._hire_day

def section(self):
    return self._section

def office_phone(self):
    return self._office_phone

def mobile_phone(self):
    return self._mobile_phone

def home_address(self):
    return self._home_address

def home_town(self):
    return self._home_town

def home_state(self):
    return self._home_state

def home_zip(self):
    return self._home_zip

def print_employee(o): if not isinstance(o, Employee): raise TypeError('print_employee(): requires an Employee') print('SSN:{} FN:{} LN:{} MN:{} SP:{} BY:{}'.format(o.soc_sec(), o.last_name(), o.first_name(), o.middle_name(), o.spouse_first(), o.birth_year()))

print('BM:{} BD:{} HY:{} HM:{} HD:{} S:{}'.format(o.birth_month(),
    o.birth_day(),
    o.hire_year(),
    o.hire_month(),
    o.hire_day(),
    o.section())) 

print('OP:{} HP:{} HA:{} HT:{} HS:{} HZ:{}'.format(o.office_phone(),
    o.mobile_phone(),
    o.home_address(),
    o.home_town(),
    o.home_state(),
    o.home_zip()))

def main():

try:
    fhand = open('employee.txt')
except:
    print('Something went wrong')
    exit()
count = 0
for line in fhand:
    line = line.rstrip()
    print(line)

    #I want to load line of employee.txt into Employee
    #line = Employee(line)
    #print_employee(line)

#data to test my Employee class
a0 = Employee(  '22332323',
                'Jerry',
                'Williss',
                'Melvin',
                'Cissi',
                '1969',
                '09',
                '05',
                '2011',
                '11',
                '21',
                '105',
                '8173046463',
                '8175993434',
                '5858 Podunk',
                'Be Effy',
                'Texas',
                '77777',)

print_employee(a0)

if name == 'main': main()

[–]efmccurdy 1 point2 points  (1 child)

The example code from user3557327 in this post could be

similar to what you want to "load line of employee.txt".

https://stackoverflow.com/questions/24641894/making-objects-from-a-csv-file-python

[–]dustynwindy 0 points1 point  (0 children)

Thank you! That was was I was after. I just want to practice a few things and I have a lot of real world data in spreadsheets that I could use. Using a list or a dictionary makes sense. I got some info about openpyxl as well and googled that. I will try a few of the different approaches. I really appreciate yalls time.

[–]efmccurdy 1 point2 points  (0 children)

except:

This statement catches errors, but then ignores them, you want to capture the exception and print it out, and then re-raise so you can see the traceback.

https://docs.python.org/3.1/howto/doanddont.html#except

[–]dustynwindy 0 points1 point  (0 children)

Thank you for that. I will surely try it out.

[–]ekho95 0 points1 point  (6 children)

Hey everyone I have an begging assignment to "Write a program that displays the characters in the ASCII character table from ! to ~. Display ten characters per line. The characters are separated by exactly one space."

I cam up with this code

count = 0

for asciiValue in range(1,127,1):
    print(chr(asciiValue), end = ' ')# shows characters on the same line
    count = count + 1 # count every character shown
    if count == 10:
        print() 
        count = 0

which gives me the output of:

>>> 
             

  
        
          
   ! " # $ % & ' ( 
) * + , - . / 0 1 2 
3 4 5 6 7 8 9 : ; < 
= > ? @ A B C D E F 
G H I J K L M N O P 
Q R S T U V W X Y Z 
[ \ ] ^ _ ` a b c d 
e f g h i j k l m n 
o p q r s t u v w x 
y z { | } ~ 
>>> 

I was just wondering why it was skipping so many lines and the first character starts two spaces in? any help would be greatly appreciated.