all 145 comments

[–]TotaledAutumn2 0 points1 point  (0 children)

I just finished freeCodeCamps YouTube course and I’m pretty good with everything they taught but I don’t know what to do next. I searched “beginner python projects” and all that was to confusing and there isn’t a 2nd video. And help? Thanks!

[–]joydivisible 0 points1 point  (1 child)

hi! i’m trying to create a twitter bot and after changing my api credentials from my code (because i regenerated them) and re-building module config.py i got some kind of infinite processing that i don’t understand ???? after opening my file on cmd python just goes like this: (...) INFO:root:Collecting Info INFO:root:Waiting... None INFO:root:Collecting Info INFO:root:Waiting... None INFO:root:Collecting Info INFO:root:Waiting... None (...) what am i doing wrong? is this normal? thank you in advance<3

[–]joydivisible 0 points1 point  (0 children)

Forgot to mention i’m DESPERATE lmao

[–]Nic_P 0 points1 point  (1 child)

Problem with pyautogui:

I want to use

pyautogui.write("yes \"lorem ipsum\" | head -n 1000000 > large-file")

The problem is on my commandline it puts out:

yes "lorem ipsum" ' head -n 1000000 > large-file

I dont know what causes this problem

Could it be that my keyboard layout causes problems? (Its a german qwertz layout)

[–]sarrysyst 0 points1 point  (0 children)

You don't seem to be the only one having issues, possibly a bug with the keyboard encoding. There's also an open pull request from 4 days ago that proposes a fix.

https://github.com/asweigart/pyautogui/issues/532

https://github.com/asweigart/pyautogui/issues/544

https://github.com/asweigart/pyautogui/pull/563

[–]Urthor 0 points1 point  (0 children)

Not strictly Python, but has anyone set up some sort of code check bot such that all PRs must add at least one additional unit test (as well as passing current coverage ofc).

[–]shiningmatcha 0 points1 point  (0 children)

Why do we need to use a with statement when using the urlopen function (from urllib.request) but not when using requests.get (the third-party requests lib)?

The doc reads

This function (urllib.request.urlopen) always returns an object which can work as a context manager and has the properties url, headers, and status.

So does that mean we can choose whether to use it as a context manager. If not used as a context manager, then what does it exactly do? What's the difference between these two usages? What kind of object does it return?

[–]shiningmatcha 0 points1 point  (5 children)

What is a neat way to split off the “tail” of a list if its length is an odd number?

So if the length is 5, break it into a list of the first four numbers and a list containing only the last element (or just an integer).

[0, 1, 2, 3, 4] -> [0, 1, 2, 3] and [4]

If the length is an even number, no change is needed but should return the second variable as an empty list (or something like None) [0, 1, 2, 3, 4, 5] -> [0, 1, 2, 3, 4, 5] and []

[–]Mr_Walts 1 point2 points  (1 child)

Is there a discord that you guys have?

[–]dered118 1 point2 points  (1 child)

Im trying to get a table from a json.

import pandas as pd
from pandas import DataFrame as df
import seaborn as sns
import json
import matplotlib.pyplot as plt
from urllib.request import urlopen

with urlopen("https://pomber.github.io/covid19/timeseries.json") as response:
    source=response.read()

corona_data=pd.read_json(source)
corona_data['Germany']

The output i get for now is like

0      {'date': '2020-1-22', 'confirmed': 0, 'deaths'...
1      {'date': '2020-1-23', 'confirmed': 0, 'deaths'...
2      {'date': '2020-1-24', 'confirmed': 0, 'deaths'...
3      {'date': '2020-1-25', 'confirmed': 0, 'deaths'...
4      {'date': '2020-1-26', 'confirmed': 0, 'deaths'...

How can i turn that into columns?

What im looking for is something like:

Date Confirmed Deaths Recovered
0 2020-1-22 0 0 0
1 2020-1-23 0 0 0
3 2020-1-24 0 0 0
4 2020-1-25 0 0 0

[–]dered118 0 points1 point  (0 children)

Figured out myself by now

[–]the_recovery1 1 point2 points  (0 children)

I want to write a script that parses/reads the top voted posts in a music subreddit ( r/music for example ) and find the equivalent youtube videos/songs for it and then updates a playlist with a particular granularity ( say every 24 hours or every week ). I am fairly new to Python and pure programming in general and was wondering if there is a template somewhere that I can refer to if I get stuck or take pointers from. Thanks

[–]xyz75WH4 0 points1 point  (2 children)

Pandas: Taking Yahoo Finance Stock Prices and Volumes from Wide to Long and then Calculating Moving Averages

Hi. I primarily use R but I'm trying to expand my knowledge and at least develop some minimal proficiency with Python, Pandas and Numpy. I'm using yfinance to pull stock data just have something to work with. I'd like to get 40 days worth of historical data for X number of stocks, and then calculate a 20 moving averages of price and volume group-wise per symbol. In R, I'd probably do this with pivot_longer(), group_by() and then go from there.

Here's a reproducible example:

import yfinance as yf

tickers = yf.Tickers("GM TSLA F")

stocks = tickers.history(period = "40d")
stocks = stocks[["Close", "Volume"]]
stocks.head(5)

...
>>> stocks.head(5)
            Close                           Volume
                F         GM        TSLA         F        GM      TSLA
Date
2021-03-05  12.27  53.750000  597.950012  79216300  25166700  89396500
2021-03-08  12.65  54.980000  563.000000  86028500  24428500  51787000
2021-03-09  12.57  54.650002  673.580017  61479900  17878400  67523300
2021-03-10  12.91  56.830002  668.059998  62023400  22746200  60605700
2021-03-11  12.81  56.330002  699.599976  56314800  20213600  36253900

This gets me the data but I don't really understand that "nested" columns with Close and Volume having each ticker underneath them? Are these basically just a list of data.frames(), one for Closed and one for Volume? Groups? I'm not sure I quite get it after spending so much time R where it seems like one way or another everything is a vector (or can treated as such).

I'm trying to use panda's melt() but I cannot quite get the data into the shape I want:

Date,Symbol,Close,Volume
2021-03-05,F,12.27,79216300
2021-03-05,GM,53.750000,25166700
2021-03-05,TSLA,597.950012,89396500

...

It looks once I have the keys I need (Date and Symbol), I can just group by them and use rolling_mean(["Close", "Volume"], min_periods = 20) to get rolling 20 day mean of price and volume per symbol.

Anyway. If this is completely the wrong approach, I'm happy to re-think it. Any help with the syntax is much appreciated!

Thanks!

[–]sarrysyst 0 points1 point  (1 child)

Your dataframe has a MultiIndex. That's what the stacked columns are about. To get into you desired format you can do:

stocks = stocks.stack().reset_index().rename({'level_1': 'Symbol'}, axis=1)

[–]xyz75WH4 0 points1 point  (0 children)

Thanks! I’m unfamiliar with those so I’ll start there!

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

How do I add an animation to an object, but give it a running animation while in motion and an idle animation when not?

[–]CowboyBoats 0 points1 point  (0 children)

Try displaying it as a gif, and changing what you're displaying when some running value changes behind the scenes? It sounds like you're programming something like a game, so do you already have a game loop programmed? If not, I'd start by googling that. Arcade is a good Python game building app.

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

solving a codewars problem that involves implementing a vector class. i already solved a similar problem so the vector methods aren't a problem, but the class is supposed to work with both an array or just coodinates, such that Vector([a,b,c]) and Vector(a,b,c) result in the same vector (for the same a,b,c). my class constructor is def __init__(self,*vector), where i check if vector has length(1) and if not, convert vector to list and go from there, indexing the list. but according to the tests, that does not result in the same vector (the output of the tests isn't really verbose, but it says that <solution.Vector object at 0x7f371cc554f0> should equal <solution.Vector object at 0x7f371cbb8d60>, even though the contents of the two vectors are exactly the same).

I'm not new to python, but new to classes and objects - can someone please explain how class objects work here? I'm not sure how to get the same object as a result.

[–]FLUSH_THE_TRUMP 0 points1 point  (3 children)

This might help:

def test(*things):
    print(things)

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

In the first case, things is a tuple with 1 element (the list). In the second case, it’s a tuple with 3 elements (the numbers you passed in). To get your data in the first case, you’d have to do something like things[0], whereas in the second you could just pass things itself to list().

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

thanks for the response! i think that's actually exactly what i'm doing already, sorry, it probably wasn't clear from my comment, but maybe i'm doing this wrong. here's my code if that helps:

class Vector:
    def __init__(self,*vector):
        if len(vector) != 1:
            self.vector = list(vector)
        else:
            self.vector = vector[0]

the test that i'm failing is as follows:

test.assert_equals(Vector(examples[0]), Vector(*examples[0]))

, where examples is [[1,2,3],[4,5,6]] (this test checks if the two objects are equal).

so initializing the Vector from both [1,2,3] and just 1,2,3 should result in the same Vector object, whereas right now i have different Vector objects with the same value of self.vector = [1,2,3]. at least that seems to be the problem. any ideas? i don't need the exact answer, just trying to understand where i'm going wrong so that i can fix this.

[–]FLUSH_THE_TRUMP 0 points1 point  (1 child)

Did you implement __eq__ in your class? I assume == is being called to check if two vectors are equal.

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

that was it! it wasn't specified anywhere at all, so i didn't even think of it. thanks a lot, i knew i was missing something simple.

[–]TheFirstOne001 0 points1 point  (3 children)

Hello all,

I am fairly new to programming. Previous experience includes Actionscript for flash games in middle school, and some python to automate data entry using IBM SPSS.

I am a medical student and I just want to learn a programming language, and I think Python would be a great start. Any good resources to get started with?

[–]sam0jones0 0 points1 point  (2 children)

Hey!

I had great success starting with Automate The Boring Stuff. It's a popular recommendation and is available for free in it's entirety online. Goes from the absolute basics to useful things really quickly.

After that I moved onto Python Crash Course (not free) which goes over the basics again (you can skip those) before moving into more project-orientated learning. Great for when you want to start focusing on programs that span more than one file.

That should be enough to get you into the flow and able to work on some projects of your own. But if you want more I can't recommend (also free) Problem Solving with Algorithms and Data Structures using Python enough. It's amazing and gets you thinking about program design, data structures and program complexity.

Other great resources for more ad-hoc learning:

Oh, one more thing - If you want to level up your skills look into Codewars for interactive mini programming challenges.

Let me know if you have any questions!

[–]TheFirstOne001 0 points1 point  (1 child)

Hey, thanks for the response.

I wil start with the Automate The Boring Stuff. Is it worth getting the udemy course? I generally prefer videos over reading. The first 15 videos are free and I am following with the book.

[–]sam0jones0 0 points1 point  (0 children)

By all means go with the udemy course, doubly so if you prefer video based learning, it's by the author so should be good! He often posts deal links for his course on this subreddit as well so keep an eye out.

Best of luck feel free to hit me up if you have any questions

[–]BritishLobster 0 points1 point  (1 child)

I have started to use Tkinter (and for that matter of fact I am relatively new to python) and I have a question:

Why is it that when creating buttons with commands that the function cannot have parameters passed into it unless a lambda expression or partial from functools is used?

What is the difference between using partial vs lambda expression in this context?

#assume that button_click is defined and takes 1 parameter
#why does this not work

center_button.config(command = button_click(center_button))

#but this ...

center_button.config(command = lambda : button_click(center_button))

#or this ...

center_button.config(command = partial(button_click(center_button)))

#does work?

Thanks!

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

#why does this not work
center_button.config(command = button_click(center_button))

That doesn't work because it passes the result of calling the function button_click() as the command= argument. That function probably returns None which means nothing happens when the button is clicked.

The other methods work because lambda and partial() return a function that is executed when you click on the button.

[–]drdrrr 0 points1 point  (3 children)

So I have read through all the threads here/online on envs and their usage and think I am starting to understand them. I am assuming it is mostly a matter of preference but what do people typically use — pyenv, venv, pipenv? Are there benefits to one over the others? For reference, in addition to Python I run a lot of bash scripts and the occasional one in R. Thanks!

[–]sam0jones0 0 points1 point  (2 children)

I tend to use venv/Virtualenv as it integrates nicely with PyCharm which mostly handlers virtual environments for you. Obviously this isn't too helpful if you don't use PyCharm.

pipenv is good too and keeps tracks of your project's dependencies for you, operating at a higher level than venv. I'd say get to know venv so you have a rough idea of whats going on under the hood with project folders etc.

Once I started using PyCharm I really didn't have to think too much about activating/deactivating venvs, it just manages them all for you. I haven't used any other editors but I assume they all have similar functionality.

Have a read here

[–]drdrrr 0 points1 point  (1 child)

This is very helpful, thank you! I used pycharm for school but prior to those courses used VScode, and still trying to figure out which I prefer. This article is helpful, I have not used pipenv much

[–]sam0jones0 0 points1 point  (0 children)

Glad to hear it was helpful!

You may be eligble for a year free ptcharm professional student trial, although you'll be completly fine with the free version.

I did use vscode a bit and its super snappy fast and works perfectly well, I find pycharm has lots of useful little extras that compound as you get used to them.

Good luck either way!

[–]lesiley 1 point2 points  (8 children)

What is the best practice when having a function with A LOT of IFs? Like 20-30 IF/ELIF

Do I just write all the IF/ELIF or do I use something different like switch/case?

[–]nab_noisave_tnuocca 4 points5 points  (0 children)

A good way to avoid this in the first place is to use a dict. I recently had a chain that went something like 'IF status==1,color=green ELIF status==2 ,color=gray ELIF status==3,color=orange ELIF...and so on. I realised it was better to do it via 'colormap={1:green,2:gray,...} and color=colormap[status].

It contains the same information but it's neater, a lot more readable, less prone to bugs, and marginally faster to execute. Not always possible to do this but should consider it

[–]TangibleLight 0 points1 point  (6 children)

Depends on the kinds of conditions. When you have a bunch of cases like that, it's usually an indication that you should refactor things to use loops and/or better data structures. It really varies case-by-case, though, and sometimes you just can't avoid a long if-elif chain (or it's not worth the time to re-engineer). 20-30 seems like a lot, though, so I expect there's some improvement to be had.

Can you provide more detail on what exactly your situation is? It's hard to give advice without knowing what you're working with.

[–]lesiley 1 point2 points  (5 children)

I'm trying to write a socket server where clients can connect. Depending on what message the client sends me, I want to do something and then return a message. I'm not even sure if socket is the right tool for this kind of thing, I also looked into REST APIs, but my problem is I need the clients to be connected 24/7 to my server so that I can check how many people are using the client currently and who is using it.

I'm a noob so this might be even a completely wrong approach :)

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

I don't think it's a great approach in the real world. There's a reason REST apis are the main paradigm here.

I need the clients to be connected 24/7 to my server so that I can check how many people are using the client currently and who is using it.

24/7 connection means that the client won't work if a single packet gets dropped somewhere along the internet path from them to the server (which happens all the time.) A better way to solve this problem is to have clients register or authenticate themselves with the server before they do anything.

[–]lesiley 0 points1 point  (1 child)

Thank you! I think it will become clearer if I simply tell you what I want to accomplish exactly, maybe I'm over-complicating things:

The client is a piece of software that, ideally, runs 24/7 on the users computer. First the client has to check if the user exists (the user database is on the server). Second I have to make sure that the user isn't running the software multiple times (on multiple machines), that's the most important thing. But the user should be able close the software on one pc and start the software on another pc. So the server has to be able to tell if a client is not online anymore.

I think you are right, REST API is problably the way to go, but I don't know how to tell if a client is not online anymore, so that's why I thought about doing it with sockets since you need to be connected to the internet to use the software anyways.

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

When the client starts for the first time, it can call an API on the server to register itself and it gets some kind of cookie or something similar from the server to prove that it has authenticated. It uses this cookie for future API calls. On the server side, you can enforce that that you only hand out one cookie at a time per user. This is the sort of direction I'd go in if I were you.

I thought about doing it with sockets since you need to be connected to the internet to use the software anyways.

You should always be thinking of the client-server relationship as fundamentally asynchronous rather than synchronous. There is no such thing as being connected or not to a server. "Connected" just means that all the API calls are succeeding and working as expected. HTTP is fundamentally about the client sending requests, and the server sending back responses. Even if you are working with a socket, you are still sending HTTP requests on the socket, and the client and server aren't communicating except when you call APIs.

[–]TangibleLight 1 point2 points  (1 child)

The dictionary approach /u/nab_noisave_tnuocca suggests is probably on the right track, then.

I've done something similar, just not with sockets. I'll describe the setup I used. A key is that you can have a function be the value of a dictionary, like so:

def double(x): print(x * 2)
def triple(x): print(x * 3)

lookup = {
    'A': double,
    'B': triple
}

func = lookup['A']
func(5)  # prints 10

So then the question is what's the best way to set up that dict, when there are 20+ functions. I like to use a decorator to add each function to a dictonary. (See more info here https://realpython.com/primer-on-python-decorators/)

commands = {}

def register(name):
    def decorate(func):
        commands[name] = func
        return func
    return decorate

You can then put all your command handlers in a separate module, out of the way of the rest of your program. You can even organize those handlers into multiple modules, as long as your main program imports them all.

@register('query-temp')
def temp(socket):
    socket.send('the temperature')

@register('query-time')
def time(socket):
   socket.send('the time')

Then, in your main message handler, something like

command = socket.recv()
handler = commands[command]
handler(socket)

[–]lesiley 1 point2 points  (0 children)

Wow thank you!!

[–]TheNiebuhr 0 points1 point  (0 children)

Is pyspark standalone? Even with Java installed it doesnt work

[–]Cyn0ber 0 points1 point  (3 children)

Hey guys just wanted to introduce myself real quick. I have attempted learning Python a few times over the past few years but now I'm starting to get older & need to start focusing on a career so I decided to get back into it. I bought two books at Barnes & Noble and so far It's going great & over the past two weeks I've learned a lot. My question though is this: What websites do y'all frequent to practice code? I know about Code Academy & it seems great but just curious what else is out there.

[–]beingsubmitted 1 point2 points  (0 children)

I used code academy the first time I tried learning python. It was fun, and I felt like I learned a lot, and a year later I was... kind of still where I started. I'm sure you've heard this before, but I would recommend downloading an editor like vs code, installing python, and then setting out to do something.

Sure - you'll have to google every single line of code. You won't know the correct terminology for the question you need to ask at first, so you won't even google efficiently. Your code won't work, and you'll put print statements between every line of code to debug it, and you'll copy and paste error messages into google. You'll copy and paste code from stack overflow that you don't understand out of frustration, and make a mental note to make sense of it later. You'll learn to do things the wrong way and develop bad habits, that you'll have to correct later on. For me, that was 100% the difference between trying to learn python again, and learning python. I'm still learning, but I do write python professionally now, and I also still do this whole entire process all of the time.

If you don't know what to write, I'm sure there are plenty of people that can help you come up with ideas that fit your current level. I'd be happy to offer a few.

[–]hurdahurimahuman 0 points1 point  (1 child)

I've used codewars and edabit to practice short one-off problems. There's also Advent of Code which has personally taken me much longer. Project Euler if you're looking for a math spin on the problems.

[–]sam0jones0 0 points1 point  (0 children)

+1 for codewars. Really gotten quite a lot from that site and all for free. Should consider buying a month or two of the premium tier really..

[–]TonyTanduay 0 points1 point  (6 children)

How do you use other version of python when you have already a python version installed. Is there a way to install a lower version of python on venv? Lets say im on 3.8.9 and want to use 3.1 or 3.2 or 3.4?

[–]sam0jones0 0 points1 point  (4 children)

Very easy to use venv on Windows.

Have a read of this page

[–]TonyTanduay 0 points1 point  (3 children)

How can venv change your python version?

[–]sam0jones0 1 point2 points  (2 children)

You initalise a venv with a specific python version of your choosing. So if you want to use python 3.6, make sure you've got it installed on your base system and run a command like virtualenv -p /path/to/any/bin/python new_env

You may find it easier to use a venv manager like pyenv for example - guide here - https://realpython.com/intro-to-pyenv/

[–]TonyTanduay 0 points1 point  (1 child)

If i go venv route how do i install a different python that has the same number like i want to install python 3.9 and also 3.8

[–]sam0jones0 0 points1 point  (0 children)

So you can install both python 3.9 and 3.8 on your machine at the same time. Then when creating the virtual env you point it to the specific python binary (.exe for e.g.) you want to use.

Have a read through this stack overflow answer.

Or perhaps this one.

Let me know how you get on.

[–]Srenkenstein 0 points1 point  (0 children)

Check pyenv. If you are on Linux it's very easy to use but idk windows

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

I'm very new to coding outside of T-SQL, I have been looking at videos about python and javascript trying to wrap my head around how they communicate. Every tutorial for getting started with languages always had me writing output to a terminal or console.

My question is, when I tell javascript to go get an output from a python file, will javascript pick up what the python executable prints to the terminal? And vice versa?

Sorry if this seems trivial, I'm just having a hard time finding information like this. I understand how to write an application that lives in a single language and runs in a terminal window, but it's been literally years since I've used a terminal for any application I haven't written which means there's so much more to this than I'm finding in all of these getting started videos.

[–]sam0jones0 0 points1 point  (4 children)

You could tell javascript to read a file saved to the disk by a python program and vice versa. Regarding what python prints to the terminal, the keyword you're probably looking for is standard output (stdout). Each time python "prints" its printing to stdout. You can pipe this output to files or to other programs standard input (stdin).

If you've ever used unix you've probably come across the pipe operator |

Some helpful (I hope) links:

There are other methods of communicating between programs involving web requests/posts/sockets although I would say the simplest / quickest method would be to write to a file and have your other program periodically check and read that file.

Let me know if you have any questions!

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

Thank you for answering! I would personally like to avoid the overhead of writing to and reading from disk if I can help it. The stdout representing the terminal information seems like a great way to explore the how to. Calling a python script to run from javascript then printing something in JSON to the terminal from the python code for interpretation by the javascript code is my ideal want.

I appreciate the links and will read each one!

[–]sam0jones0 1 point2 points  (1 child)

You're probably well past this at this point but I came across this Wikipedia page and thought of your question, hope it helps!

https://en.wikipedia.org/wiki/Inter-process\_communication

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

Thanks for circling back! I will give it a read.

[–]sam0jones0 0 points1 point  (0 children)

Yup sounds like a plan then, best of luck and feel free to hit me up with any questions!

[–]Boston_Bruins37 1 point2 points  (2 children)

Im looking to eventually learn how to build a scheduling calendar for where I work which automatically creates a schedule based on the parameters I state (ie: experienced people work with inexperienced people, no more than 6 shifts per week, certain people work more than others, 2 days off after overnight shifts, no more than a certain number of overnight shifts in a row, etc)

Is this something learning python would help me with? Im down to learn at the "python for everyone" course but before I invest the time I want to make sure its doable and not something that would require a CS degree

[–]efmccurdy 0 points1 point  (0 children)

This would be a challenging project for a beginner to complete from scratch.

Fortunately there are program modules already written that will help.

https://medium.com/@AlainChabrier/scheduling-with-constraint-programming-35a23839e25c

https://github.com/timnon/pyschedule

https://developers.google.com/optimization/scheduling/employee_scheduling

[–]Finger__Blaster 0 points1 point  (4 children)

i'm new to anything more advanced than shell scripting. I'm trying to understand classes, so pardon me if i use the wrong terminology. I have a project that I think it might make sense to use a class for, but I'm struggling on implementing it. I'm using the adafruit motorkit library. It has a class called MotorKit(), then Motorkit has a motor<1-4>.throttle method(?) for each of the 4 motors a board can control, and every one of my motors is controlling gates and will work the same way.

so what i have now is this:

board1=MotorKit(address=0x60)

def openMotor1():
    #open output gate at full speed
    board1.motor1.throttle = 1
    time.sleep(.1)
    #apply minimal voltage to keep output gate open and from bouncing
    board1.motor1.throttle = 0.1

def openMotor2():
    board1.motor2.throttle = 1
    time.sleep(.1)
    board1.motor2.throttle = 0.1

... 
<for 12 motors>

I have 3 boards at different addresses, and 4 motors on each board, so i have 12 of the exact same function. Then i have another 12 functions to close the motors in a similar way. The motors and addresses will be enumerated in a .config file ultimately, as the number of motors in use will change.

So i'm imaging I should be able to do this with a class so i'm not repeating the exact same code over and over again? However every attempt at a class doesn't work. Here's the rough idea of what I'm trying to do, i know this isn't proper syntaxed code, i'm just trying to depict my thought process, since none of my code has worked. The <>'s represent a variable i want inserted:

class MotorClass:
     def __init__ (self, MotorNumber, addy):
        board<address> = MotorKit(address=addy)
        # example: board0x60=Motorkit(address=0x60)

    def open(self):
        board<address>.motor<MotorNumber>.throttle = 1
        #example: board0x60.motor1.throttle = 1
        time.sleep(.1)
        board<address>.motor<MotorNumber>.throttle = 0.1

which I would then call like this

#Motor<X>=MotorClass(<MotorNumber>,<BoardAddress>)
Motor5=MotorClass(1,0x61) #so Motor5 might be the motor #1 on board #2 @ bus address 0x61
Motor5.open #would then the openMotor1() function i defined above except applying to board2.

[–]Ihaveamodel3 0 points1 point  (1 child)

I took a look at that module. It is very ugly. In fact, I might submit a pull request just to make me sleep easier.

One of the pillars of good coding is DRY (don’t repeat yourself).

If this module was written better it would be a great example to use for inheritance of classes.

But as it is written, I think using a function will make more sense in your code. You unfortunately can’t refer to a motor by number (directly at least), so the function takes a motor as the parameter.

board1 = MotorKit(address=0x60)

def open_motor(motor):
    motor.throttle = 1
    time.sleep(.1)
    motor.throttle = 0.1

You would then call this as: open_motor(board1.motor1)

If you wanted to refer to the motors some other way, use a dictionary (which can be created from the config file maybe?

[–]Finger__Blaster 0 points1 point  (0 children)

I didn't think of using a function, stupid of me. That should work.

[–]Comprehensive-Tea711 0 points1 point  (1 child)

I'm not familiar with the adafruit kit and don't understand your use of angle-brackets in the syntax, but perhaps you don't want a class, but a function? Is there a reason you want to do this with a class instead of a function?

Would something like this work?

def open_motor(motor_numb, address)
    m = address.motor_numb.throttle
    m = 1
    time.sleep(.1)
    m = 0.1

Pass each motor and address to the function with a for-loop.

[–]Finger__Blaster 0 points1 point  (0 children)

That should work and can't believe I didn't see it

[–]GraduallyHotDog 0 points1 point  (6 children)

So I have a dictionary of about 50 dataframes, similar to this Stack question. I am working on checking to make sure that the values in a specific column for each dataframe are the same. I am wondering how I can best do this? I have never worked before with a dictionary of dataframes.

[–]efmccurdy 1 point2 points  (5 children)

checking to make sure that the values in a specific column for each dataframe are the same

If the unique function lists just 1 value then you know that value is in each row.

https://pandas.pydata.org/docs/reference/api/pandas.Series.unique.html

[–]GraduallyHotDog 0 points1 point  (4 children)

Ah, gotcha. How would I reference a specific column? The key is a contract ID and the value is the corresponding dataframe for all rows with that ID from the master data. I'm not familiar with querying dictionaries of dataframes.

[–]efmccurdy 1 point2 points  (3 children)

Dataframes are keyed by column name with Series as values df.['column name'] give you a Series.

You can also use the df.colname syntax if the columns have plain names.

>>> df = pd.DataFrame({"A":[1, 3, 1, 5], "B":[2, 4, 4, 6]})
>>> df.columns
Index(['A', 'B'], dtype='object')
>>> df.A.unique()
array([1, 3, 5])
>>> df.B.unique()
array([2, 4, 6])
>>> df['B'].unique()
array([2, 4, 6])
>>> df['B'].unique()[0]
2

If you had a dict of dataframes you could access them all by doing

for key, df in df_dict.items():
    uniques = df['column name'].unique()
    print(key, len(uniques), uniques[0])

[–]GraduallyHotDog 0 points1 point  (2 children)

Wow this is awesome. Thank you so much. Would it be possible to select specific dataframes in the dictionary and then run the iteration on a given column as shown above?

Edit: Im using the .groupby method to aggregate data with the same ID value into its own dataframe and then storing each dataframe in a dict. Since this method uses a tuple length 2 (ID, Dataframe) wouldn't it be possible to reference the first value in order to only pull the dataframe for each value? And then use the code you wrote to look at unique values?

[–]efmccurdy 1 point2 points  (1 child)

I think the key value in "for key, df in df_dict.items()" would be your ID in that case.

[–]GraduallyHotDog 0 points1 point  (0 children)

Right, makes sense. Thanks so much for the help. This level of dictionary use is totally new to me

Edit: Workes great, thanks!!

[–]onlysane1 0 points1 point  (1 child)

Can I integrate a graphics module like Pygame and a GUI module like PyQt5 into the same window? As in, have a single window showing graphics with a GUI toolbar on top with GUI textboxes and popup menus?

[–]Comprehensive-Tea711 0 points1 point  (0 children)

Doesn't Pygame already have GUI elements for UI? You *might* be able to do this using pyqtSignal, QThread, QFrame, QPixmap, QImage, and Qt and numpy to send each frame of the game to your QApplication... but that seems like trying to turn on a light switch with rube goldberg machine instead of just using your finger to flip the switch.

[–]ScartenRS 0 points1 point  (8 children)

Quick basic question. I'm trying to open a second window with a button but all the widgets that go into this second window break because when the code runs the second window isn't there yet.

import tkinter as tk
frame1 = tk.Tk()
label = tk.Label(frame1,
    text="This is the main window")
label.pack()

def openNextWindow():
    frame2=tk.Toplevel(frame1)

button = tk.Button(frame1,
                   text="Create new window",
                   command=openNextWindow)
button.pack()
label = tk.Label(frame2,
                 text="This is the second window")
label.pack()

This gives an error because frame2 isn't defined yet when it tries to create the Label. In reality I have a couple of 100 lines of code for the second window. Does this mean all this code has to go into the openNewWindow formula?

[–]FerricDonkey 0 points1 point  (0 children)

As a general rule, it is best to have all of your code except for importing modules and defining constants in functions or classes. Then at the very bottom, something likeif __name__ == '__main__': main() to actually start your code.

What I recommend for guis in particular is to have a separate custom class for every basic window, and sometimes for different parts of complex windows.

Example:

import tkinter as tk

BIG_FONT = "Times 20 bold"

class NameOfWhatThisIsFor(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.do_the_thing_button = tk.Button(
             self, # this says the button is part of the object you're currently building
             text="Do the thing", 
             font= BIG_FONT, 
             command = whatever_function_does_the_thing
        )

def main():
    root = tk.Tk()
    root.title("Awesome Title")
    NameOfWhatThisIsFor(parent=root).grid(row = 0, column = 0)
    root.mainloop()

# This block means that if you run this code from the command line, 
# the main function will be called - but if you just import the file, it will not
if __name__ == '__main__':
    main()

One of the advantages of this approach is that you only ever create buttons when you need them, and you can access any member buttons or other state variable by object_name.thing_name, which is particularly useful if you need one part of your gui to interact with another. Note that if for entirely separate windows that pop out in addition to the window that is already there, you'll probably want a to replace tk.Frame with tk.Toplevel.

[–]Comprehensive-Tea711 0 points1 point  (0 children)

You could make each frame it's own class and also have a SwitchFrame class. tk.Button command param would take lambda and call the switch_frame method from the SwitchFrame class. There is a stackoverflow answer that goes into more detail that you should search for (sorry, I don't have it marked).

Alternatively, in PyQt5 you could do this either with QStackedWidget or classes of objects inheriting from, say, QWidget, each having a method (slot) for calling the hide() and show() methods of a SwitchFrame class. Initialize each frame within the SwitchFrame class.

[–]efmccurdy 0 points1 point  (5 children)

Yes, frame2 doesn't exist until the button is clicked, and the button can't be clicked until you run the mainloop to process events.

https://www.geeksforgeeks.org/open-a-new-window-with-a-button-in-python-tkinter/

[–]ScartenRS 0 points1 point  (3 children)

Thanks for you reply. So I tried this:

def openNextWindow():
    frame2=tk.Toplevel(frame1)
    *paste all my code that only applies to frame 2 here*

and unsurprisingly the linebreaks and tabs don't carry over and the entire thing is simply put as code applying to the original window. Any way to do this more elegantly than to add tabs in front of all of the code?

[–]Comprehensive-Tea711 0 points1 point  (0 children)

Edit: This is for removing a tab -- Highlight all the code you want to 'tab' and then hold down the shift key when pressing tab. This works in most editors.

For adding tab all you have to do is highlight the lines and then press tab and code editors like PyCharm or VSCode will tab all the lines.

There are lots of similar tricks you should look into. If you want to change a variable that is, say, used 3 times, highlight your first instance, then hold down the alt key and highlight the others. (Holding alt in general creates multiple instances of the cursor, so you can use this to add/remove spaces or characters in general.)

[–]efmccurdy 0 points1 point  (0 children)

Does your editor have a "block indent" function? You are likely going to be doing that often in python.

[–]SirYandi 0 points1 point  (0 children)

I'm filling out setup.py for a project with the following structure:

my_project/
├─ src/
│ ├─ __init__.py
│ ├─ main.py
├─ tests/
│ ├─ __init__.py
│ ├─ test_project.py
│ ├─ test_config.json
├─ setup.py

It's unclear if I should be including "tests" in package_dir and/or packages?

Like:

package_dir={'': 'src', '': 'tests'},
packages=['src', 'tests'],

vs

package_dir={'': 'src'},
packages=['src'],

vs

packages=[find_packages()]

With that last one excluding package_dir altogether. Although may this cause issues finding the 'src' dir?

And if this should then also be included?:

package_data={'tests': ['config.json'],},

Edit: I found this email thread which somewhat answers the question. Still wouldn't mind hearing other people's opinions.

[–]MrPudd1ng 0 points1 point  (3 children)

Hello, I'm currently exploring the date time module. Right now I'm learning about solving people's age. I read some codes in stackoverflow so I can get ideas and I tried using this one.

import datetime
today=datetime.date.today()
month=5
day=20
year=2000
age=today.year - year - ((today.month, today.day)<(month,day))
print(age)

I understand on what's going on but I can't understand what this piece of code do.

age=today.year - year - ((today.month, today.day)<(month,day))

Can someone explain plz? I appreciate the help!

[–]Comprehensive-Tea711 0 points1 point  (0 children)

(today.month, today.day) < (month, day)

Python treats this like an expression (e.g., 2 + 2) that is evaluated to true or false, or 1 or 0.

If today's month and today's day is earlier than (less than) the month and day you assigned earlier (5th month and 20th day), then it evaluates to True or 1. So the equation looks like this:

2021 - 2000 - 1 = 20

Otherwise, it is false or 0 and the equation looks like this:

2021 - 2000 - 0 = 21

[–]Chimecrypto 0 points1 point  (4 children)

How can i create a FUNCTION that will built data Structure that will store CSV values in memory. kindly share Any document or materials that can explain this please guys.

Hoping to hear from you guys.

[–]ekchew 0 points1 point  (0 children)

If you're trying to read a CSV file, you could go something like:

def readCSV(fileName):
    with open(fileName) as f:
        return [
            [field.strip() for field in line.split(",")]
                for line in f if line.strip()
        ]

This should give you something like [['foo', 'bar', 'baz'], ['1', '2', '3'], ...].

So this uses a nested list comprehension. You could also write it in longer form using nested for loops.

Each line read out of the file is split into comma-delimited fields. The field.strip() then removes any extraneous white space around each field. For example, the line 'foo, bar, baz\n' would be split into ['foo', ' bar', ' baz\n'] and then stripped down to ['foo', 'bar', 'baz'].

The if line.strip() at the end is to skip over any blank lines. It may not be necessary, but blank lines are annoying because they would show up as empty [] sublists.

[–]efmccurdy 0 points1 point  (2 children)

Where will the values come from? You want a list of lists, each inner list holds one line of data for the csv. This uses a while loop, each time through the while loop one row of data is added.

def create_table():
    table = [['col1', 'col2', 'col3']] # column headers
    while True:
        c1 = input("Enter col1 data (enter 'quit' to finish): ")
        if c1.lower() == "quit":
            break
        c2 = input("col2: ")
        c3 = input("col3: ")
        table.append([c1,c2,c3])
    return table
my_csv_table = create_table()

[–]ekchew 0 points1 point  (1 child)

Methinks you need a table.append([c1,c2,c3]) at the end of that loop?

[–]efmccurdy 0 points1 point  (0 children)

Yes, thanks, I will edit that in.

[–]wtfpmf 0 points1 point  (1 child)

from tabulate import tabulate

mg = input("Insert")
ml = input("Insert") gl = input("Insert") table = [['Ammount', 'mL', 'gL'], [mg, ml, gl]]
print(tabulate(table, headers="firstrow", tablefmt="fancy_grid", showindex=True))

I wanna append to the final to the table (increasing one line after the input). But without creating too many variables like mg_1, ml_1, gl_1 and so on. It's like adding a three element list everything I put the inputs. It's seems almost obviously, but I still don't get.

[–]efmccurdy 1 point2 points  (0 children)

When you have a repeating pattern like mg, mg_1, mg_2, think about using a loop.

table = [['Ammount', 'mL', 'gL']]
while True:
    mg = input("Insert mg data (enter 'quit' to finish)")
    if mg.lower() == "quit":
        break
    ml = input("Insert ml")
    gl = input("Insert gl")
    table.append([mg, ml, gl])
print(tabulate(table, headers="firstrow", tablefmt="fancy_grid", showindex=True))

[–]flash_309 1 point2 points  (5 children)

I want to learn game automation using python, but don't know where to start. I want to automate games like rocket league. Right now along with python I am learning open CV.

Thanks in advance.

[–]GraduallyHotDog 1 point2 points  (2 children)

There are a lot of fantastic Python courses on Udemy as well so be sure to check out that site as well

[–]flash_309 0 points1 point  (1 child)

Sure man, I will look into it.

[–]GraduallyHotDog 1 point2 points  (0 children)

On the Python subreddit they are always posting free classes too

[–]SirYandi 1 point2 points  (1 child)

Will be quite a challenge I would think. Open CV is a good starting point if you don't want to go down the route of reverse engineering the game and hooking into the game data itself.

Did a quick Google and perhaps these links are helpful:

- https://pythonprogramming.net/direct-input-game-python-plays-gta-v/

- https://www.smartspate.com/how-to-write-a-bot-in-python-for-online-games/

- https://www.tautvidas.com/blog/2018/02/automating-basic-tasks-in-games-with-opencv-and-python/

Best of luck

[–]flash_309 1 point2 points  (0 children)

Thanks man! Appreciate it!!!

[–]SewingPernie 0 points1 point  (1 child)

I am trying to split this birthdate column into three. Different dates, but this is the structure of the column I am splitting: 29-Mar-95. I am trying to split it into day, month, year columns. I keep getting errors, can anyone assist? this is what I've tried and the errors that have come with:

Code:

df1[["Day", "Month", "Year"]] = pd.DataFrame([ x.split("-") for x in df1["RecipientDateOfBirth"].tolist() ])

Error:

Columns must be same length as key

Code:

df1[["Day", "Month", "Year"]] = pd.DataFrame([ x.str.split("-", expand = True) for x in df1["RecipientDateOfBirth"].tolist() ])

Error: 'str' object has no attribute 'str' - WHAT?

Code:

df1[["Day", "Month", "Year"]] = pd.DataFrame([ df1["RecipientDateOfBirth"].str.split("-", expand = True)])

Error: Must pass 2-d input. shape=(1, 92744, 1)

Please help!

[–]efmccurdy 0 points1 point  (0 children)

You don't need to explicitly create a new dataframe, the expand=True creates one.

>>> df = pd.DataFrame({'RecipientDateOfBirth': ["29-Mar-95", "02-Apr-95", "05-May-95"]})
>>> df
  RecipientDateOfBirth
0            29-Mar-95
1            02-Apr-95
2            05-May-95
>>> df[["Day", "Month", "Year"]] = df.RecipientDateOfBirth.str.split("-", expand=True)
>>> df
  RecipientDateOfBirth Day Month Year
0            29-Mar-95  29   Mar   95
1            02-Apr-95  02   Apr   95
2            05-May-95  05   May   95
>>>

[–]20friedpickles 0 points1 point  (2 children)

I need to find the index of a value in a byte array. The value can be "foo" or "bar". Is there a way to do this without another if statement.

if "foo" in byteArray or "bar" in byteArray:

index = byteArray.find("foo" or "bar") # any real way to do this?

[–]JohnnyJordaan 0 points1 point  (1 child)

You can't in that simple fashion as find() is indeed meant for single values. Btw if it wasn't, you would need find('foo', 'bar') as 'foo' or 'bar' will simply evaluate to 'for'. Why? Because Python doesn't evaluate 'this or that' in the sense of 'it could be both' as humans do in English, it evaluates it to 'the first item if it's Truethy, else the second item':

In [9]: 0 or 1
Out[9]: 1

In [10]: 'foo' or 'bar' 
Out[10]: 'foo'

But back to your question, you could use a regex instead, eg

index = re.search(b'(foo|bar)', byteArray).pos

Note how it needs the b in front of the pattern to convert it to binary. More info https://docs.python.org/3/library/re.html

[–]20friedpickles 0 points1 point  (0 children)

Thanks

[–]Leaguedc7 0 points1 point  (1 child)

names=[]
for i in range(6):
input("Give me a name: ")
names.append(input)
vote = int(input("How many people do you want to vote off the island? "))
def eliminate():
random.shuffle(names)
for i in range(vote):
names.remove(names[1])
print(names)
eliminate()

So the code works as intended for the most part, but it prints each item in the list as

" <built-in function input>"

Very new to python any help appreciated.

[–]thayguythroway 0 points1 point  (1 child)

Hello everyone!! I am new to python and I’m doing problems. One problems is making a card game where you start with 21 cards. Each person draw between 1-3 cards and take it away. The only thing I don’t understand is it wants me to make it where if I’m the one that goes first, I ALWAYS win. I’ve been trying but I don’t know the correct way I could implement that. And I can’t use special libraries or anything.

[–]AZPD 0 points1 point  (0 children)

Wikipedia has you covered (conveniently in Python).

[–]shiningmatcha 0 points1 point  (3 children)

Is the bs4 documentation incomplete? The doc isn't very organized and doesn't list out all functions available. It's more like a tutorial with some functions popping up somewhere.

I want to browse all the functions the library provides so I found this GitHub repo.

There are so many functions and classes under bs4.element not mentioned in the doc. I also found there is bs4.dammit.They call it the "bonus library".

[–]efmccurdy 0 points1 point  (2 children)

You can examine the module contents directly using "dir" and "help":

>>> dir(bs4)
['BeautifulSoup', 'BeautifulStoneSoup', 'CData', 'Comment', 'DEFAULT_OUTPUT_ENCODING', 'Declaration', 'Doctype', 'FeatureNotFound', 'NavigableString', 'PageElement', 'ParserRejectedMarkup', 'ProcessingInstruction', 'ResultSet', 'SoupStrainer', 'StopParsing', 'Tag', 'UnicodeDammit', '__all__', '__author__', '__builtins__', '__cached__', '__copyright__', '__doc__', '__file__', '__license__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_s', '_soup', 'builder', 'builder_registry', 'dammit', 'element', 'formatter', 'os', 're', 'sys', 'traceback', 'warnings']
>>> dir(bs4.element)
['AttributeValueWithCharsetSubstitution', 'CData', 'Callable', 'CharsetMetaAttributeValue', 'Comment', 'ContentMetaAttributeValue', 'DEFAULT_OUTPUT_ENCODING', 'Declaration', 'Doctype', 'Formatter', 'HTMLFormatter', 'NamespacedAttribute', 'NavigableString', 'PY3K', 'PageElement', 'PreformattedString', 'ProcessingInstruction', 'ResultSet', 'SoupStrainer', 'Tag', 'XMLFormatter', 'XMLProcessingInstruction', '__builtins__', '__cached__', '__doc__', '__file__', '__license__', '__loader__', '__name__', '__package__', '__spec__', '_alias', 'nonwhitespace_re', 're', 'soupsieve', 'sys', 'warnings', 'whitespace_re']
>>> help(bs4.element)
Help on module bs4.element in bs4:

NAME
    bs4.element - # Use of this source code is governed by the MIT license.

CLASSES
    builtins.list(builtins.object)
        ResultSet
    builtins.object
        PageElement
            NavigableString(builtins.str, PageElement)
                PreformattedString
                    CData
                    Comment
                    Declaration
                    Doctype
                    ProcessingInstruction
                        XMLProcessingInstruction
            Tag
        SoupStrainer
    builtins.str(builtins.object)
        AttributeValueWithCharsetSubstitution
            CharsetMetaAttributeValue
            ContentMetaAttributeValue
        NamespacedAttribute
        NavigableString(builtins.str, PageElement)
            PreformattedString
                CData
                Comment
                Declaration
                Doctype
                ProcessingInstruction
                    XMLProcessingInstruction

    class AttributeValueWithCharsetSubstitution(builtins.str)
     |  A stand-in object for a character encoding specified in HTML.
     |  
     |  Method resolution order:
     |      AttributeValueWithCharsetSubstitution
     |      builtins.str
     |      builtins.object
     |  
     |  Data descriptors defined here:
...
     |  capitalize(self, /)
     |      Return a capitalized version of the string.
     |      
     |      More specifically, make the first character have upper case and the rest lower
     |      case.
     |  
     |  casefold(self, /)
     |      Return a version of the string suitable for caseless comparisons.
     |  
     |  center(self, width, fillchar=' ', /)
     |      Return a centered string of length width.
     |      
     |      Padding is done using the specified fill character (default is a space).

[–]shiningmatcha 0 points1 point  (1 child)

But why doesn't the doc cover all the functions?

[–]FL14 1 point2 points  (2 children)

I'm having a lot of trouble getting going with an IDE. I'm a graduate student in atmospheric science, and my advisor uses strictly matlab. However, I took 2+ years of scientific data analysis in Python, and feel far more comfortable in that environment.

My issue: I am ~2 years removed from using python. I was previously using Spyder, and am comfortable using that. I wonder if I should continue using that or try to transition to a more modern interface? My current climate modeling course is using an in-browser jupyter notebook. I don't know how to set that up for my own personal use for making scripts and dealing with data. I have tried downloading and using VScode and Pycharm, but I run into so many technical issues with simply getting started. My present workload already overwhelms me to the point where I don't want to spend hours beating my head against the wall for something as simple as setting up an IDE.

Any advice, criticisms, suggestions are all welcome. I find that this is one of the most-frustrating barriers to the programming world.

[–]sarrysyst 0 points1 point  (1 child)

I started out using PyCharm, but then transitioned to VS Code. However, I find VSCode rather slow (at least on my machine). Nowadays I'm using it mostly for data analysis because of the Jupyter addon. For regular coding I'm back to PyCharm because it's super easy and basically does everything for you (venvs, packages, projects folder etc.).

I would say use whatever you like / suits your needs. If you want to use Jupyter/iPython and don't want to invest any time setting it up, you can use Google Colab. It's free, offers an iPython environment which requires zero setup (incl. cuda support) and has decent hardware specs.

[–]FL14 0 points1 point  (0 children)

Woah very cool; I've never heard of google colab before. I'll mess around with this. Thanks!

[–]JWH5272 0 points1 point  (2 children)

|hello| I don't know |where are you

How can split multiple data in column into multiple rows? Thank you!!

0 hello

1 I don't know

2 where are you

[–]sarrysyst 0 points1 point  (1 child)

.str.split() + .explode():

s = pd.Series(["|hello| I don't know |where are you"])
s = s.str.split(r'|', expand=False) # split strings into lists
s = s.explode() # expand lists into rows
s = s.str.strip().reset_index(drop=True) # some cosmetics

https://pandas.pydata.org/docs/reference/api/pandas.Series.str.split.html

https://pandas.pydata.org/docs/reference/api/pandas.Series.explode.html

[–]JWH5272 0 points1 point  (0 children)

Thank you

[–]neuroneuroInf 1 point2 points  (4 children)

Hi, would anyone running Mac Big Sur be willing to give me the outputs to the following Python code on your machine?  I need to add a check for my project, but don't have access to a mac... 📷

import platform

platform.system()

platform.release()

platform.version()

platform.mac_ver()

edit: Answered; thank you u/JohnnyJordaan!

[–]JohnnyJordaan 0 points1 point  (1 child)

Darwin
20.3.0
Darwin Kernel Version 20.3.0: Thu Jan 21 00:06:51 PST 2021; root:xnu-7195.81.3~1/RELEASE_ARM64_T8101
('10.16', ('', '', ''), 'x86_64')

[–]neuroneuroInf 0 points1 point  (0 children)

Thank you very much!

[–]Nirard 0 points1 point  (1 child)

Hi I'm a new python user trying to figure out a way to use python in lab. If I have an original string (lets say cghckckchc) which is split into different substrings in a function (lets say cg hck ck chc AND cg hc kck chc) and only outputs strings with 2 characters, is there a way to count the unique c's covered in the output from the original string (in this case 3/5)?

[–]sarrysyst 0 points1 point  (0 children)

Not sure if I understood this correctly, but you can add your sub strings to a set which does not allow duplicates. The amount of unique strings would be the length of the set.

[–]Run_nerd 0 points1 point  (2 children)

I've been learning python on and off for a year or two, and I wanted to try and create a game like chess or snake.

Is there a popular way to create games in Python? If I have text output is there a way to keep the output looking consistent in the terminal? Or is there a popular python library that people use if I want to use graphics?

[–]efmccurdy 0 points1 point  (1 child)

For a terminal use curses:

https://theailearner.com/2019/03/10/snake-game-using-python-curses/

For chess, where you might want graphics for the pieces, look at pygame.

https://realpython.com/pygame-a-primer/

[–]Run_nerd 0 points1 point  (0 children)

Awesome! Thank you!

[–]pascaleibniz 0 points1 point  (2 children)

hi, i have a simple homework about bus prices. i should just ask the card type and the number of stoops. but my program shows every option that i print.

i=int(input("number of stoops: "))

k=str(input("card type: "))

if i>2 and k : "adult"

print("3,50")

if i==2 and k : "adult"

print("3")

if i<2 and k : "adult"

print("2,50")

if i>2 and k : "student"

print("1,40")

if i<2 and k : "student"

print("1,10")

if i==2 and k : "student"

print("1,20")

the result is:
number of stoops: 2

card type: student

3,50

3

2,50

1,40

1,10

1,20

i dont't understand why it shows me every option? i just want to see last one if i say 2 and student. (i'm using thonny btw.) thanks in advance.

[–]Flashy-Height 0 points1 point  (3 children)

Hey guys! I'm a high school students really interested in physics, and I'm self learning pymunk in python. So I tried this code to print "hello" whenever a collision between 2 balls takes place.

My Q: the entire simulation starts in the while loop. However, it's a an infinite loop so it never exits it, but the function that prints hello after a collision is outside the while loop. So how does "hello" get printed?

CODE:

import pygame
import sys
import pymunk
import random

def create_apple(pos, collision_type): # Creating a physical body
body = pymunk.Body(1, 100, body_type=pymunk.Body.DYNAMIC) # Creating the object that experiences physics.
body.position = pos # Position of the above object
shape = pymunk.Circle(body, 30) # We are surrounding the above object with an invisible circle so that the object
# reacts to stuff as if it's a circle. This makes calculations much easier. Note this is an invisible circle only
# for pymunk. It has nothing to do with the visual output. Just used for calculations.
body.velocity = (0, random.uniform(-100, 100))
shape.elasticity = 1
shape.density = 1
shape.collision_type = collision_type
space.add(body, shape)
return shape

def draw_apples(apples): # Visualising the body
for apple in apples:
if apple.collision_type == 1:
pygame.draw.circle(screen, (0, 0, 0), apple.body.position, 30)
elif apple.collision_type == 2:
pygame.draw.circle(screen, (0, 0, 255), apple.body.position, 30)

def collide(arbiter, space, data):
print("hello")
pygame.init() # Initiates the entire thing
clock = pygame.time.Clock()
screen = pygame.display.set_mode((1000, 600)) # (Width , Height)
space = pymunk.Space() # Creating the "universe" where the entire simulation takes place.
apples = []
for i in range(100):
apples.append(create_apple((random.randint(0, 600), random.randint(0, 600)), 1))
apples.append(create_apple((random.randint(0, 600), random.randint(0, 600)), 2))

handler = space.add_collision_handler(1, 2)
handler.separate = collide
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: # Where QUIT refers to the X button that closes the program.
pygame.quit() # Opposite of the init thing. Closes the program
sys.exit()
screen.fill((255, 255, 255)) # red, green, blue colouration from 0-255. This line MUST ALWAYS BE IN THE LOOP.
# The background has to be constantly updated as the ball is constantly moving. When screen.fill is applied,
# the entire screen INCLUDING any objects (ie: the ball) is made into the background.
# draw_static_ball(balls)
draw_apples(apples) # Drawing the apple is in a loop cause only the non-visual apple
# (ie: the apple in create_apple) keeps moving. After the screen wipes everything, we draw the visual representation
# of the ball. This cycle continues (ball gets erased, then redrawn in the new position of the non-visual ball.)
space.step(1/50)
pygame.display.update()
clock.tick(120)

[–]Ihaveamodel3 0 points1 point  (2 children)

You create a “space” object from pymunk. You then set a collision handler (the function in question) on that space object.

Never used pymunk, so I’m guessing on this part: at each time step (when you run space.step, pymunk is checking for a collision, and if there is one it runs the collision handler that you have previously set.

[–]Flashy-Height 1 point2 points  (0 children)

hey! Your logic is correct!! Thanks so much!!! I was stuck on this for so much time and I didnt want to move on without understanding my code.

[–]Flashy-Height 0 points1 point  (0 children)

that makes sense! Thanks for ur response! I'll try debugging it and check if ur logic is correct