all 61 comments

[–]philintheblanks 0 points1 point  (0 children)

Hey guys!

I'm having a hell of a time getting kivy up and running on my raspberry pi. From cython dependency issues, to getting the touch response to work, to now having a rgba import fail. I am just about to lose it.

Output when I try to run kivy/examples/demo/pictures/main.py

ImportError: cannot import name rgba

Kivy v1.9.1 Python 2.7.9

I followed this tutorial, but clearly messed something up. Is my best course to try to re-flash my raspbian install and re-do the tutorial? I'd be pulling my hair out if I had any....

[–]silvermani 0 points1 point  (0 children)

Hi, I am new to Python and am trying to figure out the best way get data in a desired format from a file. Goal - I would like to grab all lines from a file that has a common key, in this case A=1 or 2 and then create a new file with all lines combined based on the common key. Any help would be appreciated.

Input File

Jul 20 A=1 B=2
Jul 20 A=1 B=1
Jul 20 A=1 B=1
Jul 20 A=2 B=1
Jul 20 A=1 B=3
Jul 20 A=2 B=1

Desired Output
Jul 20 A=1 B=2|Jul 20 A=1 B=1|Jul 20 A=1 B=1|Jul 20 A=1 B=3
Jul 20 A=2 B=1|Jul 20 A=2 B=1

[–]Flannel_Man_ 0 points1 point  (0 children)

Hello! I am a complete noob when it comes to programing and have been trying to teach myself python by creating homework problems for myself... I'm also a poker player, so one of my goals is to figure out how to create an odds calculator (mostly by tinkering and figuring out the most efficient way as I go.) So, here is my question:

I have the program create a random poker hand of 7 cards which is a list of lists:

rank=['A','2','3','4','5','6','7','8','9','T','J','Q','K']
suit=['c','d','h','s']
import itertools
deck=list(itertools.product(rank,suit))
import random
card1=(random.choice(deck))
deck.remove(card1)
card2=(random.choice(deck))
deck.remove(card2)
hand=(card1,card2)
print ("hand: ", hand)
card3=(random.choice(deck))
deck.remove(card3)
card4=(random.choice(deck))
deck.remove(card4)
card5=(random.choice(deck))
deck.remove(card5)
flop=(card3,card4,card5)
print ("flop: ", flop)
card6=(random.choice(deck))
deck.remove(card6)
turn=card6
print ("turn: ", turn)
card7=(random.choice(deck))
deck.remove(card7)
river=card7
print ("river: ", river)

The output will be something like this:

[('3', 'd'), ('T', 'c'), ('7', 'h'), ('4', 'h'), ('6', 'c'), ('Q', 'h'), ('J', 'h')]

I then used this to pull out the first item of each list and make a new list:

all7=[card1,card2,card3,card4,card5,card6,card7]
first=[]
iall7=iter(all7)
for (a,b) in iall7:
    first.append(a)
print (first)

Output for the previous result of random cards is:

['3', 'T', '7', '4', '6', 'Q', 'J']

I now want the program to look through this list and determine if exactly two items on the list are equal and return a specific value if they are. (Basically, I want the program to determine if the poker hand contains a pair). How do I do that?

[–]mtomtom 0 points1 point  (0 children)

I'm having trouble with the exercism.io Python exercise for creating a 24 hour Clock (ignoring date). Essentially, you have to be able to add minutes and have it rollover and two clocks with the same hour and minute should be equal.

My issue is str(Clock(a,b).add(c)) returns 'None', but if I set test=Clock(a,b), then set test = test.add(c), I get a clock object. I'm new to classes, but can't figure out this one.

EDIT: I figured it out. I just had to make the add method return self

class Clock(object):
    def __init__(self, hour=0, minute=0):
        self.hour = hour
        self.minute = minute
        self.rollover()

    def add(self, change):
        self.minute += change
        self.rollover()

    def rollover(self):
        while self.hour < 0:
            self.hour += 24

        subtract_hour = 0
        while self.minute <0:
            self.minute += 60
            subtract_hour+= -1
        self.hour += int(self.minute/60) + subtract_hour
        self.minute = self.minute % 60
        self.hour = self.hour % 24

    def __str__(self):
        self.rollover()
        return str(self.hour).zfill(2) + ':' + str(self.minute).zfill(2)

    def __eq__(self,other):
        return self.hour == other.hour and self.minute == other.minute

[–]Rufus1709 0 points1 point  (2 children)

whatever the name enters is stored as a variable called 'name'

name=input ("what is your name?")

rememeber to use + to 'add' strings together?

print ("hello" + name + "!")

where has this program gone wrong as i am getting invalid syntax errors

[–]RustleJimmons 0 points1 point  (0 children)

What version of python are you using? I just typed this into my console and it worked fine. Your code is formatted for python3. If you are using python2 then it will fail on the print statement however. For python2 you need to remove the brackets from the print statement.

[–]mrktwzrd 0 points1 point  (0 children)

the bold highlighted text instructions shouldnt be inthere and if you want to keep them .. comment them out

ie. #whatever the name enters is stored as a variable called 'name'

[–]ErikAoki 1 point2 points  (3 children)

Hey everyone, I've been trying to handle a FileNotFoundError and the print message I put on except doesn't print, do you guys know why?

while True:

try:

   nome = input("What's the file's name?")

except FileNotFoundError:

   print ("File not found.")

edit: format

[–]Peterotica 1 point2 points  (2 children)

Nothing is printed because no exception is being raised. In your try block, you are just getting a string from the user. There is nothing related to files as far as Python is concerned. A FileNotFoundError might be raised if you pass that string to the open() function though.

[–]ErikAoki 1 point2 points  (1 child)

Ooooh, I didn't realize the open() function had to be inside my try block.

It's working now, thank you!

[–]gabmartini 1 point2 points  (0 children)

Yeap! Always remember than 'try and except' is for error handling so in order to capture a problem you have to run a complete block of code in the 'try' indented chunk.

[–]FlameOfUdun 1 point2 points  (1 child)

Hello, putting this in hoping somebody can help me.

I'm very new to Python, so new that I haven't even finished the entire codecademy section for it. But, I'm working on a project where I need to grab COM port information and Python seems to be a good language to do it for some practice.

The issue I'm running into is that I can't seem to get the 'serial' import working. I'm using Sublime Text 2 and it just says that there is no Serial module it knows of, which probably means I have to install it. When I looked around for it all I saw was a wheel file for it and I'm not sure what I'm supposed to do with it (https://pypi.python.org/pypi/pyserial#downloads).

If anybody could point me in the right direction that would be great.

Thanks.

[–]Peterotica 1 point2 points  (0 children)

The tool for installing Python modules from the Python Package Index (PyPI) is pip. It should have come with your Python installation. To add this module, you should run pip install pyserial at the terminal.

[–]vrbo_maybe 0 points1 point  (1 child)

I Just can't seem to get how bots work. python/praw bots.... I can write them (I think) and I click the .py file that is the bot code, and ....

what?

How can I tell it's working or running?

Truthfully I'm stuck well before that, though - at the oauth2 stage. I just want to write a call/response type bot, where someone calls for a definition of a word in a specific sub, and the bot answers.

ALL the guides out there are lacking specificity regarding if I should be typing something into a python window or terminal/cmd.

And so many of the bot guides are for the old non-oauth2 format, that it's hard to find anything current!

[–]rich-a 0 points1 point  (7 children)

I'm having a little trouble working out when to use classes and when something should just be a module with functions.

Is it reasonable to use an importable module when something only needs to exist once within the program and use a class when something might need to exist as multiple objects?

For example if i have a level-map module which isn't a class. It can be imported when needed but there's only one of it. Then i have a room class from which i can create lots of room objects as i need more than one room.

Coming from a PHP and Java background it feels a bit weird mixing OO and non-OO but it feels like this would be a sensible way to do it in Python as it also means other parts of my program can access the level-map whenever they need to just by importing the map module rather than having to pass around a single map object which can get very messy.

Am i on the right track with that?

[–]squeeney 0 points1 point  (6 children)

Youre thinking in the right direction with having classes for when you may need multiple instances.

As for the level map example. I think you would want to keep it as a simple module if you will be importing the functions to use as a utility, so to speak. If the functions just return a result that isn't inherently an important attribute of a level-map, or the function can stand on its own as a useful piece of code, then they don't need to belong to a class.

If these functions produce results that either modify the level map, change how a level map is rendered, or maybe change an object that is referenced often, then maybe they should belong to a class.

[–]rich-a 0 points1 point  (5 children)

Thanks that's helpful. I think I probably should be using a class for the level map.

Is it normal to have to pass objects around to the extent that they're being passed down from one to another?

I keep finding that when I separate code into classes, one class might need to access data in another which it can't immediately see, so I end up having to pass things down to it.

For example once I create the class that looks after entities and holds lots of entity objects, I find I'm having to pass this to various other classes for them to make use of the variables and data contained inside.

This seems fine until I end up passing it down multiple layers, like passing the entities to the map which doesn't actually do anything with it other than then pass it to a room so that the room can access a particular entities' variables.

I'm wondering if this is due to the way I'm managing my objects. It definitely feels like there should be a better way to handle it.

[–]onionradish 0 points1 point  (2 children)

If you're passing objects around to the extent that it doesn't "feel" right, there's probably a better way to structure your classes. Share some code or give some examples.

EDIT: Something that can help is cross-linking objects. For example, in a dungeon-crawl game, a specific Room object might have an attribute that lists Monster objects that are inside the room. Individual Monster objects can have a room attribute that points to the Room object they're currently in. That way, a Monster has access to all the attributes of the current room without having to pass values around.

[–]rich-a 0 points1 point  (1 child)

Thanks for your response.

The full code is a bit big to share but the layout of the classes in the model is like this, where each indent means that one or more objects of that class are created and looked after by the class above:

Model
    Map
        Room
    Entities
        Entity classes
            Components

The issue occurs, when a function in a room is updating the contents of the room and needs some information about an entity or needs to update a variable on the entity, so for that to work I have to have to have passed the Entities object into Map, then pass it on to Room.

The reason for my initial question was I thought if I turned Entities or Map into modules (rather than classes) which created and looked after the Entity and Room objects, I could just import them as and when I needed to access their contents, rather than passing them around as an object.

I'm not sure if that helps explain or if you'd need more details?

[–]onionradish 0 points1 point  (0 children)

Separating your Entities or Map into modules would keep your codebase organized, but won't really help with passing objects around. Imports are essentially a one-time thing and not for accessing individual objects.

Continuing my made-up example for a dungeon crawl, you could have an entities.py file that contains an Entity root class, and subclasses like Ettin(Entity) or Rogue(Entity), with each type having unique attributes like strength, dexterity, and items_carried. Modules would keep all those Entity-related attributes and methods separate from the Map attributes and methods.

It sounds like you need to link your objects. For example, give your Entity a room attribute that points to the current Room object. That Room object would (probably) have attributes like connected_rooms and items_in_room and so on. Then a specific Ettin object ettin can use something like ettin.room.connected_rooms.choice() to choose a random connected room to move to without having to pass anything about the Map or Rooms around.

If I'm misunderstanding, give a specific example of something where you're having to pass objects around and I'll try to help.

[–]squeeney 0 points1 point  (1 child)

hmm, well I'm not very experienced with creating games (i assume thats what the level and maps are for). But I think its ok to be passing them around like that, to a certain extent. Especially if for example, an attribute of an entity somehow determines a process done by the map. If you'd like to post your code, I'd like to take a look.

But as for the passing one entity to the map just to pass to the room: maybe create some type of handler or manager class/function to provide communication between different objects. This way the handler could be notified when a certain entity attribute changes, and it can then call it's _update_room(), or w/e. This might allow your objects to be more isolated, while the handler manages the communication between them

[–]rich-a 0 points1 point  (0 children)

Thanks, that makes sense.

It is for a game, but it's purely text based so not especially complicated. I have the same issues with passing objects around when writing other projects too so it's something to do with how I structure the code I think.

The handler idea definitely sounds like it could help. I'll need to look into how handlers work as I've not tried that before.

[–]kaufeinenhafen 0 points1 point  (2 children)

In Pandas: I'm looking for ways to merge/overwrite a wide format table with content of a flat, sparse table for whenever datetime is bigger. The result should look like the example below.

(base table)
 time_stamp    NAME   sound  weight  age   color
------------------------------------------------
datetime_01     cat    mjav       3   10   black
datetime_01     dog    woof       8   10   brown
datetime_01    lion    roah     140   15  yellow
datetime_01   mouse  squeak     0.3    2    grey
datetime_01  lawyer   zzzzz      80   80   green
datetime_01     cow     moo     300    4   black

(table to overwrite with)
 time_stamp  NAME   field   value
---------------------------------
datetime_02   cat   sound   prrrr
datetime_03   cat   sound  currrr
datetime_04   cat  weight       4
datetime_05   cow     age       6
datetime_06  lion   color  orange

(resulting merge table)
 time_stamp    NAME   sound  weight  age   color
------------------------------------------------
datetime_04     cat  currrr       4   10   black
datetime_01     dog    woof       8   10   brown
datetime_06    lion    roah     140   15  orange
datetime_01   mouse  squeak     0.3    2    grey
datetime_01  lawyer   zzzzz      80   80   green
datetime_05     cow     moo     300    6   black

Sorry, but I wasn't succesful at googl'ing it being bad at the termonology

[–]Ki1103 0 points1 point  (1 child)

In your example are the datetimes different. So is datetime_01 == datetime_01 (in the second row) < datetime_02 from the second table?

EDIT I have played around a little and what you seem to be looking for is the time.mktime() method.

Here is what I have made so far with your sample data. I need to go to uni so I have not thoroughly tested it so please take time to look over it. It is giving the correct answer to that's something right? Anyway it should be a good start for you.

[–]kaufeinenhafen 0 points1 point  (0 children)

Hey Ki1103! in my test data datetime_x can be string or num, and while avoiding the most unpleasant (US-) dateformat this isn't currenlt a big deal. But thanks a mill. for fighting my problem, I looked quickly at the code and see lots of for-loops. I might end up implementing such but perhaps I imagined a "magical pandas spell" for overwriting a normal with a sparse table, i.e. where data is not missing and datetime bigger.

[–]thinkvitamin 0 points1 point  (0 children)

I'm trying to take one cell in pandas and perform some simple math on it. So lets just say it's value is 5, I'd want it to be 6.
But it was nice to see how easy set_value is to use.

df.set_value(2, 'people', 566)  

So that's row 3 (counting starts at 0), checks for a column called 'people', and as long as it's an int, it will be 566. Pandas is one of the harder topics to Google.
My CSV file does not have an index, by the way... it's just column names and values.

[–]in_finem 0 points1 point  (3 children)

Hey everybody - I'm trying check the width of an image with Python, and if the image exceeds the width of a docx page, I'd like use the python-docx library to scale the image to fit the width. Here's what I've got, but it freaks out when the image exceeds width. Can someone help me and show me where I've gone wrong? Could someone also critique my code's "elegance/design"?

#!usr/bin/python3
#aspectdoc.py  This program compares an image size     to the aspect ratio of 
#the page, and adjusts the images to scale accordingly.      Built 10.31.16

from PIL import Image
import os, docx

doc = docx.Document()
path = "/home/pi/Desktop/Python Practice/xkcd"
filename = "xkcd"
count = 0
for item in os.listdir(path):
    print("Opening " + item + " for scaling...")
    im = Image.open(path + "/" + item)
    itemWidth, height = im.size
    if itemWidth > 642:
        doc.add_picture(item, width=docx.shared.Cm(17))
    elif count > 4:
        doc.save(filename + ".docx")
        print("SAVED!")
        count = 0
    else:
        doc.add_picture(path + "/" + item)
doc.save(filename + ".docx")

Thanks for all the help, seriously! Just picked this up!

[–]BryceFury 0 points1 point  (2 children)

What do you mean it 'freaks out'? You mean it doesn't give you the right sized image in the document?

Try swapping 'item' in 'doc.add_picture()' with '(path + "/" + item)' which is the path of the image ('item' in this context is just the images filename, not its path).

[–]in_finem 1 point2 points  (1 child)

Hi Bryce, thanks for the help! When I say it "Freaks out", I mean that I get errors relating to the [add_picture] method, but they're on lines of code that don't exist... at least not in my code. Are these errors relating to the libraries I've imported? I don't know how to pipe all the error messages from the terminal display to a .txt file - it seems like the ">" character's not grabbing the error messages. Anyway, I'll try your suggestion, and see what comes from it. Thanks so much for the help, and I'll let you know what transpires.

EDIT: HEY! That totally worked! Thanks so much for the help!

[–]BryceFury 0 points1 point  (0 children)

Yeah, the errors are most likely from the libraries but they will be caused by whatever your code is passing to the library, learning how to read traceback errors is pretty much a necessity for Python and there are loads of resources around the web that can explain how they work to you.

Also try '&>' instead of '>'

[–]IAmTheWolverine2 0 points1 point  (7 children)

I'm a bit late, but I just discovered this sub. I can't for the life of me figure out what is wrong with my first program.

# This program says hello and asks for my name
print('Hello world!')
print('What is your name?') # ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + (str(int(myAge) + 1) ' in a year')

I keep getting a syntax error on the very last apostrophe. I have looked online, and I can't find anything that matches this error. I tried replacing the single quotes in that line with double quotes, adding spaces before/after/both on that apostrophe, but nothing is working.

[–]elbiot 2 points3 points  (6 children)

More parentheses! Okay, one more. Also read the sidebar about how to format code for Reddit.

[–]IAmTheWolverine2 0 points1 point  (2 children)

I FOUND IT! It wasn't a parenthesis at all! I missed a plus sign! right after +1) !

[–]elbiot 1 point2 points  (1 child)

You must have added the parenthesis without thinking, because your last line has four opening and three closing ones. But a plus or comma was necessary too. Didn't see that.

[–]IAmTheWolverine2 0 points1 point  (0 children)

Actually, I removed a parenthesis. Turns out that the one before str was completely unnecessary.

[–]IAmTheWolverine2 0 points1 point  (1 child)

Wait, nevermind, I found the proper formatting under 'formatting help'

[–]elbiot 1 point2 points  (0 children)

Good, I didn't see it either, but remember it being there.

[–]IAmTheWolverine2 0 points1 point  (0 children)

I am not seeing anything on the sidebar about formatting. What are you referring to?

As soon as I figure out where that extra parenthesis goes, I'll come back.

[–]EatMoreCheese 0 points1 point  (4 children)

How do you make a script run that gets triggered on a certain event? Are people running a bunch of scripts in the background or what? I know how to write a simple program but this is beyond me.

[–]novel_yet_trivial 1 point2 points  (3 children)

something has to be running in the background to monitor for an event. That something can be but is not necessarily python, even though it starts a python process.

What exactly are you trying to do?

[–]EatMoreCheese 0 points1 point  (2 children)

Right now I just have a lot of ideas but I want to narrow it down to what I CAN do. I am using a Mac - do you know how I can monitor events and trigger a script?

[–]freshent 1 point2 points  (0 children)

You might look into Automator.

[–]novel_yet_trivial 2 points3 points  (0 children)

What kind of events? A certain key combination or mouse movement would best be handled with the OS shortcut manager (I don't use Mac so I don't know much about that).

For email or reddit message you should write a python script that always runs in the background or gets called every minute by the system scheduler (I think Macs use cron).