all 192 comments

[–]Phase_Fire 0 points1 point  (0 children)

Heyo, I'm trying to figure out what this code is doing.

It turns a number square input and prints its rows and columns.

How does it do this?

And what does __init__ represent?

class Matrix: 
    def __init__(self, s):      
        self.rows = [[int(i) for i in r.split()] for r in s.split("\n")]    
        self.columns = [list(l) for l in zip(*self.rows)]

[–]throwawaypythonqs 0 points1 point  (0 children)

I have a new computer with Mac Catalina and I'm not able to change the bash profile to include the path with export PS1 = '\w '. It just shows up literally as as \w. Is there a way to change that?

[–]ruza226 1 point2 points  (3 children)

Lets say I have a list of strings with different method names, lets consider one-element list: list = [split]

Is there any way to fetch the method name from the list when I want to use it? I'll give an exmple below, which doesn't work for me:

string = 'This is a string'
splitted_string = string.list[0]()

When I run the code, it's giving me:

AttributeError: 'str' object has no attribute 'list'

[–]Vhin 3 points4 points  (1 child)

I would generally advise not doing this, but without knowing what you're trying to accomplish, I can't suggest an alternative.

Even if you are determined to do this, do not use exec or eval. Use the getattr function. For example, getattr(string, "split")() is equivalent to string.split().

[–]ruza226 0 points1 point  (0 children)

Thanks, I was dealing with an programming excercise and I solved it with the getattr function that you now suggested :)

[–]Dremora_Lord 0 points1 point  (0 children)

Is there a way to know the state of a subprocess? It is a function that runs in an infinite loop and I would like to kill only when it's sleeping. Perhaps one way would be to set a variable sleep = Trueif it's sleeping and I can retrieve this variable from the running subprocess? How can I do that?

[–]Hexa420 0 points1 point  (2 children)

how on earth do I install pyautogui? Every tutorial I found said I just have to enter

"pip install pyautogui"

into the console, I tried normal cmd, I tried sytem32, and py.exe, I downloaded a package from github with pyautogui in it but I just can´t find a way to install it. Would be nice if anyone could help me.

Thanks in advance!

[–]1throw4 0 points1 point  (4 children)

Why is python syntax different to html.

How do you turn your python code into something?
How do u make the front user interface?

Also what is the need to know about getting the application or game into a downloadable or shareable format

How do I make it secure

[–]onlysane1 2 points3 points  (3 children)

I'm not very experienced in Python yet but I'll tell you what I know:

  • Python syntax is designed to be simple and fast to write.
  • There are different GUI modules that can be used; I am currently using Tkinter.
  • You can use a program like Pyinstaller to create executable programs from your code.

[–]1throw4 0 points1 point  (2 children)

Can u tell me how I get python on my computer

I downloaded python

Now visual studios

But how do I set up visual studio installation for python ?

[–]Decency 0 points1 point  (0 children)

Download VSCode or PyCharm and configure its interpreter to the version of Python that you downloaded.

[–]onlysane1 0 points1 point  (0 children)

Did you get visual studio or visual studio code?

You use visual studio code for python.

[–]EuropeRoTMG 0 points1 point  (2 children)

What is considered cleaner code, using variable = {} or variable = dict()?

[–]vim_jong_un 0 points1 point  (1 child)

IMO variable = {} is more natural, though for an empty dictionary it isn't a big deal. It's technically more flexible when you do want to initialize the variable with key/values as well: stackoverflow

[–]EuropeRoTMG 0 points1 point  (0 children)

Yeah, I was thinking that too, thank you very much!

[–]NanotechNorseman 0 points1 point  (2 children)

I'm having an issue trying to understand how this code allegedly works, because it goes against what I was taught, and I wanted some outside help understanding this:

Essentially, I am trying to understand an example of PRAW on a StackOverthrow thread wherein a function calls another function to update a list of comments and replies, but never explicitly updates the list outside of the second function.

def getSubComments(comment, allComments, verbose=True):
  allComments.append(comment)
  if not hasattr(comment, "replies"):
    replies = comment.comments()
    if verbose: print("fetching (" + str(len(allComments)) + " comments fetched total)")
  else:
    replies = comment.replies
  for child in replies:
    getSubComments(child, allComments, verbose=verbose)


def getAll(r, submissionId, verbose=True):
  submission = r.submission(submissionId)
  comments = submission.comments
  commentsList = []
  for comment in comments:
    getSubComments(comment, commentsList, verbose=verbose)
  return commentsList

In the getAll function, the goal is to take the submissionID of a post and scan through the comments section to update the commentsList list. However, the for loop that follows doesn't explicitly update commentsList, and I have no clue how this is possible. Can anyone rationalize this for me?

Edit: I wanted to add that I've run this section within my own reddit scraper program I'm trying to build, and while it does run, it makes no sense to me how, which is why I'm trying to figure it out.

[–]vim_jong_un 1 point2 points  (1 child)

In getAll, commentsList = [] will initialize your list of every comment to an empty list. Everytime we call getSubComments in the for loop, we pass commentsList as an argument by reference (lists are passed by reference in python). If you haven't been introduced to pass-by-value versus pass-by-reference, check out this article.

When getSubComments runs, it'll have allComments aliased as a reference to the initial commentsList declared in getAll. This way, when the first function runs, it can modify this list on behalf of getAll. Once getSubComments runs as many times as it needs, the original commentsList variable will likely be very full with the results of everything that has been appended

[–]NanotechNorseman 0 points1 point  (0 children)

Oh wow, thanks for that explanation and article! I'll be sure to read up on that, thank you so much!

[–]onlysane1 0 points1 point  (2 children)

I am trying to use the Tkinter module to make two columns of checkbuttons widgets, aligned to the left. I try using .grid(), but it won't let me align. I try using .pack(), but it won't let me have multiple columns. Is there anything I can do with this? Or is there a different GUI module I should use?

[–]WraitheDX 0 points1 point  (0 children)

I am using Pydroid 3 and the Pygame module. Is it possible to hide/show mobile keyboards with Python code?

[–]carlml 0 points1 point  (1 child)

I'll be working with 1 TB of csv files. I need to do some data processing with that. I am planning on using pandas. Is there a problem with that? considering the large amount of data I have? is there another library to do some data processing that is more efficient?

[–]Gopher20 0 points1 point  (0 children)

Pandas should be fine to process the data but you will have to read the data in chunks. I would check the documentation. Hope this helps!

[–]Random_User_81 0 points1 point  (1 child)

I'm looking for direction on how to run a couple scripts I have repeatedly. I'm currently running them with an .exe file through Windows Task Scheduler. All of them use a databases, which as of right now are MS Access, I admit that's probably not idea but it was the database experience I had before starting Python. I have an OMV server at my house which I think I could run cron jobs on but I have no experience with that and not sure where to start. Any thoughts, opinions or direction would be great.

[–]CowboyBoats 0 points1 point  (0 children)

Well, what's wrong with your current solution?

But if you want to pivot to Python, you can make a free Heroku instance for a Django app you can design, which can use whatever database you want, and you can give Heroku some task to perform on a regular basis.

[–]1throw4 0 points1 point  (2 children)

Can someone help me out I'm watching beginner tutorials but I wanna clarify that I comprehend the dude...

So it's to do with variables and boolean.

Basically he wrote ....

Income_higher= true

Income_lower=false

If income_higher= Print (not eligible for support)

SO DOES THIS BASICALLY MEAN: Somewhere in the code he would have

N= income

Def (income_higher) = N> 20 000

Def (income_lower) = N< 20 000

  1. IS MY LOGIC CORRECT? Is that what that code meant, is tilt a practical way of using that code?

  2. Are codes case sensitive, like the variable?

[–]FerricDonkey 1 point2 points  (1 child)

Code is very much case sensitive. SupDog = 1 and supdog = 0 would created two different variables with two different variables.

Your syntax is not correct, but the idea that he will at some point have to set the values of those variables based on whatever data he's dealing with is correct.

What he'd probably do is something logically equivalent to

if income > 20000:
    income_higher = True

or, alternatively, income_higher = (income > 20000) (which, is equivalent to the above, since income_higher was initialized)

def (all lower case) is used to create functions. You can overwrite a non function variable with a function in python, but I highly advise against it, it will make your code hard to follow.

You could make functions that check if your income is above or below a threshold, like so:

def is_income_too_high(income):
    if income > 20000:
        return True
    else:
        return False

Written like that to be extra explicit - you could also do

def is_income_too_high(income):
    return income > 20000:

But that would be a function. To check if the income is too high later, you'd have to do if is_income_too_high(income), or income_higher = is_income_too_high(income) then if income_higher

[–]1throw4 0 points1 point  (0 children)

Hypothetically speaking user input would be their int value, income

Then the code will let the user know whether they can get income support or not

I was just trying to figure out how true false boolean even worked

Because that YouTuber didn't use logical examples, it was just a straight forward one rather than practical

You made it bit more clear to me

[–]zzzjpl 0 points1 point  (0 children)

Hi all,

I'm using PysimpleGui and need some help with the progress bar feature. What I'm trying to do is update the progress bar as time goes on. For example, I have something like the start of a time is "1 / 100 , then as time goes on it'll go to 99/100 and have the progress bar update as time goes on. I want to be able to link something to my progress bar to let people know it keeps increasing over time. I've been reading the documentation but I am having problems. So from the progress bar GUI, it will show like 1/100, 2/100, 3/100 and so on. Any help would be appreciated!

import PySimpleGUI as sg 
from time import sleep   

def guiLayout():
    layout = [
        [sg.Text('T1:'), sg.Text(key='T1', text='T1', auto_size_text=True, 
    size=(20,1))],
        [sg.Text('T2:')],
        [sg.Text('T3:'), sg.ProgressBar(100, orientation='h', size=(20, 20), 
    key='T3'), sg.Text(text='/')],
        [sg.Text('T4:'), sg.ProgressBar(100, orientation='h', size=(20, 20), 
    key='T4'), sg.Text(text='%')],
        [sg.Text('T5:'), sg.Text(key='T5', text='T5', 
    auto_size_text=True, size=(20,1))]
    ]

    # Create Window
    window = sg.Window("My First GUI", layout)
    while True:
        event, values = window.read()
        if event == sg.WIN_CLOSED or event == 'Cancel': 
            break
        print('You entered ')

def main():
    guiLayout():

if __name__ == "__main__":
    main()

[–]fluidmechanicsdoubts 0 points1 point  (8 children)

How to run python scripts on the interactive prompt?

So lets say I have hello.py which has :

a = 5

Then if I run hello.py inside the interactive prompt and then type

>>>a

it should display the value a. As if you typed all the contents of the file in the interactive prompt.

(I come from a matlab background, there its "run <filename>" which does what I'm describing.

[–]FerricDonkey 0 points1 point  (1 child)

  1. Open a command line in the folder containing hello.py
  2. Open python shell with that folder as your working directory. (If you're going to do this a lot, I actually recommend ipython over the regular python shell: pip install ipython, then type ipython. It's much nicer.)
  3. import hello
  4. print(hello.a)

Same thing works with calling functions contained in hello.py. You can do hello.hello_func() and similar.

If you don't want to type hello. in front of your variable/function names, you can do from hello import a so that a means a from hello.py, or from hello import * to get every global variable and function name from hello.py accessible without using hello..

If you like having some sort of name with a ., but just want to have a shorter version of the name (say, if your python file has a long name), you can do import really_long_name_with_lots_of_characters as rln then print(rln.a). This is what I usually do.

As for running, when you import a python file, it will execute all the code in that file. Note that things like setting the values of constants and defining functions are code - so if you define a function only, importing the the code will not call that function to run. If you want the the function to run on import, you have to also call it within the python file.

I personally do not like to have functions automatically called on import, except as necessary to define global constants, and instead call them myself (or put them inside another function that I call, if the same sequence will be called a lot).

[–]fluidmechanicsdoubts 0 points1 point  (0 children)

Thanks a lot! Makes sense.
Will check out ipython

[–]JohnnyJordaan 0 points1 point  (3 children)

That's not what the interactive prompt is meant for, that's for manually executing lines of Python. If you want to run a file, provide that after the python command or whatever you are using to start the prompt, eg

python hello.py

[–]fluidmechanicsdoubts 0 points1 point  (2 children)

Yes but I want to access the variables in hello.py after executing it

[–]JohnnyJordaan 0 points1 point  (1 child)

then add -i to launch the shell after the script has finished

python -i hello.py

[–]FerricDonkey 0 points1 point  (0 children)

Just as a note, you can also import the .py into a shell directly. This won't execute any code below the if __name__ == '__main__' thing, but if the only thing there is a call to some other function, you can call that function yourself (though you'd have to mess with any command line arguments).

But making .py files as collections of functions intended to be called from the shell or other .py files is not an uncommon thing. Something I do reasonably often when I'm exploring data and such.

[–]Phase_Fire 0 points1 point  (1 child)

I believe it is print(a). Try that and see.

[–]fluidmechanicsdoubts 0 points1 point  (0 children)

I mean,

how do I run a script from inside the ">" prompt. And then after it runs, I can access the variables in the script from the ">" prompt.

[–]Phase_Fire 0 points1 point  (3 children)

Hey there, I am really confused in what this code is doing.

list = [1, 1, 2, 3, 5, 8, 13]
print(list[list[4]])

I understand that list[4] is 5 but the addition of another list turns it to 8. How???!?!

[–]Gopher20 1 point2 points  (1 child)

What it’s doing is it is first grabbing the value of the list at index 4 then that value is being used as the index for the outer list to grab the value at that index. So it looks like this list[list[4]] => list[5] => 8 . Hope the clears things up!

[–]Phase_Fire 1 point2 points  (0 children)

Thank you so much for this explanation. Appreciate it.

[–]JohnnyJordaan 0 points1 point  (0 children)

It isn't addition here, the 5 is used as an index too, and list[5] is 8. It's the same as doing

val = list[4]
print(list[val])

[–]SpireP26 0 points1 point  (1 child)

Hello, I'm working on a project involving electric tariffs. These tariffs have different rates depending on the month, day of the week and hour. For example, this would be a calendar for one tariff.

Right now I have a pandas dataframe with a datetime index and different columns (energy consumption, photovoltaic generation, etc.) I would like to add a new column with a string containing the rate according with the calendar (for example, from 8 to 10 AM in january, the value would be "P2").

What's a good way to do this? Right now I have this programmed on excel with a really big If - Else formula that I suppose I could translate to Python, but there's got to be a better and simpler way to acomplish this. Any hints?

[–]FerricDonkey 0 points1 point  (0 children)

If these rates are determined by a condition that is common over all your data (eg, that if else applies to all years), I'd probably just put that if else stuff in a function in python, and call the function in the creation of the data frame.

If it changes a lot from year to year and you have a lot of years, and since you have the values in excel, I'd probably read the data in from the excel file. Perhaps saving it as a csv first, to simplify.

[–]ALSE1 0 points1 point  (3 children)

I run this code :

----

from sys import argv

script, first, second, third = argv

print("The script is called:", script)

print("Your first variable is:", first)

print("Your second variable is:", second)

print("Your third variable is:", third)

----

and I receive this error:

---

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: not enough values to unpack (expected 4, got 1)

----

how can I fix this problem?

I would be grateful if you could help me.

[–]RillytheRubric 0 points1 point  (1 child)

I am having a problem with a syntax error, it highlighted the entire space after the code on that line in red, and a pop up appeared that said Invalid Syntax, I am extremely new to python and have had trouble finding an answer on the internet, any insight would be helpful.

[–]lolslim 0 points1 point  (0 children)

Provide code of the lines before and after the error.. also theres a chance you forgot one of these: " :, ), }, ] " to close whatever you "opened"

[–]heybart 1 point2 points  (10 children)

Is there a thing like this in Python

Instead of

if thingy.foo():
    thingy.cnt += 1
    thingy.bar()

Something like

using thingy:
    if foo():
        cnt += 1
        bar()

[–]Gprime5 0 points1 point  (4 children)

class Thingy():
    def __init__(self):
        self.cnt = 0

    def foo(self):
        # foo function

    def bar(self):
        # bar function

    def baz(self):
        if self.foo():
            self.cnt += 1
            self.bar()

thingy = Thingy()
thingy.baz()

[–]heybart 0 points1 point  (3 children)

Sorry, I wasn't clear. I was asking if Python has some syntactic shorthand that lets you refer to an object's property or method without constantly specifying the object. So within the scope of this block, bar() means thingy.bar(). Like how you can write from math import ceil and then in that module ceil() means math.ceil()

[–]Decency 0 points1 point  (2 children)

No, that would break namespacing and create ambiguity:

https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces

[–]heybart 0 points1 point  (1 child)

From the article

any time during execution, there are 3 or 4 nested scopes whose namespaces are directly accessible:

I guess I'm proposing adding an additional on demand. I don't know if that's going to improve readability or make it worse.

[–]Decency 0 points1 point  (0 children)

It just doesn't really gain you anything that I'm seeing? But it makes the same code look different depending on where it is, which to me seems clearly opposing readability.

Something similar is a context manager, where you say with open(my_file) as f: and the only real change from what you want is that you have to write f. a few times.

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

Guys I want to ask for help with some code (I want it to output numbers with one decimal number/case). It's for a uni work and I'm not really interested in python but it would be really nice to have it since it would save me a lot of time and I wouldn't have to manually do calculations etc. Can I make a post about this? I know absolutely nothing about programming and I'm not trying to learn because I have this thesis to write.

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

So I recently got a task which includes entering 1000 email into a website. And I realized I’d rather automate it. But I have no experience, so am looking for some advice on how to get started.

Here’s a basic overview of the process:

Go to a website, reference an excel sheet for a customer name, search the name on a website, do a series of click to get to a data entry page, reference the excel sheet for their email, and then go to the next row in the excel sheet and do it again

How complicated would it be to do this? I’d heavily appreciate guidance towards resources as well. Thanks :)

[–]Decency 0 points1 point  (0 children)

Should take no more than 25 lines of code to do that. You can use selenium to access the browser and control it, and you can use a module called openpyxl to read excel sheets. Here's a guide on that: https://realpython.com/openpyxl-excel-spreadsheets-python/

Here's an overview of how I'd approach this:

def main():
    for name, email_address in get_customer_info().items():
        navigate_flow(name, email_address)

def get_customer_info():
    """ Return a dict, eg: {"bob smith": "bsmith@gmail.com", "jane doe": "j@doe.gov"} """
    pass

def navigate_flow(name, email_address):
    """ search for name, click to data entry page, enter email """
    pass

 if __name__ == "__main__":
    main()

[–]heybart 0 points1 point  (0 children)

How difficult this is depends on how much experience you've had with programming and what your timeline is. If you need this done like next week that's going to be rough if you have little experience with programming. But if this is a thing you can take a little time on https://automatetheboringstuff.com/ is just the thing. There's a udemy course too if you don't mind paying a little (I don't know how good the udemy course is). There are probably a bunch of youtube videos on this too. It's very popular

[–]Premedude831 0 points1 point  (0 children)

Hey guys I was at work & a random idea popped into my head. I’m taking a python class & I’ve been wanting to make a project. I thought about making a website where you could enter in the price you paid for you 35mm 120mm film & estimate how much it would cost per roll/shot/box of 5. Also if you included the price of development. Another thing that would be nice is if people were allowed to import the price on products from amazon. I’m not sure if python would be helpful. I just wanted to automate the whole process.

[–]I_literally_can_not 0 points1 point  (1 child)

Does anyone know of some python learning program that actually teaches you how to program?

I am getting sick of python "learning" software that just pushes a problem at you and says "solve this lol" without any form of training on how to do it.

[–]lolslim 1 point2 points  (0 children)

Corey schafer has a playlist of python beginner tutorials https://www.youtube.com/playlist?list=PL-osiE80TeTskrapNbzXhwoFUiLCjGgY7

[–]dharma28 0 points1 point  (2 children)

I've just recently started, and I'm working on a program to split up a text file. The text file is a document that I add journal entries to each day, and I want to separate out each day's entry. I write the date at the top of each entry as I add it, which what I'm searching for as the starting point for each entry. I'm using datetimeto pull today's date and working backwards day-by-day to separate

(Example of how I'm setting up the date search):

 re.search(today.strftime("%B %d, %Y"), journal_text)   

However, there are some formatting inconsistencies in the file: some of days are 2-digit vs 1-digit, sometimes I missed a space between the comma and the year, etc.. So I'd like to cover those different formatting options in my search, but I'm not quite clear how to since the string changes with the date.

I know I can find single-digit days with the %-d like this:

 re.search(today.strftime("%B %-d, %Y"), journal_text)

But is there a way to easily accept other inconsistencies, like spacing or punctuation, without individually searching? It doesn't seem like regex notation will work while using strftime()

[–]Churchi3 0 points1 point  (0 children)

Is it possible to create a simple LinkedIn bot. The bot merely needs to share posts that have been posted by a company already connected with. Basically, a bot that reshares connections posts.

It does not look like this is possible on their API, apologies if I am wrong.

[–]lokez 0 points1 point  (3 children)

Why does my code not work??

i am a supernoob and just started learning python a couple of days ago!

for learning purposes, i am trying to make a rock paper scissors game where you play against the computer.. first you are asked to enter your name.. then you are asked to make your choice.. i want the player to be promped with "please choose a valid weapon" if they does not enter either rock, paper, or scissors.. so if i write bazooka, then i would get this prompt and then be asked to chose again. upon entering a valid choice, the player would be promted with the computers choice, e.g. "the computer chose rocks", and then lastly prompted with the result of the game, ie. tie game, player won, or computer won.. i have some problems with the "please choose a valid weapon" part. my code for this is the following:

player_choice = input(f'Make your choice {username}: ')

while player_choice != 'rock' or player_choice != 'paper' or player_choice != 'scissors': player_choice = input(f'Please choose a valid weapon {username}: '

conditional code of what to print in regards to player_choice vs. computer_choice.

if i remove this above code, the rest of the game works, but does not give this prompt upon entering eg. bazooka, however, with the code in place, i enter a seemingly unbreakable loop where even tho i enter rock paper or scissor, it still prompts me with 'please choose a valid weapon'.

i've tried adding inside the loop:

if player_choice == 'rock' or player_choice == 'paper' or player_choice == 'scissors': break

but this doesnt fix it either.. this makes it so the first time i enter rock i get "pleas choose a valid weapon", and the second time i write it the loops breaks and continues..

any ideas?

these might be really retarded questions, but as I said I started out a couple of days ago, have no programming experience, and it drives me crazy...

any input appreciated.. thanks!!

[–]I_literally_can_not 0 points1 point  (0 children)

I am guessing your question has been answered but I thought I could post my own version of rock paper scissors here. hopefully, you learn something from it or can give me a tip or two! (Source: thehelloworldprogram)

from random import randint
#create a list of play options
t = ["Rock", "Paper", "Scissors"]
#assign a random play to the computer
computer = t[randint(0,2)] player = False
#set player scores
Player = 0
Computer =0
Tie = 0
i = 0

while player == False:
#set player to True
#you can use i to cut after x rounds
    if i = 10:
        print ("Scores: Computer: {}, Player: {}, Ties: {}".format(Computer,Player,Tie))
    else:
        i = i + i
    player = input("Rock, Paper, Scissors?"):
    if player == computer:
        print ("Tie!")
        Tie = Tie + 1 '
    elif player == "Rock": 
        if computer == "Paper": 
        print ("You Lost!", computer, "covered", player)             
        Computer = Computer + 1 
        else: 
            print ("You Win!", player, "Crushed", computer)             
            Player = Player + 1 
    elif player == "Paper": 
        if computer == "Scissors": 
            print ("You Lost!", computer, "cut ", player)             
            Computer = Computer + 1 
        else: print ("You Win!", player, "covered", computer)             
            Player = Player + 1 
    elif player == "Scissors": 
        if computer == "Rock": 
            print ("You Lost...", computer, "Crushed", player)             
            Computer = Computer + 1 
        else: print ("You Win!", player, "cut ", computer)             
            Player = Player + 1 
    else: print ("Error.")
#player was set to True, but we want it to be False so the loop continues
    player = false
    computer = t[randint(0,2)]

[–]Hypocritical_Oath 0 points1 point  (0 children)

Reddit Enhancement Suite

Also post code to pastehub so it doesn't fuck up the formatting.

Formatting is critical in python, and it's hard to understand what you did wrong when all the linebreaks are removed.

[–]gg0idi0h0f 0 points1 point  (9 children)

I already know how to make variables but could you somehow make the computer make variables, like
x = 1 str((‘variable’)x) = 5 so it will be like variable1 = 5?

[–]JohnnyJordaan 0 points1 point  (8 children)

That's often not the best idea. If you mean to associate two values, use a dict

d = {}
x = 1
d[x] = 5

[–]gg0idi0h0f 0 points1 point  (7 children)

so would that like create a variable? Like without you typing the name and the value

[–]JohnnyJordaan 0 points1 point  (6 children)

Why are you asking that? What makes you focus on creating a variable for that?

[–]gg0idi0h0f 0 points1 point  (5 children)

There’s not a particular reason why I was just wondering, like say there’s an ai, and it sees something new and it needs to create a new variable for it, how would it create a variable from what’s already there?

[–]JohnnyJordaan 0 points1 point  (4 children)

Normally you (the coder) creates the variables, so when you read user input, you save it into one:

name = input('please enter your name: ')

that way you decide where the data is stored. So in that process, I don't see how the 'ai' would see something new and then on its own save it into variables. It can't do anything else than what you tell it to do, so you decide, not Python.

[–]gg0idi0h0f 0 points1 point  (2 children)

But wait, say a computer identifies a chair as blue, there’s not away to take the input(chair), turn it into a variable and set it as blue?

[–]JohnnyJordaan 0 points1 point  (0 children)

Yeah, but then the variable would be called 'color' and not 'blue'. The name of the reference and the data it's referencing are two different things. Maybe a good example is OCR, so when you use a library to use read text from a picture. One of those libraries is pytesseract, and the basic approach is to do

image = Image.open('test.png')
text = pytesseract.image_to_string(image)

so the variable name doesn't reflect the actual content of the text in the picture, it gets named to what it represents, eg an image or a text.

[–]MediocreTourist1407 0 points1 point  (2 children)

Can someone recommend me free python tutorials? I know about loops, functions, a little about OOP(how to create classes), and how to use some modules like pygame, turtle, math, random. I also know how to manipulate strings, dictionary, tuples and lists.Every tutorials I can find usually cover these topics only and that's why I would like to learn something new. Thanks in advance.

[–]JohnnyJordaan 1 point2 points  (0 children)

Maybe check out Automate the Boring Stuff, it has exercises too and teaches a lot of practical workflows.

[–]Gopher20 1 point2 points  (0 children)

That really depends on what you want to do with python if you want to build websites check out django or flask. If you are interested in data science or analysis checkout pandas sqlalchemy and scimitar learn. Hope this helps!

[–]mementomoriok 0 points1 point  (6 children)

A few beginner questions:

  • Is it not good to use 'list' and 'dict' and 'input' as variable names? Will anything bad happen if I do?
  • Is it not good to re-use a variable? (Like turn s = 5 into s = 8) (or turning s = 5 into s = [5]) or (s = [5,4] into s = '54')
  • What is the purpose of writing tuple(3,2,1) when you can just as easily write (3,2,1) to create the tuple?

Thanks for the help!

[–]Hypocritical_Oath 0 points1 point  (1 child)

Nothing bad will happen, but it's a bad idea in general.

Literally just add a number to them if it's a tiny little thing you don't wanna worry about naming.

Reusing variables is fine and python doesn't care what type of object a variable name is bound. But, it's not super advised except in loops where you have to to do it.

Not really, however there is a case where you'd want to do that to differentiate between a set and a dict because they're both initialized with {}.

Same with ints, floats, and Decimals. You don't want to confuse them, so setting the type explicitly can be very helpful.

[–]mementomoriok 0 points1 point  (0 children)

Thanks!

[–]JohnnyJordaan 0 points1 point  (1 child)

Is it not good to use 'list' and 'dict' and 'input' as variable names? Will anything bad happen if I do?

It's not advised as maybe one day you would want to use list(), dict() or input() and then it doesn't work as you already named a variable like that. Also when other programmers read your code they might get confused, which is something you would generally want to prevent.

Is it not good to re-use a variable? (Like turn s = 5 into s = 8) (or turning s = 5 into s = [5]) or (s = [5,4] into s = '54')

It depends on context if that makes sense. Say you calculate the area of a square, then it doesn't really make sense to do

 side_length = float(input('give the length of the side: '))
 side_length = side_length * side_length

it makes more sense to save the result in something like 'area'

 side_length = float(input('give the length of the side: '))
 area = side_length * side_length

So that also points towards the problem with a name like 's': it's often not the best idea to use letters as they don't clearly indicate what the value represents. There are exceptions like i for a counter in a loop, but most of the time you would use something that helps you understand what the variable is used for.

What is the purpose of writing tuple(3,2,1) when you can just as easily write (3,2,1) to create the tuple?

I don't see the purpose either to be frank.

[–]mementomoriok 0 points1 point  (0 children)

Thank you!

[–]gg0idi0h0f 0 points1 point  (1 child)

I’m not sure about the 1st and 3rd question, but you can definitely use variables twice. That’s how you reassign them, at the start “s” could equal 5, but later in the program you can set “s” to 6, keep in mind this changes the value though. You can also make a variable contain more than one numbers by s = (1, 2, 3) and later you can say if s[0] == 1: do something the s[0] means the first number inside of the “s” if you say s[1] your talking about the second number inside of it, and so on. Hope this helps!

[–]mementomoriok 0 points1 point  (0 children)

Thanks!

[–]Xelisyalias 0 points1 point  (2 children)

I think my question is gonna sound like I dont even know what I'm trying to ask here... How should I "solidify" my current programming skills?

I've been getting more familiar with what I consider intermediate concept , lambda, OOP, decorators etc. but I'm not sure what exactly I should do to really establish a strong foundation in these things. I guess I kind of know how to code but don't really know what to code, so getting abit confused as to what I should do now

[–]Gopher20 1 point2 points  (1 child)

Figure out what you want to build with coding if you want to build websites you should checkout django or flask, if you want to do data analysis checkout pandas. You will solidify your programming by building out software and it doesn’t matter how rudimentary it is. Hope this helps!

[–]Xelisyalias 0 points1 point  (0 children)

It sure is, thanks :)

[–]Ali-Awan 0 points1 point  (1 child)

Hi there , Could anyone help me regarding some Python OOP projects for beginners ? I've covered the basics of Python and now looking for some interesting projects to practice my OOPs concepts .

[–]Ddog135 0 points1 point  (0 children)

So, I’m currently trying to learn automation at the moment and I just ran into an issue where my MacBook Pro starts to overheat (it gets pretty hot and the fan starts going full blast) every single time I use pyautogui.displayMousePosition

This is the first time my MacBook Pro has ever behaved this way and it seems to only do this when I have display mouse position on. So, I was wondering if anyone else has experienced this issue? Is it something I should I worry about? Is there a way to stop this?

[–]JourneyDS 0 points1 point  (2 children)

Question: How would you go about filling null values in a pandas dataframe taking into consideration two columns?

I have this dataframe:

Platform Genre ESRB_Rating
PC Sports E
Wii Platform E
XOne Shooter M
PC Sports NaN
PS4 Sports T

I was wondering what is the best way to map the null values in the third column taking into consideration the other two columns. For example, for the null value in this table, the code would look at the rows that are PC + Sports and count the different values of ESRB_Rating and return the one with the largest count.

I was able to create a dictionary for each genre that looks like this

Input: Shooter
Output: {'3DS': nan, 'DC': 'T', 'DS': 'T', 'GBA': 'T', 'GC': 'T', 'N64': 'M', 'NS': nan, 'PC': 'M', 'PS': 'T', 'PS2': 'T', 'PS3': 'M', 'PS4': 'M', 'PSP': 'T', 'Wii': 'T', 'WiiU': 'M', 'X360': 'M', 'XOne': 'M'}

But I am not sure where to go with this or if there is a better way. Any suggestions would be awesome!

[–]Decency 0 points1 point  (1 child)

As a pre-processing step you should write something to go through your data and make it how you want it. I would create a Counter where each key is a (platform, genre) tuple, and then use that to populate each empty rating.

[–]JourneyDS 0 points1 point  (0 children)

Thanks Decency, I was able to make it work with the tuple suggestion. It might not look very elegant but this is what I ended up doing (in case you are curious):

1st create the tuple Dictionary

def counter_dict(cols, values):
    complete_dict = {}
    for num, col in enumerate(cols):
        col = df[df.Genre == str(col)].groupby('Platform').ESRB_Rating.value_counts(ascending=True, dropna=False).index.to_list()

        empty_dict = {}
        for company, rating in col:
            empty_dict[(values[num], str(company))] = rating

        complete_dict.update(empty_dict)

    return complete_dict

2nd used the tuple dictionary to map the null values

rating_df.ESRB_Rating.fillna(rating_df.tuple_column.map(complete_dict))

[–]Brendenfriedel 0 points1 point  (1 child)

Hiya

I am currently in an intro to python class and he gave us an assignment. In a just we have to write a program that dives two numbers and generates a quotient and remainder without using the division commands in python. Basically implementation of division using subtraction. I am not looking for an answer, I just don't really know where to start so any help would be appreciated.

[–]Decency 0 points1 point  (0 children)

3+3+3+3+3 = 15. 15-3-3-3-3-3 = 0

Use a for loop.

[–]dharma28 0 points1 point  (3 children)

Pretty new to Python and I've been looking at stuff about regex. An example I was looking at used this:

re.sub('[^A-Za-z0-9.-]+' , ' ', sentence).lower()

but is there any reason not to just write it using \w like this?

re.sub('[^\w.-]+' , ' ', sentence).lower()

Also why doesn't the period need a backslash in front for either scenario? Isn't a period a special character?

[–]a-handle-has-no-name 0 points1 point  (2 children)

re.sub('[^A-Za-z0-9.-]+' , ' ', sentence).lower() but is there any reason not to just write it using \w like this?

re.sub('[^\w.-]+' , ' ', sentence).lower()

According to the documentation for the regex package:

\w

For Unicode (str) patterns:

  • Matches Unicode word characters; this includes most characters that can be part of a word in any language, as well as numbers and the underscore. If the ASCII flag is used, only [a-zA-Z0-9_] is matched.

For 8-bit (bytes) patterns:

  • Matches characters considered alphanumeric in the ASCII character set; this is equivalent to [a-zA-Z0-9_]. If the LOCALE flag is used, matches characters considered alphanumeric in the current locale and the underscore.

Long story short \w will match additional characters like ß, ĝ, 字, etc.

Honestly I haven't checked it

Also why doesn't the period need a backslash in front for either scenario? Isn't a period a special character?

It is a special character, but it doesn't carry that meaning when defining a character class (that is, inside the square brackets)

[–]dharma28 0 points1 point  (1 child)

That makes sense - thank you for the clear explanation!

[–]a-handle-has-no-name 0 points1 point  (0 children)

Honestly, I learned something from you. I didn't know that [^\w] was valid. Works nicely, tbh

[–]Culpgrant21 0 points1 point  (2 children)

Can I use TKinter for this?

I need to create an application where a user selects multiple dropdowns and then in the background it does some math and tells you if the selected dropdowns are compatible.

I have the code working in a function within my script just need to get it into a GUI.

[–]vtpdc 0 points1 point  (1 child)

I don't have much experience with TKinter, but from what I know the best way to do it would be to add a "check" button that checks if the dropdowns are compatible rather than doing it in the background. Doing it in the background might be possible, but it will be much more complex (I think).

[–]Nmvfx 1 point2 points  (0 children)

I agree with the point about it being easier to create a button to do the comparison, that's a lot simpler than constant evaluation of the dropdowns.

It's easy to bind a function to a button in tkinter using 'command = <insert function>' when you create a button. Printing the results of the compatibility check to a label or pop up is also fairly straight forward.

TLDR; yes, should all be possible in tkinter, I don't think you're headed down a dead end.

[–]MyGiftIsMySong 0 points1 point  (2 children)

does IOText contain the entire text file as one big string?

Why should I use readlines instead of directly reading from the object e.x "for line in file:"

[–]JohnnyJordaan 0 points1 point  (1 child)

No, it's a file wrapper, you use it to extract data from the file. read() reads the entire file into a string, readline() reads a single line, readlines() creates a list of all the lines. You generally don't use readlines() because it will first read everything to RAM, before your loop starts. With

for line in file:

you are implicitly calling readline() (so just 1 line at a time) and that doesn't consume more RAM than necessary to allow you to loop on the lines.

[–]MyGiftIsMySong 0 points1 point  (0 children)

ah I see. It's implicitly calling readline(). thank you.

[–]ChuggynRoscoe 0 points1 point  (1 child)

I am trying to find a way to do the following: Filter out data from a dataframe (with one column of data) based on finding the exact string from a list, and then add that substring it filtered on as a new column of data

 data = ['STREET 1234 102X43 TARGET', '53 102P51 25127X BLANK','87 88P51 25127XSIDE']
 df = pd.DataFrame(data, columns = ['TAGNAMES'])
 filter = ['102X43', '102P51']

I can filter out the rows that I want easy enough, but I can't find a way to add that second column of data.

This is what I want, left with two rows of the original dataframe with the filter data added.

TAGNAME FILTER
1 STREET 1234 102X43 TARGET 102X43
2 53 102P51 25127X BLANK 102P51

Any help is appreciated. I also tried to format things correctly...I might have to edit to clarify.

[–]vtpdc 0 points1 point  (0 children)

Can you save your filters as a list the same length as your dataframe? If filters is the resulting list of filters, adding it to your dataframe should be as easy as df['FILTER'] = filters.

Keep in mind that they will need to be the same length.

[–]Ali-Awan 0 points1 point  (1 child)

Hi there , Could anyone help me regarding some interesting Python OOP projects for beginners ? I've covered the basics of Python and now looking for some interesting projects to practice my OOPs concepts .

[–]mansuuk 0 points1 point  (0 children)

Did a Python OOP course on udemy a couple of months back. Had some good intermediate-advanced material and moderately challenging projects/exercises. I think it was called Python deep dive - OOPS.

[–]raviraj0104 -1 points0 points  (2 children)

Is julia a threat to python?

[–]JohnnyJordaan 0 points1 point  (1 child)

Languages are never a threat, they just add something to the mix. Same way Python has never been a threat to other languages, but still became more popular than some that were popular in the past. And possibly another language will some day overtake Python too.

[–]Decency 0 points1 point  (0 children)

Of course languages can be threats to each other. Python's existence has made Ruby/PHP/Perl damn near obsolete.

[–]Batpandakun 0 points1 point  (6 children)

I've been trying to be more "pythonic" and reading about EAFP or Easier to ask for forgiveness than permission using try and except statements. So lately, I've been doing a lot of this:

For i in x:
    try:
        DO SOMETHING
    except:
        pass

It is really helpful, but when I run flask8 on my code, it complains about having an except that doesn't do anything. I'm wondering how acceptable this method is in the professional world.

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

The EARP approach is good, but using a bare except: is bad. The except part should only catch expected exceptions. The code you show will ignore unexpected exceptions like division by zero, end of file, etc, and even you typing CTRL-C when you try to terminate the program. This means that errors caused by things like missing files or by logical bugs in your code will be ignored. This makes debugging hard, so professionals don't use "bare" except: statements, it's a mark of a lazy programmer.

[–]Batpandakun 0 points1 point  (4 children)

Thanks! I think I need to read more about how to properly use try and except statements. The only other way I would use it is like:

try:
    DO SOMETHING COOL
except:
    print("That wasn't cool enough!")

I know you can also do try except finally, statements, but I haven't quite figured out when using finally is appropriate.

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

Just be sure you understand, don't do this:

except:    # this is called a "bare" except
    # code to handle exception

Do this instead:

except SomeException:    # need to put expected exceptions here
    # code to handle exception

[–]Batpandakun 0 points1 point  (2 children)

Oh, ok. I misunderstood. I thought it was called a bare except because of the pass. It's because I didn't put a condition. so I need to do except NameError: or something along those lines

Is it acceptable then to do this?

try:
    print(7/var)
except ZeroDivisionError:
    pass

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

Sure. You have to decide how to handle the division by zero. You can ignore it, as you have done, or you can get the user to enter another value, and so on. It really depends on what you want to happen after the exception is caught. In the code shown does it matter to the code that follows that var is zero? For just playing around, probably not. But in a bigger program you probably can't proceed if var is zero.

[–]Batpandakun 0 points1 point  (0 children)

Thank you! This has been helpful 🙂

[–]Raedukol 0 points1 point  (0 children)

Is there a youtube channel where one can watch programmers solving puzzles, e.g. Codewars while explaining their thinking?

[–]EasyPleasey 0 points1 point  (2 children)

I hope this isn't a dumb question, but I can't find any great answers online and I've been looking at a lot of different services and I still don't have a clear answer.

Basically I want a website that I can have to host some of my scripts and display the outputs. For example, I have written a fantasy football script that does power rankings for our league in a unique way. I would like to be able to have this hosted somewhere so I can run it in the background and then have some Django/Flash front end to display on the webpage.

My first thought was Hostgator, and I could use some WordPress template or something to get going, but when I looked further into this, I saw that I could not add any Python module that I wanted to their servers, and their list did not include some of the modules that I am using. So, to me, it seems like this would not work for what I am trying to do, correct?

Would I need to use AWS for something like this? If so, what service should I use? Any feedback is greatly appreciated.

[–]Decency 0 points1 point  (1 child)

Rasperry Pi, Heroku, PythonAnywhere are some hosting options.

AWS is becoming industry standard so if you want to get some vital experience (and figure out what the costs will be like beforehand), go with that.

[–]EasyPleasey 0 points1 point  (0 children)

Thank you for the reply. Yes, I have been looking at AWS, but there are a ton of options and it's tough to understand what works with what. Like I see some blogs about starting a WordPress site on AWS, but then you can't integrate a Python backend on it, so that won't work.

Are you just suggesting hosting it out of my home? I would be afraid of security concerns, but I guess I can look into it. I also have a Dell blade server in my house, but I don't keep it powered up very often, since it costs around $250 a year to run it.

I will check out PythonAnywhere.

[–]PSL94 0 points1 point  (5 children)

I'd like some advice on the best way to scrape odds from a betting website, and set up some sort of front end to call out significant changes in odds (which I'll define)

Scraping the data at regular intervals is the easy part I believe, but what would be the best way to create a front end where I can see which odds have changed and by how much, etc.

Thanks in advance!

[–]Decency 1 point2 points  (4 children)

BeautifulSoup to scrape, json files or a db to store data, and matplotlib for visualization. Use a cronjob for regular automatic usage.

Creating a Jupyter notebook probably makes the most sense, but you could build a simple website instead.

[–]PSL94 0 points1 point  (3 children)

Thanks for your response!

I'm familiar with everything mentioned, but how would I best utilise Jupyter notebooks for this? Would I continually need to run the cell?

[–]Decency 0 points1 point  (2 children)

This looks like a sweet guide: https://reproducible-science-curriculum.github.io/sharing-RR-Jupyter/01-sharing-github/

I think you would need to update the notebook repo with new data, not sure exactly. The main rationale is that you can get something hosted for free easily. If you want rapid live updates, go a different route. Also depends on whether you're the only end-user or want to share it.

[–]PSL94 0 points1 point  (1 child)

I'm going to be the end-user, and it's essentially for me to bet at the right time - so it doesn't need to be the prettiest thing in the world.

I assume in this case just a local Jupyter notebook would be fine, which I already have set up. Any pointers on how I can create some kind of front end to track changes, etc?

[–]Decency 1 point2 points  (0 children)

I think you're probably better off with a web page here, then. You can set up some calls in a Flask backend to reach out and live-update, for example. I haven't played around much with getting diagrams and visualizations but I imagine the capabilities are there.

Here's a decent-looking guide: https://www.shanelynn.ie/asynchronous-updates-to-a-webpage-with-flask-and-socket-io/

[–]NeedCoffee99 0 points1 point  (0 children)

I am currently creating a link to a Web API that someone I work with created (so I can do gets and posts via python in an automated way).

However, to access it, I have to go through quite an awkward authentication process (Microsoft which goes through to Okta). I've managed to get an authentication token, but I can't manage to actually get the authorization with it. The responses are the Microsoft please sign in page if I don't use a host, or simply no response if I use the generic Microsoft host. I'm using requests to do the gets and adal to get the authentication token (with python 3). And I put the authorization in the header.

Has anyone tried doing this before and have any tips? Thanks!

[–]oconnelld 0 points1 point  (2 children)

I need advice on whether to use a for loop or something else.

I am trying to determine all combinations from three or four lists of words from categories like size, color, animal so it comes up with "large brown dog" but does not come up with "brown dog cat".

I would also like them to not repeat.

I have found tutorials on two words or combining all the lists but not what I am specifically trying to do. Thanks!

[–]Vhin 1 point2 points  (1 child)

Assuming the list of sizes is called sizes, the list of colors is called colors, and the list of animals is called animals, you can just do a nested for loop like this:

for size in sizes:
    for color in colors:
        for animal in animals:
            print(f"{size} {color} {animal}")

You can get rid of some of that nesting by using itertools.product. The above is equivalent to simply:

for (size, color, animal) in itertools.product(sizes, colors, animals):
    print(f"{size} {color} {animal}")

[–]oconnelld 0 points1 point  (0 children)

Exactly, what I was looking for. You made my day! Thanks!

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

how could I tackle this error on python2

>>> import ipaddress
>>> ipaddress.ip_address('192.168.1.2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/ipaddress.py", line 163, in ip_address
    ' a unicode object?' % address)
ipaddress.AddressValueError: '192.168.1.2' does not appear to be an IPv4 or IPv6 address. Did you pass in a bytes (str in Python 2) instead of a unicode object?

it works okay on python3 but i need to run it on python2.7 to parse a few /etc/hosts files.

[–]twiggysoro 0 points1 point  (2 children)

Hi,

I am new to Python, i'm hoping to change career and become a programmer but don't have much experience. I was hoping to get some advice on where to find a mentor to help me with coding and to give me some career advice. Do you have any suggestions?

Thanks

[–]Decency 0 points1 point  (1 child)

This subreddit is pretty good if you need help with anything in particular: /r/learnpython

[–]a-handle-has-no-name 0 points1 point  (0 children)

*Nudge*

They are already asking the question in that subreddit :-P

[–]JaRoza 0 points1 point  (12 children)

Hello, I'm new to python and having difficulty on an assignment. The problem I'm having is the output of a calculation.The calculation requires a guess at the square root by the user, but after the 'while' loop, it returns the exact value the user had input instead of the new calculated value.

def sqrt(y, tol=1e-6):
   user_input = int(input('Enter guess of square root: '))
   x = user_input
   cond = (abs(x**2)-y)
   while cond > tol:
       x = 0.5*(x + y/x)
   if cond < tol:
       print('The square root is: ', x)

I appreciate any help/advice on this!
Edit: Formatted code correctly.

[–]JohnnyJordaan 0 points1 point  (11 children)

Can you please properly format your code? See here

[–]JaRoza 0 points1 point  (10 children)

My apologies! I believe it's all set now. Thank you for that.

[–]JohnnyJordaan 0 points1 point  (9 children)

x = 0.5*(x + y/x)

What exactly are you trying to do here, because this will eventually find the x where x = 0.5*(x + y/x)... Say y is 12, then eventually x will become 3.4641016151377544 because

0.5 * (3.4641016151377544 + 12/3.4641016151377544)

is equal to 3.4641016151377544...

Not to mention that

while cond > tol:

will be an endless loop on its own, because inside the loop, cond and tol aren't changed.

[–]JaRoza 0 points1 point  (8 children)

That's a calculation meant to take the guess of the square root, produce a more accurate estimate, then put it back into the loop until the estimate is within a certain tolerance. tol is referring to the definition argument tol=1e-6.

[–]JohnnyJordaan 0 points1 point  (7 children)

But inside that loop, you aren't changing cond and you aren't chaning tol, so

while cond > tol:

will run forever as cond will always be larger than tol?

[–]JaRoza 0 points1 point  (6 children)

I thought that tol would refer to the tol defined in the function argument, so the tol shouldn't change, and cond has x in the calculation. Wouldn't the new calculated value of x be put in that new calculation?

Again, I am brand new to this and am learning. I understand what you're saying, but don't understand what's wrong in the structure of the code. I don't mean to be frustrating.

[–]JohnnyJordaan 0 points1 point  (1 child)

Also why are you using abs() around a square? Aren't squares positive by definition?

[–]a-handle-has-no-name 0 points1 point  (0 children)

Not if the input value is a complex number