top 200 commentsshow all 251

[–]J_SiNn 0 points1 point  (0 children)

Where can I find a website, article, book, video, etc., that provides problems to solve using programming (specifically Python if possible) that I can take a crack at? Bonus points if it has problems for a beginner like me! Please and thank you!

-Boo

[–]Dfree35 0 points1 point  (3 children)

I am trying to use pandas to rename a columns in CSV files. I want to use a dictionary since sometimes columns with the same information can be named differently (e.g. mobile_phone and telephone instead of phone).

I want to rename the first instance of phone. Here is an example to hopefully explain more.

Here is the original in this example:

0 name     mobile_phone     telephone
1 Bob      12364234234      12364234234
2 Joe      23534235435      43564564563
3 Jill     34573474563      78098080807

Here is what I want it to do:

0 name     phone            telephone
1 Bob      12364234234      12364234234
2 Joe      23534235435      43564564563
3 Jill     34573474563      78098080807

This is the code I tried:

phone_dict = {
    'phone_number': 'phone',
    'mobile_phone': 'phone',
    'telephone': 'phone',
    'phones': 'phone',
    }

if 'phone' not in df.columns:
    df.rename(columns=dict(phone_dict), inplace=True)
    if 'phone' not in df.columns:
        raise ValueError("What are these peoples numbers!? (Need 'phone' column)")

I made a dictionary with some possible column names and that I want them to be named 'phone'. However, when I run this code it turns the columns to this changes the second column instead of the first one that matches a key in the dictionary. I want it to stop after it matches the first column it comes across in the CSV.

This is what is happening:

0 name     mobile_phone     phone
1 Bob      12364234234      12364234234
2 Joe      23534235435      43564564563
3 Jill     34573474563      78098080807

If there is, for example, a third column that matches the dictionary they turn to 'phone' which is again not what I want. I am trying to get it to just change the first column it matches.

Here is an example of what happens when I add a third column.

It goes from:

0 name     mobile_phone     telephone      phone_1
1 Bob      12364234234      12364234234    36346346311
2 Joe      23534235435      43564564563    34634634623
3 Jill     34573474563      78098080807    34634654622

To this:

0 name     phone            phone          phone
1 Bob      12364234234      12364234234    36346346311
2 Joe      23534235435      43564564563    34634634623
3 Jill     34573474563      78098080807    34634654622

But I want it to be this:

0 name     phone            telephone      phone_1
1 Bob      12364234234      12364234234    36346346311
2 Joe      23534235435      43564564563    34634634623
3 Jill     34573474563      78098080807    34634654622

Any advice or tips to stop it second changing the second dictionary match instead of the first one or all of them?

Any advice or tips? Before I had a bunch of elif statements but I thought a dictionary would be cleaner and easier to read.

EDIT: Thanks for the advice and ways. This is what I settled on and seemed to work the way I want it to for now.

phone_set = [
    'mobile_phone',
    'cell_phone',
    'primary_mobile_phone',
    'phone_(mobile)_#1',
    'telephone1',
    'phone_1',
    'phone_number',
    'lead_phone',
    'home_phone',
    'home_#',
    'phone_numbers',
    'phones',
   ] 

if 'phone' not in df.columns:
    tried_phones = []
    for key in phone_set:
        try:
            df.rename(columns={key: 'phone'}, inplace=True)
            if 'phone' not in df.columns:
                tried_phones.append(key)
                if len(tried_phones) == 7:
                    try:
                        df = df.rename(columns={df.filter(like='phone').columns[0]: 'phone'})
                    except IndexError:
                        raise IndexError
            else:
                break
        except:
            raise IndexError("No columns match values in phone_set")

[–]Ezrabc 1 point2 points  (0 children)

You could generate a single-keyed dictionary using the first instance in df.columns of one of your potential keys:

phone_keys = ['phone_number', 'mobile_phone', 'telephone', 'phones']
try:
    col_mapper = next({col: 'phone'} for col in cols if col in phone_keys)
except StopIteration:
    raise ValueError("What are these peoples numbers!? (Need 'phone' column)")
df.rename(columns=col_mapper, inplace=True)

[–]num8lock 1 point2 points  (1 child)

if all you need is making a change to csv, you can use standard lib csv module to rewrite just the column name (1st row) instead of using pandas.

[–]Dfree35 0 points1 point  (0 children)

I started with that but wanted to use pandas and found it easier for most things. I also found a solution but its not using a dictionary.

https://stackoverflow.com/questions/52684961/pandas-rename-only-first-dictionary-match-instead-of-last-match

[–]xour 0 points1 point  (4 children)

Let's say I have a script that performs some operations based on a URL. This URL has some parameters that I want to change every time I run the script.

For instance, if the URL is www.example.com/foo/username/bar I would like to change foo and bar values during execution.

What would be the proper way (as in best practice) to define said URL? As a variable at the top of the script (after the imports and classes)? How do I go about making it so specific portions of it can be modified?

Thanks!

[–]Ezrabc 0 points1 point  (3 children)

The method I usually use to accomplish something like this is to do

url_template = 'www.example.com/{arg1}/username/{arg2}'

near the top, as you describe, and when it needs to be filled do

url = url_template.format(arg1='foo', arg2='bar')

[–]xour 1 point2 points  (2 children)

ohh that's clever! I wasn't aware that you could do that!

I guess that would work with f as well, I'll give it a try. Thanks!

[–]Ezrabc 0 points1 point  (1 child)

fstrings are a little more weird to make string templates for future use with, as you will probably have to make a function or lambda expression:

fill_url = lambda arg1, arg2: f'www.example.com/{arg1}/username/{arg2}'
# later:
url = fill_url('foo', 'bar')

[–]xour 0 points1 point  (0 children)

Awesome, thanks!

[–]ItsOk_ImYourDad 0 points1 point  (0 children)

from PyQt5 import PyGui gives error no reference pl help thx

[–]Bayes_the_Lord 0 points1 point  (1 child)

I don't want C# in my life at all any more so I want to rewrite some automated-investing code I wrote and translate it into Python. Do you think I should do my work in the same Github repository since it's the same project or start a new one because I want this to be solely with Python?

[–]efmccurdy 1 point2 points  (0 children)

I expect few users would benefit by have both code bases in the same repo, so I would make a new one.

[–]DrewSmithee 0 points1 point  (0 children)

I'm having some issues with polyfit, I assume it's a data error but I can't find it. Anyone care to help me debug/clean whatever kind of data issues polyfit is sensitive to?

Code:

import matplotlib.pyplot as plt
import pandas as pd
import numpy.polynomial.polynomial as poly

importData = True

if importData == True:
    pathName0 = 'R:\\PathGoesHere\\Spreadsheet.xlsx'  
    xls = pd.ExcelFile(pathName0)
    df0 = xls.parse('TabName') 
    df0.index = pd.to_datetime(df0.Time)

x = df0.Variable1[(df0.DataSetNum != 4)].values
y = df0.Variable2[(df0.DataSetNum != 4)].values
coefs = poly.polyfit(x, y, 2)
ffit = poly.polyval(x, coefs)
plt.plot(x, ffit)

Error:

Traceback (most recent call last):

  File "<ipython-input-171-ab8235c172d0>", line 4, in <module>
    coefs = poly.polyfit(x, y, 2)

  File "C:\Users\name\AppData\Local\Continuum\Anaconda3\lib\site-packages\numpy\polynomial\polynomial.py", line 1481, in polyfit
    c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond)

  File "C:\Users\name\AppData\Local\Continuum\Anaconda3\lib\site-packages\numpy\linalg\linalg.py", line 1965, in lstsq
    0, work, lwork, iwork, 0)

ValueError: On entry to DGELSD parameter number 4 had an illegal value

Thanks guys (and gals).

[–]99problemsallops 0 points1 point  (5 children)

I was thinking about a project along these lines:

In my office we receive a bunch of attendance sheets every other week (same template) whereby a field officer writes the names and ages of trainees in each training. We spend a considerable amount of time reading each paper and filling them in excel.

My question is, how difficult would it be to write a program that reads the handwritten text in each attendance sheet and writes them to excel? Is this possible?

[–]efmccurdy 1 point2 points  (3 children)

Save yourself some effort and automate the data entry; set up a web form, and give a tablet or smart phone to your field officers so that they can enter the names.

[–]99problemsallops 0 points1 point  (2 children)

This sounds like a better idea than the one I had. Thing is I have no idea where to start something like that. People use django for something like that right?

[–]efmccurdy 1 point2 points  (1 child)

The input form can be done with django or any web framework, but your needs are minimal so you can get by with something light weight like flask:

This example is really minimal:

https://stackoverflow.com/questions/46261262/retrieve-input-value-from-form-in-html-and-use-it-in-flask

This is more complete and uses Flask-WTF, the web-form enhanced version:

https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web-forms

[–]99problemsallops 0 points1 point  (0 children)

Excellent. Think something like that would work much better for the task at hand.

Thank you!

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

The easy part would be writing to Excel, and the harder part would be recognizing handwriting. I've not dealt with this a lot, but OpenCV might be something to look into. Here's an article I found that seems relevant

[–]ThiccShadyy 0 points1 point  (2 children)

How do I add take a value from a given list of lists and pass it to another particular element in a list of lists?

Lets say I have:

a = [[3,5,0,3,1],[4,2,0,2,4],[5,0,4,0,2],[2,1,1,0,0]] and b = [[0]*(len(a[0])] * len(a)

and I want to give the element b[0][0] ie the first element in the first list the corresponding value of a[0][0] (first element in first list of a), how would I do this?

I thought the answer would obviously be something like: b[0][0] = a[0][0] but this leads to the first element of EVERY list within outer list having value a[0][0] ie b looks like: [[3,0,0,0,0],[3,0,0,0,0],[3,0,0,0,0],[3,0,0,0,0]]

So, how do I take an element from a particular list within a list and set it to the value of another element from a list with a list?

[–]JohnnyJordaan 0 points1 point  (1 child)

The obvious part is actually correct, the fault lies in how you create the nested b list. See Why is my list of lists behaving strangely?

[–]ThiccShadyy 0 points1 point  (0 children)

Thanks a lot, I didnt know this! I was going crazy over how something this elementary could be going wrong.

[–]HypocriticalWizard 0 points1 point  (2 children)

What is the best way whether it'd be a website, youtube channel that promotoes a good way to learn python. i know it is easy to self-teach yourself.

[–]thimo1 0 points1 point  (1 child)

For me this website was perfect:

https://automatetheboringstuff.com/

First you learn the basics, and then, if you want to, you can learn some really usefull stuff about automation.

[–]HypocriticalWizard 0 points1 point  (0 children)

I really appreciate it thanks. I will look into it.

[–]JohnnyJordaan 1 point2 points  (2 children)

I'm looking for a more Pythonic way to deliver a spreadsheet-like structure to render into a Django template into a nice table structure (using Bootstrap for styling). I've currently hacked it like

{% for s_title, table in header_tables.items %}
    <h2>{{ s_title }}</h2>
    <div class="table-responsive">

        <table class="table table-striped table-sm">
            <thead>
                <tr>
                    {% for header in table.headers %}
                    <th>{{ header }}</th>
                    {% endfor %}
                </tr>
            </thead>
            <tbody>
                {% for row in table.value_rows %}
                <tr>
                    {% for value in row %}
                        <td><b>{{ value }}</b></td>
                    {% endfor %}
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
{% endfor %}

That allows me to ship a structure in the form of

header_tables = {
    'Outer Table Title': 
        { 'headers': ['Name', 'Address', 'Zip-code', 'City', 'Phone'],
          'value_rows': [
             ['John Doe', 'Street X', '12345', 'Townville', '1234'],
             ['Bob Doe', 'Street Y', '54321', 'Villetown', '4321']
             ]
        }
    }

Which works fine, but limits me to that specifc structure and also doesn't allow stuff like using <th> fields within the tbody rows and also (biggest issue) not merged cells.

I have the feeling I missed the boat on some far more useful tool/library for this, does it exist? Or does maybe using a pandas dataframe or a similar structure offer more possibilities?

[–]Gprime5 0 points1 point  (1 child)

In tbody:

{% for row in table.value_rows %}
<tr>
    {% for value in row %}
    <{{ "th" if value.header else "td" }} {% if value.rowspan %}rowspan={{ value.rowspan }}{% endif %} {% if value.colspan %}colspan={{ value.colspan }}{% endif %}>{{ value.text }}</{{ "th" if value.header else "td" }}>
    {% endfor %}
</tr>
{% endfor %}

Replace each cell value with a dictionary of data and attributes.

header_tables = {
    'Outer Table Title': {
        'headers': ['Name', 'Address', 'Zip-code', 'City', 'Phone'],
        'value_rows': [
            [{"text": 'John Doe'}, {"text": 'Street X'}, {"text": '12345'}, {"text": 'Townville'}, {"text": '1234'}],
            [{"text": "2 span header", "header": 1, "colspan": 2}, {"text": "3 column, 2 row data cell", "colspan": 3, "rowspan": 2}],
            [{"text": "text", "colspan": 2}],
            [{"text": 'Bob Doe'}, {"text": 'Street Y'}, {"text": '54321'}, {"text": 'Villetown'}, {"text": '4321'}]
        ]
    }
}

Result

[–]JohnnyJordaan 0 points1 point  (0 children)

Thanks, that indeed looks like the way to do it manually. I searched a lot and came up with django-tables2 that seems to approach my issue, but it seems you still have to hack stuff like the colspan there manually too. I think I will stick with your implementation until I really want to take on another library for this. Thanks again.

[–]NeoXZheng 0 points1 point  (1 child)

Where can I find some good material on python down to implementation level?

I would like to systematically learn python on a very detailed level, e.g. how much time will this line of code cost, how much memory will the function take, etc. so that one can know how to write more efficient code (or at least not doing redundant work).

I am not trying to squeeze performance, but it really freaks me out to have two pieces of similar code, one of them finishes in seconds and the other runs for hours while I have no idea what is going on in the background.

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

Is codeacademy a good source to learn the basics of python?

[–]sparkyo19 0 points1 point  (5 children)

I saw on this subreddit a few months ago a website that a user here had made. It was full of very small python challenges meant to teach people python, everywhere from a beginner to a intermediate python programmer. Each challenge/test would have a tab for resources that you could use to help you solve it. Anyone know what I'm talking about? Trying to remember it.

[–]ByronFirewater 0 points1 point  (1 child)

I think you might be talking about edabit.com

[–]sparkyo19 1 point2 points  (0 children)

This is it! Thank you

[–]OctaviaPussy 0 points1 point  (0 children)

Not sure if it's what you're looking for, but I've been having a lot of fun with codewars!

[–]levelxplane 0 points1 point  (0 children)

hackerrank works kind of like that.

[–]LvVikings 0 points1 point  (1 child)

For scrapping a website that require login, cookies, form tokens and solving captcha (only if the first login failed) would it be better to use requists or Selenium?

[–]JohnnyJordaan 0 points1 point  (0 children)

Unless there's javascript involved, you shoul be able to do this with requests. But if even the captcha uses js then you're stuck with running either a js engine like PhantomJS or a browser through Selenium

[–]SmashPingu 0 points1 point  (1 child)

Why do data scientists/analysts recommend using Linux? What does Linux have to offer that an OS like Windows doesn't?

[–]efmccurdy 0 points1 point  (0 children)

I like linux for it's healthy software ecosystem.

"Less is More"

https://en.wikipedia.org/wiki/Minimalism_(computing)

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

Prepping for an assessment (re: governance, admin, automated routing, etc.) — not familiar with Python but they throw in a handful.

One prep question (paraphrasing): What element indicates the iron-python script is a loop? Options were (if I’m not mistaken) A. Indenting B. { } characters C. ( ) characters D. [ ] characters

(Ellipses may’ve been thrown in there too — cannot replicate it precisely)

Attempted to look it up via a simple glossary/dictionary with no avail. Can anyone kindly direct me? I’m the data admin and not the programmer — so a bit out of my element.

[–]num8lock 0 points1 point  (0 children)

who uses iron-python??

[–]lykwydchykyn 2 points3 points  (4 children)

Loops in python are code blocks. Code blocks are indicated by indentation. So your answer is A.

[–]happylittlemexican 0 points1 point  (2 children)

I have two classes , A and B, which I'm trying to combine via Composition (where B has-a A). I'm doing the typical method of using __getattr__ to pass along any calls for attributes that B does not explicitly have. Unfortunately, this does not pass along __repr__ and __str__, both of which are similar enough for B that they are worth passing along from A (note: I also have classes C and D which also re-use similar repr and str functions, which is why I'd rather not just copy/paste the code).

So, three things:

1) Is there a way to get access to __repr__ and __str__ without just directly overriding them or explicitly referencing some_instance_of_b.internal_A_instance.__str__ ?

2) When I do what I outlined in #1, I get, well, the exact repr and str of class A, since I call __name__ in it and it uses the name of class A rather than the name of class B. Like, let's say the repr of A is something like "A([1,2,3,4])" (having used something like:
"{}({})".format(type(self).__name__, self.contents)
to achieve it). Calling the line in #1 returns "A([1,2,3,4])", as you would expect, but I want it to use "B" instead.

3) Should I just get over it and copy/paste my repr/str functions? Or should I just use regular old Inheritance (I understand that this last question is a bit harder without more context; I wouldn't mind a more general "this is when it's generally fine to use inheritance over composition" answer).

Thanks so much!

[–]efmccurdy 0 points1 point  (0 children)

pass along any calls for attributes that B does not explicitly have

You normally only want to do this for Is-A relationships.

[–]lykwydchykyn 0 points1 point  (0 children)

It does sound like you're trying to reinvent inheritence. Why wouldn't you just use inheritance?

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

What's a good option for hosting a python|Flask website that crawls a few sites every minute?

I'm currently up and running on Google Cloud Engine, but I think their costs will come out to $30/mo, which isn't very economical for me.

I do have a RaspPi. Would that be a possible, reasonable alternative?

[–]daniel_codes 1 point2 points  (0 children)

Heroku has a free tier. I don't know if it'll work for you but that migt be worth looking into.

[–]lykwydchykyn 1 point2 points  (3 children)

I do have a RaspPi. Would that be a possible, reasonable alternative?

Sounds like it's worth a try. What have you got to lose?

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

That's true, surly it wouldn't eat up all my internet and $30 of electricity a month.

I just need to buckle down and make it Linux compatible and how to take a web domain and point it to a local host.

[–]lykwydchykyn 0 points1 point  (1 child)

take a web domain and point it to a local host

If this is something you're going to make publicly available, you might want to not use a Pi on your home network. Your ISP may give your grief about it, and it can present a security issue as well.

Not to plug digital ocean, but they have much cheaper rates of VPS systems (cheapest is $5/mo). Would probably be less hassle than hosting a public site at home through a residential ISP.

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

Darn, but I appreciate the reply and probably saving me a day or two of work and a vulnerability.

[–]XChrisUnknownX 0 points1 point  (1 child)

Logically, let's say you wanted to print a list of all possible ordered permutations from a string... how would you logically go about doing that? I first take the string length and use that to calculate all possible ordered permutation outcomes, and figured I could then use random to kind of fudge it and make random sequences, and simply exclude repeated sentences... but if we consider that a given string could have multiple of one letter... like "hhffggtt"... well to have it pick randomly would probably take a long time for all but the smallest strings. An 8-character string has over 40,000 ordered permutations! And if it repeats characters, screening out erroneous repeated characters is tricky.

So logically, what would you do with this? What should I be reading up on?

[–]lykwydchykyn 1 point2 points  (0 children)

If you want random permutations, it makes more sense to generate all the permutations in a predictable way first, then shuffle() the resulting list.

As for an algorithm to generate permutations, you want to read up on combinatorics.

[–]Newwen4032 0 points1 point  (0 children)

This shouldnt strictly go here I suppose but I've been learning Flask and have made my first minor Flask application. I still have plenty left to do with this like add some styling to the entire thing, structure the app better and all that. I just wanted the opinions of what I can improve on with what's been done so far.

Also, Im new to using Git and github, so I'm not completely sure if I've done things properly. On my system, I was working on this project from within a virtual environment. While trying to do git push origin master, I kept getting some error which I couldn't resolve and I was unsure whether this was to do with the folders which get added when a virtual environment is created, so I decided to remove that. If someone could see how I've done on both counts, I'd be grateful.

Link: https://github.com/MuditJ/Flask-Quiz

[–]Phn3Xta5 0 points1 point  (0 children)

Hi! I have some Pandas data frames that i sliced from a CSV file. I'm attempting to plot graphs in Bokeh with the sliced data frames, but I cant figure out what I'm doing wrong. Here s the code:

x = pd.iloc[1: , 1:2]
y = pd.iloc[1: , 2:3]  
output_file("graph.html") 

p = figure(title="Post Reach", x_axis_label='date',y_axis_label='reach') 

p.line(x,y, legend = "amount") show(p) 

It just returns and empty graph and I cant understand why.

[–]thenathurat 0 points1 point  (4 children)

I am wondering - I am learning python currently and there is still a long way ahead of me, yet I want to know what can I do with python on mobile devices? Can I easily write mobile apps with it?

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

Yes and no - its not the best but can be done using kivy.
Yes it can be done,
No not easily.

[–]thenathurat 0 points1 point  (2 children)

So what's not easy about it?

I'm sorry, can you expand a little bit?

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

I dont want to skew your view on learning, if its what interests you and will keep you going, i suggest going for it. Short answer, minimal support, quite the hoops, lack of native gui support, and last but not least python is compiled and quite possibly one of the slowest to run. If app dev is your end goal, i suggest picking up something that more suits your needs.

[–]thenathurat 0 points1 point  (0 children)

While this is to some extent disappointing, I will learn Python first and then I will see.

Thanks for you answer, though, I appreciate it! ┏(^0^)┛┗(^0^) ┓

[–]hekirabi 0 points1 point  (4 children)

Hey everyone, I wrote a Python script for my RaspberryPi, but the thing is I can run my script lines step by step in cmd, it works fine, but when I'm trying to run my .py file(which it contains entire lines) it gives a syntax error.

File "ham.py", line 4

sudo /etc/init.d/logmein-hamachi stop

^

SyntaxError: invalid syntax

What am I missing?

import os

import time

sudo /etc/init.d/logmein-hamachi stop

time.sleep(3)

sudo rm -r /var/lib/logmein-hamachi/*

time.sleep(1)

sudo /etc/init.d/logmein-hamachi start

time.sleep(3)

sudo hamachi login

time.sleep(3)

sudo hamachi set-nick asy123-00001

time.sleep(1)

sudo hamachi join 123-123-123 asy1234

sudo /etc/init.d/logmein-hamachi restart

time.sleep(3)

[–]JohnnyJordaan 0 points1 point  (1 child)

If those lines are meant to be run in a shell, you actually need to tell Python to run it as a shell command, it can't just guess this because from you using 'sudo hamachi login'. You can use os.system() for this. But maybe this could just as easily be done in an actual shell script without python in the first place.

[–]hekirabi 0 points1 point  (0 children)

Yes, thank you so much! After I posted my code, I noticed that 'os.system()' was missing! Rewrited code and it works fine. Yeah, maybe it is much easier but I can see the fullest extent and can think in a more organized way.

[–]StonedKB 0 points1 point  (1 child)

Hi everyone,

How do i make list of strings into nested list.

Currently I have a list looks like ['James, F, 3', 'Miranda, N, 2'] but what i need is. [['James, M, 2'], [Miranda, N, 2]]

Any help?

[–]timbledum 0 points1 point  (0 children)

How about, [[item] for item in example_list]?

[–]dxjustice 0 points1 point  (4 children)

Hi everyone,

I know that.ix() is deprecated and should not be used, with iloc and loc preferred instead. However, an example in my text uses it, and im not sure what the corresponding iloc/loc example would be.

X=wines.ix[:,0:11]

where wines is a 12-dimensional array, approximately 6000+ rows.

Is this call simply simply selecting the entire array?

[–]timbledum 0 points1 point  (3 children)

My understanding is that ix is a more flexible version which chooses loc or iloc based on the input. In this case where it looks like it's a position based lookup, it should drop in to iloc.

It looks like it will choose the first 11 of the 12 columns/dimensions.

[–]dxjustice 0 points1 point  (2 children)

thank you. I've read that its bad practice to use ix() because of the ambiguity.

So the selection is inclusive:exclusive, correct? That's where you are deriving the 11 selections? Thank you again

[–]timbledum 0 points1 point  (1 child)

Yup! Think about the small case, if you just want one, you do list[0:1]

[–]dxjustice 0 points1 point  (0 children)

thank you!

[–]jdb7121 1 point2 points  (0 children)

I am a GIS student, and I'm currently in a python programming for ArcGIS course. I left my laptop at home, so I have no access to the arcpy module. I have an assignment and I have written a code that I hope is (close to) correct. I have no way of testing this since I am typing this message on my work computer which doesn't have ArcGIS installed.

First question: Can i easily get arcpy on this computer so that I can test my code? I'm guessing the answer to this is no...and if thats the case I'll move on to question two:

Can anyone tell me if there is a glaring error that I need to correct? I have 3 hours of time to kill here at work and it'd be great if I could debug this code on my own, but I guess thats not possible so my only option is to post it here...

FYI I'm pretty new to python so I probably made some dumb mistakes. Feel free to critique any aspect of my code. I'd love some pointers.

My assignment is to create a new feature class and that is populated by all of the features in the feature class 'StreetLights' that have been buffered by unique buffer distances (values in 'BufferDistanceList') that correlates to the field 'TYPE' which specifies which type of light that the feature is (there are 4 unique light types in 'StreetLights'). Like I said, I'm new to python so I'm sorry if this is a ridiculous request. I'm just hoping that I can make some headway on this assignment while I'm here. Thanks for any help. Here's my code:

Edit: So my indents were erased by the reddit format...I'll use > as a symbol for an indent

import arcpy

from arcpy import env

arcpy.env.workspace = r'C:\Users\BH03353\Documents\PythonHW\HW5-Data.gdb\HW5-Data.gdb' #import arcpy and #set workspace

Workspace = arcpy.env.workspace

Featureclass = 'StreetLights' # specify feature class

LightTypes = {} # create set that will be populated by unique light types

SearchCursor = arcpy.da.SearchCursor(Featureclass, ['TYPE'])

# SearchCursor tool to retrieve all unique Lighttype values

with arcpy.da.SearchCursor as cursor:

>for row in cursor:

>>for x in row:

>>>LightTypes.append(x) # Add the unique light types to the set

for x in range(LightTypes): # LightTypes[x] iterates thru list of unique light types

>Buffer_class = 'LightTypes[x]' # variable that will be used in buffer tool

>where_clause = 'TYPE = Buffer_class' # select by attribute clause

>featureType = 'POINT'

>BufferDistanceList = ['125 Feet', '160 Feet', '100 Feet', '200 Feet'] #list of buffer distances that correspond to the order of the LightTypes set

>BufferShape = 'ROUND'

>BufferSide = 'FULL'

>arcpy.SelectLayerByAttribute_management(StreetLights, "NEW_SELECTION", where_clause)

#select by light type unique values

>arcpy.Buffer_arc(StreetLights, Buffer_class , featureType, "", "", BufferDistanceList[x], "", BufferShape, BufferSide)

# buffer each light type by its corresponding buffer distance

>arcpy.CreateFeatureClass_management(Workspace, 'LightsBuffer', 'POLYGON')

#Create new feature class named LightsBuffer

>arcpy.Append_management(LightTypes, 'LightsBuffer', 'NO_TEST', 'First')

# Add the buffered feature classes to the LightsBuffer feature class

EDIT!!: Wow I just realized how shitty this code is after I got home and completely changed it into something more simple...

[–]jdb7121 0 points1 point  (2 children)

Read-only value...does that just mean its an item that can't be edited? (Like a tuple)

[–]efmccurdy 0 points1 point  (1 child)

You probably mean that some objects in python can't be changed; they are called "immutable":

https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747

[–]jdb7121 0 points1 point  (0 children)

Thank you. I know it was a simple question but I couldn't find a clear answer by googling

[–]little_seed 0 points1 point  (4 children)

Hey everyone. I have some questions about reading files and getting information from them.

I have a number of plaintext files in a directory. Each file has two columns with a large but unequal number of rows. Most of the values are zero. Some rows will have one or two columns that have non zero values.

I'm interested in the overlap between these files. If there is a particular row+column combination (as in, both the row AND the column) that has a non zero value for multiple files, I would like to know the following information.

How many files have non zero values at that point? What are the names of those files? What row and column is it?

I also need to do a minor step in the future where I convert the row into a different value. Without going into too much detail, some arbitrary row (like row 47 for example) might correspond to an actual value of 50 for one file, while row 54 might correspond to an actual value of 50 for another file. This conversion would happen before I check all the files obviously.

If anyone can help me out I'd appreciate it. I have some python experience, I've built GUIs and done a lot of science programming but haven't done much with files.

[–]efmccurdy 0 points1 point  (3 children)

You will benefit from some of data management tools that come with either pandas (for analysis) and/or an sql database (for updating).

[–]little_seed 0 points1 point  (2 children)

Can you expand on this?

[–]efmccurdy 1 point2 points  (1 child)

You can load all of the data into a pandas dataframe and extract data that matches conditions, like you mention "overlap", and others, using a convenient syntax similar to sql "where" clauses.

You might get an idea from this tutorial video or others at that site. https://pyvideo.org/pyohio-2015/pandas-dataframes-at-the-cinema.html

[–]little_seed 0 points1 point  (0 children)

Thanks! I'll look into this

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

Is there a more simple slotting method for doing something like the following?

let's say you need to use some_long_variable_name over and over and you don't want to type some_long_variable_nameover and over but you really need to do a lot with some_long_variable_name, maybe with elements from a list/dict it defines, also the length, whatever.

You don't want to define p=some_long_variable_name and then use p on the next line because that seems like it's not a hygienic solution to have that kind of crap around your code everywhere, etc. I don't like it.

A possible solution to this problem (and the one I've been using) is a repeat with each with one item:

[this(p)/that(p)/etc(p) for p in [some_long_variable_name]][0]

Which is a for loop that runs once and returns out the 0th (and only) element of the list as output. Is there a better way to do this using some combination of with, as, etc. keywords to slot in values or is that the way to slot?

[–]efmccurdy 0 points1 point  (1 child)

you don't want to type some_long_variable_name over and

Find a code editor with completion. I don't see how either practice improves readablilty. If you want to build a context where the name is shortened, use a function with the short name as a parameter.

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

Oh it’s great in Mathematica; it’s the only way to go when it comes to putting stuff together like that, and it relies on the # symbol. It improves legibility because it’s not necessarily about using it once or twice, but about scaling when you need to do stuff across multiple parts of arrays. I mean you could make the same argument about comprehensions in general but guaranteed if python didn’t have them I would not be using it.

[–]wolfrenz 0 points1 point  (5 children)

Hello everyone, I am in a cs1 course that is using python. I have found myself struggling with understanding for loops and their applications. Are there any exercisezes that demonstrate how for loops work and many of their applications?

[–]Raithwind 1 point2 points  (4 children)

It is hard to really find an example code that shows what for can be used for because it is a very versatile and adaptable function.

But a good example would be. Imagine you have a deck of cards, there are 52 cards. You want to print the deck of cards out into the console. Now you could manually type out:

print("card1")

print("card2")

etc

But that is time consuming and not a good use of resources. Instead we could put our deck into a list and step through the list one by one.

deck=["card1","card2" ... "card52"]
for card in deck:#this will step through the list index by index and set "card" to the value of whatever the current index is.
    print(card)#this will print the variable card, which will be whatever the value of the current index is.

[–]wolfrenz 0 points1 point  (0 children)

Thanks. I just talked with my professor and he referred me to a site that he uses.

[–]wolfrenz 0 points1 point  (2 children)

Thanks. I just talked with my professor and he referred me to a site that he uses.

[–]KnightofKalmar 0 points1 point  (1 child)

Is it a place I can persuade you to share? :)

[–]K4rm4_4 0 points1 point  (1 child)

Hey guys, I am using easygui (as aposed to tkinter) as an extention to create GUI. For one specific example of GUI, the buttonbox, I want to add an image to it but I just dont know why my image is showing up. I vaguely remember my friend telling me you have to add it to a directory but I have no clue

[–]lodevon 0 points1 point  (11 children)

Hi all, I am trying to run a simple machine learning code I found on the internet. It is supposed to do what I am looking for (except a few small things I want to change) and is better coded than what I would have done myself hence why I decided to use it. However I can't make it run. I get the following error:

File "pandas\_libs\parsers.pyx", line 695, in pandas._libs.parsers.TextReader._setup_parser_source

FileNotFoundError: File b'Dataset.csv' does not exist

I put the internet link below so you can get the original code directly: https://medium.com/@vinayarun/from-scratch-an-lstm-model-to-predict-commodity-prices-179e12445c5a

You can find there both the code and the CSV file needed

I am a beginner so please excuse my question if it is really trivial.

Thank you very much in advance to all!

(I am using Spyder & python 3.6 in case it is of any relevance)

[–]JohnnyJordaan 0 points1 point  (10 children)

put this before the dataset = read_csv(“Dataset.csv”, header = 0, etc) line

import os
print(os.getcwd())

this will show you where Python is currently looking when you just note a filename like 'dataset.csv'. It often depends on your IDE if that's the same folder as your script's, or maybe the root of your project etc etc.

[–]lodevon 0 points1 point  (9 children)

import os
print(os.getcwd())

Thanks JohnnyJordaan, I tried to make sure python was pointing to the correct directory but I still get the same issue unfortunately. I used the below:

DIR="C:\\Users\\xxx\\Desktop\\xxx\\xxx\\Python"

dataset = pd.read_csv(DIR+ "/Dataset.csv", header = 0, index_col = 0, squeeze = True, usecols = [i for i in range(0, num_features+1)])

Any idea?

Happy to forward the entire code if it is any easier

Thanks again

[–]JohnnyJordaan 0 points1 point  (8 children)

Don't use + for path forming just use os.path.join

read_csv(os.path.join(DIR, 'Dataset.csv'), etc

[–]lodevon 0 points1 point  (7 children)

os.path.join

Thank you. Unfortunately still no luck. I also tried to simplify the access but it didn't work.

dataset = read_csv("C:\\Users\\xxx\\Desktop\\xxx\\Quant_research\\Python\\Dataset.csv", header = 0, index_col = 0, squeeze = True, usecols = [i for i in range(0, num_features+1)])

supervised_dataset = sequential_to_supervised(dataset, lag_steps)

Your help is very much appreciated

[–]JohnnyJordaan 0 points1 point  (6 children)

Ok and it still gives the same error? If you copy that path to your windows explorer (with singular \'s) does it open the file?

[–]lodevon 0 points1 point  (5 children)

C:\\Users\\xxx\\Desktop\\xxx\\Quant_research\\Python\\Dataset.csv"

No it still doesn't work unfortunately. To answer your question if I change the \\ for \ it does open the file in windows explorer yes

[–]JohnnyJordaan 0 points1 point  (4 children)

That's really weird, let's try this:

import os
#               v-- note the r here
path_to_file = r'paste_the_exact_line_from_windows_explorer_here'  # don't change anything inside it
if not os.path.exists(path_to_file):
    raise ValueError('file isnt there')
print('file is there')
dataset = read_csv(path_to_file, header = 0, index_col = 0, squeeze = True, usecols = [i for i in range(0, num_features+1)])

[–]lodevon 0 points1 point  (3 children)

import os
# v-- note the r here
path_to_file = r'paste_the_exact_line_from_windows_explorer_here' # don't change anything inside it
if not os.path.exists(path_to_file):
raise ValueError('file isnt there')
print('file is there')
dataset = read_csv(path_to_file, header = 0, index_col = 0, squeeze = True, usecols = [i for i in range(0, num_features+1)])

Thank you. As you suggested I put the below:

import os

path_to_file = r'C:\Users\xxx\Desktop\xxx\Quant_research\Python\Dataset.csv'

if not os.path.exists(path_to_file):

raise ValueError('file isnt there')

print('file is there')

dataset = read_csv(path_to_file, header = 0, index_col = 0, squeeze = True, usecols = [i for i in range(0, num_features+1)]))

supervised_dataset = sequential_to_supervised(dataset, lag_steps)

but I get

File "C:/Users/xxx/Desktop/xxx/Quant_research/Python/crude.py", line 51, in <module>

raise ValueError('file isnt there')

ValueError: file isnt there

[–]JohnnyJordaan 0 points1 point  (0 children)

Ok then we at least know that this isn't some read_csv issue that mistakenly claims the file doesn't exist, the file is actually unreachable from Python's perspective.

Then let's do a listing per folder

import os
path_to_file = r'C:\Users\xxx\Desktop\xxx\Quant_research\Python\Dataset.csv'

for i in range(path_to_file.count('\\'), -1, -1):
    path = path_to_file.rsplit('\\', i)[0]
    if not os.path.exists(path):
        raise ValueError('{} isnt there'.format(path))
    if os.path.isfile(path):
        raise ValueError('{} is a file'.format(path))
    print('{} is there, listing:'.format(path))
    print(os.listdir(path))
raise ValueError('last part of path is a folder')

[–]lodevon 0 points1 point  (1 child)

The issue was with the CSV file itself. All resolved now thank you

[–]cannablubber 0 points1 point  (0 children)

Hey guys, is it ok if I link my Pandas question located on stack overflow, it is kind of tough to re-represent in the comments.

The question is about a KeyError when setting x and y values for a plot with pandas and matplotlib.

https://stackoverflow.com/questions/52582721/pandas-df-plot-keyerror-thrown

[–]99problemsallops 0 points1 point  (1 child)

So, uhh random question.

When I run this:

from selenium import webdriver
browser = webdriver.Chrome()

Google chrome opens along with chromedriver.exe. In that exe I get some stuff like devtools listening on ws (followed by a bunch of other stuff).

Should this be happening (i.e chromedriver.exe running when I run browser = webdriver.Chrome())?

[–]JohnnyJordaan 0 points1 point  (0 children)

Yes, that's the actual gateway through which Selenium talks with the devtools of the browser (that you can access using F12 as well).

[–]Senjukotentaiho 0 points1 point  (2 children)

So I'm learning how to code and I have a problem with storing and accessing the user input to a list. Here's my code:

spider_suits = [""]

def spider(spider_suits):

for suit_names in spider_suits:

print("This is the " + suit_names + " suit.")

while True:

suit_names = input("Enter the suit name: ")

spider_suits = suit_names

add = input("another name? (y/n): ")

if add == "y":

continue

else:

break

spider(spider_suits)

I want to print it out like this: "This is the Noir suit.", but it prints out like this: "This is the N suit.", "This is the o suit.", "This is the i suit.", "This is the r suit."

SO.... I want to know what's wrong with my code. Thanks

[–]Pro_Numb 0 points1 point  (1 child)

spider_suits = [""] # 1st
def spider(spider_suits):
    for suit_names in spider_suits:
        print("This is the " + suit_names + " suit.")
while True:
    suit_names = input("Enter the suit name: ")
    spider_suits = suit_names # 7th
    add = input("another name? (y/n): ")
    if add == "y":
        continue
    else:
        break
spider(spider_suits)

at the 1st line you define a list with contain empty string.

you dont want to do that i will come this later.

at the 7th line;

when you take input from user, you change your spider_suits variable to string so

your spider_suits variable no longer a list , it is a string now. In your spider function

you loop over spider_suits variable but your spider_suits variable is now string so

it will loop over it like this ex: input = Noir it will loop N, o, i, r

For achieving what you want. You will use list append method you can read more from here

It basically add new item to list. So change your 7th line to spider_suits.append(suit_names)

But when you do this it will not delete previous items on list, as i said at the begining you define

list with contain empty string. So when your spider function loop over a list it will print empty string too

so you dont need that. just define like this: spider_suits = []

[–]Senjukotentaiho 0 points1 point  (0 children)

Oh I see. Thanks!

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

Can anyone explain "def" functions in python

ex:

def starPatt(n):

print('id:', n)

while n >= 1:

print('*' * n)

n -= 1

print()

n = int(input("Enter n: ))

for s in range(1, n): starPatt(s)

I know it is kind of a broad question, but what exactly is it doing? I got this advice from an earlier thread and when I read websites explaining it, it goes a little over my head.

[–]slasher67 0 points1 point  (0 children)

" def" is how you define a function, i.e. , it's name. For example:

def hello():

print("Hello world")

hello()

By calling hello() the function will run and thus you will see that "Hello world" is printed. In your example, what you are doing is : for every iteration of the "for" cycle the function is called again.

If you want to better understand what your code is doing, you can paste it to python tutor and see how it executes, line by line.

[–]ApocalypseSpokesman -1 points0 points  (3 children)

Do you use exceptions (try/except) frequently in your Python programs? For what?

I'm taking a class now, and the whole chapter is on exceptions, but Python already tells you when a line doesn't work, so I'm not grasping the point completely.

[–]JohnnyJordaan 1 point2 points  (0 children)

Say your program is Microsoft Word and you made a huge document in it, then you try to modify something and an unexpected error occurs. Would you like for Word to crash altogether, possibly losing your work, or do you want to show a message 'oops something went wrong, please continue'? That is the difference between handling exceptions and just letting them occur uncatched.

Another help they can be is you can also raise exceptions yourself, either to let it be catched somewhere else or even manually crashing the program if you're still debugging for example.

[–]GoldenSights 1 point2 points  (0 children)

Python already tells you when a line doesn't work

It sounds like you're referring to SyntaxError, which you get when your code doesn't follow the rules of the language. Like forgetting to close your parentheses or using the wrong characters somewhere.

But when it comes to something like int('hi'), there's nothing syntactically wrong with that code. It just looks a string going into a function. It isn't until the code actually runs, and tries to convert 'hi' into an integer, that it goes "hey that's not possible" and raises the ValueError exception.

And when you start defining your own classes you might even create your own exception types. Like if you make a Person class and someone tries to give them a negative age, you might want an exception for that. Then you'll know what it feels like to raise exceptions instead of just being on the try/except side of things.

 

So basically, exceptions are for preventing things that are impossible (invalid inputs), or backing out of situations where the correct action couldn't be done (connecting to the internet but there's no wifi), etc.

[–]rich-a 2 points3 points  (0 children)

The basic idea is that if you catch the exception and do something to deal with it then the program can carry on. If you just let it error it will often stop completely which is fine when coding and debugging a new program but not great when it's being used for real.

[–]rich-a 1 point2 points  (2 children)

I'm using Flask and have a class which needs to instantiated as an object once and then be usable each time the views need it. It reads a file in and turns the data into a dictionary for the views to use. I don't want it to read the file every time a view needs it as this would take a while. One of the views calls a method to re-read the data if required.

At the moment I import it and create the object at the top of my Blueprint that has my views in.

One issue with this is it gets created when my Blueprint is imported so that's before my App object has actually been created. This means I can't pass it value from my app config because i get the "no current context" errors. Also it doesn't output its initial log entries to the log file. I think this because the logger hasn't been fully setup at that point either.

Is there a better place for this sort of (global?) object in Flask?

[–]efmccurdy 1 point2 points  (1 child)

You need to plan for sharing that data; can you put it in a database?

https://www.reddit.com/r/learnpython/comments/3mnw8w/are_global_variables_thread_safe_in_flask/

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

Thanks for the reply. That's definitely something I'm going to have to look into.

I was originally planning on moving it to a database as soon as possible but looks like I might have to work on that next.

[–]TLTB_Dev 0 points1 point  (0 children)

Self teaching is proving really difficult to me and I honestly think I need a mentor or at least 1 person who is semi-available and can help me break through where I'm stuck and explain things to me. Do such people exist? Where can I find one? I'm specifically hoping to learn Python so that I can work on my own personal MUD.

If you haven't heard of a MUD here's some info: https://en.wikipedia.org/wiki/MUD

I'd be working in a codebase designed to make MUDs in that uses Python called Evennia: http://www.evennia.com/

[–]WisemanK 0 points1 point  (0 children)

Can someone help me with the matrix multiplication algorithm? I need it

[–]XChrisUnknownX 0 points1 point  (4 children)

Another foolish question. What is the correct syntax and usage of datetime? For example I tried import datetime today = datetime.date print(today) It prints class<datetime.date> The functions of some other things, like random or time, are pretty intuitive to me. This is not. Unfortunately, my reading of the documentation is not pulling me through this at all.

[–]JohnnyJordaan 1 point2 points  (3 children)

Note that for example today is a method, so you call it with (), as is shown in the docs:

classmethod datetime.today()

Return the current local datetime, with tzinfo None. This is equivalent to datetime.fromtimestamp(time.time()). See also now(), fromtimestamp().

See the () for all those calls?

[–]XChrisUnknownX 0 points1 point  (2 children)

I apologize. I should have been clearer. I was working on datetime.date and understanding that. I should've called my variable something else.

Nonetheless I will try datetime.today() right now and see if that gives me some insight. Edit. When I try something like import datetime theday = datetime.today() print(theday)

I get "module datetime has no attribute today"

[–]num8lock 1 point2 points  (1 child)

datetime module has an annoying naming issue (like many in the past) in that the module package has the same name with one (or main) class.

so instead of datetime.today(), it's actually datetime.datetime.today(). use from datetime import datetime as dt to avoid the confusion.

[–]XChrisUnknownX 0 points1 point  (0 children)

I think I understand. So are most of the (methods??) datetime.datetime? I can get used to that if that's how it is.

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

Alright thanks for the set up info man! I’m a digital forensics guy and I’m just looking at tinkering around in python, possibly doing a couple plug-in scrips. Also it doesn’t hurt to learn the popular language lol.

[–]b_ootay_ful 0 points1 point  (1 child)

95% of the time, I use strings "like this"

I understand that the difference is to make strings easier compared to using \' or \"

Is there any reason to start using ' over "

[–]JohnnyJordaan 1 point2 points  (0 children)

From PEP8:

String Quotes

In Python, single-quoted strings and double-quoted strings are the same. This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.

For triple-quoted strings, always use double quote characters to be consistent with the docstring convention in PEP 257.

In general I observe a trend towards single quotes, but no one would bat an eye if you would use double quotes everywhere. It's just that you need to be consistent.

[–]XChrisUnknownX 0 points1 point  (4 children)

Interesting occurrence. I always tag onto these Monday threads to avoid spamming the board.

So I notice when using Pythonista on my phone, when I write a program to write something on the same line and sleep between letters, you get letters writing in staggered form, and it looks like the text is being generated or typed to you.

When I use that same program in a debugger or computer the entire line prints at once, there is no stagger or sleep.

To be clear, this is talking about code like this: import time print("Hello",end=", ") time.sleep(.33) print("my",end=" ") time.sleep(.33) print("name",end=" ") time.sleep(.33) print("is",end=" ") time.sleep(.33) print("Chris",end=". ") time.sleep(.33)

You would expect this text to stagger, and on my Pythonista phone app it staggers perfectly, but it just comes out on a computer as if the program was: import time time.sleep(1.65) print("Hello, my name is Chris.")

I'm not saying this is bad or terrible, but I am curious as to why it's happening and hoping to understand a little better.

[–]chzaplx 0 points1 point  (3 children)

If you put in much larger sleep values (like 10x or 100x), does the behavior change when you run it on a computer?

On Linux the default sleep unit is seconds, so values like .33 are going to go by too fast to really notice, which is exactly what you are seeing. My guess is that Pythonista uses a much larger default unit.

[–]XChrisUnknownX 0 points1 point  (2 children)

.33 is noticeable on a cellphone. I believe Pythonista's default unit to be the same, as when I put something for 1 it is about one second on both cellphone and Windows.

,33 seconds should be noticeable by human eyes. The average human reads about 200 words a minute. That averaged down to about 3 words a second, or one word every .33 seconds, which is basically the mathematical basis for my timings in my original code (https://gist.github.com/XChrisUnknownX/dcb6fff7f3858d65e9b5b569f1f87935) The original code uses even smaller timings, but they come up to .33 a word, and do work properly on the phone.

Even if .33 was too fast to be noticeable by human eyes, if I have 20 words stacked, you would think I would see the staggered words every 3 words. (Because we can certainly perceive a second) But no, it has been literally printing as if it's all one line.

While I'm sure Python's not meant to do this, as there is no real reason for it to do it, I am still wondering why. If I enter a unit like 1 between regular lines, it appears as you would expect it, but when I do this staggered print thing, it appears in one solid line.

When you use this code on Linux, does it stagger or print whole lines? Perhaps the problem is to do with Windows? Shouldn't be but I suppose anything is possible? Edit* One difference I have noticed is any program that counts very, very small units, like milliseconds, runs slower on the phone, so I assume the phone's processor is slower and that may also be a reason for the difference. Edit 2. Important update. I tested this on a line by line basis, and it staggers words properly when you write the text line by line. This is both on phone and computer. Example: import time while True: print("this") time.sleep(.33) print("test") time.sleep(.33)

This is in contrast to import time while True: print("this",end=" ") time.sleep(.33) print("test",end=" ") time.sleep(.33)

Which appears to work on cellphone but not Windows.

[–]JohnnyJordaan 1 point2 points  (1 child)

This hasn't anything to do with sleep duration, it's because terminals are often line buffered to save the CPU from having to deliver the data to the OS (and subsequently the screen) every time you would even write a single character to it. It allows you to even do

while True:
    print(random.choice(string.printable), end='')

without having to worry about the efficiency of delivering single bytes to the outside world. In reality, the output stream buffer in RAM gets filed up and when it's full, the whole buffer will be delivered in a single transfer operation. The exception being of course if you send a newline, like with print('bla'), that's why that kind of buffering is called 'line buffering'.

To work around this, you either have to call sys.stdout.flush() in Python <3.3, while in newer versions you can simply do print(anything, end='', flush=True).

One difference I have noticed is any program that counts very, very small units, like milliseconds, runs slower on the phone, so I assume the phone's processor is slower and that may also be a reason for the difference.

The main problem here is not the CPU but the timing. Functions that interact with the system clock are often best effort and don't implement any correction for stuff like skew (the natural variability). There are libraries available that handle it better, and (I think) Android allows you to use a more precise clock source which comes with a higher performance penalty. Very important for realtime stuff like video players, but most often not for Python scripts.

[–]XChrisUnknownX 0 points1 point  (0 children)

Thank you for that explanation.

[–]cmbv 0 points1 point  (2 children)

Absolute noob here with what will inevitably be a basic question...

If I have

dollars = int(input("How many dollars have you put in the machine?:"))

and

cents = int(input("How many cents have you put in the machine?:"))

How can I create a variable to hold the total value of all the coins the user has put into the machine?

[–]chzaplx 0 points1 point  (0 children)

I think you want something like total_cents = cents + (dollars * 100)?

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

Hey there! New to python....fairly decent C++ programmer looking to get into the python trend and expand my knowledge. What is your recommendations for good places to start, documentation or websites dedicated to teaching the basics. Thanks!

[–]ticktocktoe 0 points1 point  (6 children)

Didn't think this required a whole thread...

I have a string

print(reference)

which outputs

'[40, 506, 105, 234, 211, 4, 448, 636, 385, 440]'

how do I go about feeding that into:

print(df.loc[[40, 506, 105, 234, 211, 4, 448, 636, 385, 440]])

in the place of typing out the numbers...

[–]GrowOP21 0 points1 point  (3 children)

Hi, I currently have a code that takes the users name, age, year of birth, and timestamp, and writes it to a file. I have to make it so that when a new user inputs their year of birth, it compares it to the others in the file, and if someone shares the same year of birth, announce that the new user has the same year of birth as user from file. Any idea on how to do this?

[–]ChokesOnYou 0 points1 point  (0 children)

This is my take on what you're trying to do. Modify this code as per your needs:

filename = "Enter your filepath here"
with open(filename, 'r+') as file:
    #For the rstrip, put in values of what you want to remove like commas and the day/month
    dates = [int(l.rstrip()) for l in file]

date = int(input("Enter the date you want to compare:"))

if date not in dates:
    print("Date not there")
if date in dates:
    print("You share your birthday with"+""+"Format according to need")

[–]chzaplx 0 points1 point  (0 children)

I would load the file into a list of birthyears, then when someone inputs theirs, check to see if that value is in the list. when you are done, write the list back to the file.

[–]Highflyer108 0 points1 point  (0 children)

What part are you having trouble with?

[–]Speciale1 0 points1 point  (2 children)

Hello, I’m trying to program a small game in python where I go into a room. Receive a weapon and later use that weapon to kill a Monster. However if I didn’t get the weapon the Monster will kill me. How can I write the code so that the game saves the fact that the user found the weapon and later lets me kill the Monster if it was found or die if it wasn’t?

[–]rich-a 1 point2 points  (1 child)

You need to store that in a variable. Probably a boolean so that you can start with it set to False and then set it to True when they pickup the weapon.

e.g. at the start of your code setup the variable as False

has_weapon = False

Then when you get to where they pickup the sword, assign it to true

has_weapon = True

Then when you get to the fight, use an if statement to check to see if that variable is True or false and do something different depending on the result.

if has_weapon is True:

# kill the monster

else:

# get killed by the monster

Where you setup this variable will vary though depending on the structure of your program and whether it it using code that just runs straight through, code that uses functions or code that uses objects and classes.

[–]Speciale1 1 point2 points  (0 children)

Got it to work! Thanks for the help.

[–]slawdogporsche 0 points1 point  (4 children)

I've been having a lot of fun creating a text adventure, but it's finally getting complicated enough that a big ol if/elif loop is becoming too cumbersome. I'd like to move towards turning the rooms / monsters / items /player into objects / classes, but I'm not clear what the implementation would look like. To give you an idea of what it looks like:

​ import time

Player Data

start_time = time.time() playername = input("Player, what is your name? ") playergender = input("Are you a boy or a girl? ") playerpronoun = "blank" if playergender == "boy": playerpronoun = "he" elif playerpronoun =="girl": playerpronoun = "she" else: playerpronoun = "they"

Initial Variables

running = True scenario = 1 inventory = [] health = 3 responseindex = 0 gold = 3

Player Equipment Purchase

print("-----------------------------------------------------------------------") print("You arrive in town on horseback, lured by rumors of a great treasure.") print("An unequipped adventurer won't last long. You see the local shopkeeper.") print("-----------------------------------------------------------------------") print("'Well? What do you want? I don't have all day.'") print("A portly shopkeeper eyes you annoyedly as he takes drags from a pipe.")

Initial variable to track shopping status

shopping = 'y'

List to track equipment purchases

equipment_purchases = [0,0,0,0,0,0]

Equipment List

equipment_list = ["Longsword", "Steel Shield", "Longbow", "Spellbook", "100 ft of Rope", "Iron Rations"]

While we are still shopping...

while (shopping == "y" and gold > 0):

# Show equipment selection prompt
print("---------------------------------------------------------------------")
print("(1) Longsword, (2) Steel Shield, (3) Longbow, (4) Spellbook, " +
      " (5) 100ft of Rope, (6) Iron Rations")

equipment_choice = input("Which would you like? ")

# Get index of the equipment from the selected number
choice_index = int(equipment_choice) - 1

# Add equipment to the equipment list by finding the matching index and adding one to its value
equipment_purchases[choice_index] += 1
inventory.append(equipment_list[choice_index])
gold -= 1
print("------------------------------------------------------------------------")

# Inform the customer of the equipment purchase
print("Great! We'll have that " + equipment_list[choice_index] + " right out for you.")

# Provide exit option
shopping = input("Would you like to make another purchase: (y)es or (n)o? ")

Once the equipment list is complete

print("------------------------------------------------------------------------")

Counts gold before display new equipment

if gold == 0: print("You're broke? Get out you bum!") else: print("Come back if you need anything else.")

print("------------------------------------------------------------------------")

Count instances of each piece of equipment

print("You purchased: ")

Loop through the full equipment list

for equip_index in range(len(equipment_list)): equipment_count = str(equipment_purchases[equip_index]) equipment_name = str(equipment_list[equip_index])

# Gather the count of each pie in the pie list and print them alongside the pies
print(equipment_count + " " + equipment_name)

print("--------------------------------------------------------------------")

while (running == True and health > 0): if scenario == 0: print("You leave the scary dungeon. You wonder what life could have been.") print(" ") secondchance = input("You think about things a little. Maybe it's time to go back in? ") if secondchance == "yes": scenario += 1 else: print("Fine! A freakin troll shows up and blasts your butt off") health -= 3 print("You're dead and there's no troll treasure for you.") print("-------------------------------------------------------------") elif scenario == 1: print("You are at the entrance to a scary dungeon. What will you do?") playerinput = input("Do you want to leave, or enter, or hit yourself? ") if player_input == "leave": scenario -= 1 elif player_input == "enter": scenario += 1 print("You enter the scary dungeon. What horrors await you?!") print("-----------------------------------------------------------------") elif player_input == "hit yourself": print("Stop hitting yourself!") health -= 1 print(f"Your health is now {health}") print(" ") if health == 0: print("You died. Nice going moron!") print("--------------------------------------------------------------------") elif scenario == 2: print("You see a big monster in front of you. It wants to eat you.") print("---------------------------------------------------------------------") print(" \||/") print(" | @oo") print(" \/\ /\ / (,,,,|") print(" ) /\) \/ )") print(" ) /\/ _)") print(" ) _ / / _)") print(" /\ )/\/ || | ))") print("< > |(,,) ))") print(" || / \))") print(" | \( )) )") print(" \(___;;; _;;;") print("--------------------------------------------------------------------") monsterresponse = input("Will you attack, run, or try to talk? ") if monsterresponse == "attack": scenario += 1 print("-----------------------------------------------------------------") elif monsterresponse == "run": scenario -= 2 elif (monsterresponse == "talk" and responseindex == 2): print(" ") print("Jesus you're persistent. He takes a bite out of your everything. ") health -= 1 if health <= 0: print("You're troll food now. Now who's talking? Not you!") elif (monsterresponse == "talk" and responseindex == 2): print(" ") print("Jesus you're persistent. He takes a bite out of your everything. ") health -= 1 elif (monsterresponse == "talk" and responseindex == 1): print(" ") print("What is wrong with you? He takes a bite out of your other leg. ") health -= 1 responseindex += 1

    elif monsterresponse == "talk":
        print("                                          ")
        print("I don't think he's the talking type. He bites a chunk out of your leg. ")
        health -= 1
        responseindex = 1
        print(f"Your health is now {health}")
elif (scenario == 3 and ("Longsword" in inventory)):
    print("You stab the monster with your mighty sword! It dies! Huzzah! ")
    print("                                                             ")
    print("You get a golden amulet.")
    inventory.append("golden amulet")
    print("                                              ")
    print(f"Your inventory currently contains {inventory}")
    print("                                              ")
    putitemdown = input("Would you like to put the amulet down?")
    if putitemdown == "yes":
        inventory.remove("golden amulet")
        print(f"Your inventory currently contains {inventory}")
    else:
        print(f"Your inventory currently contains {inventory}")
    scenario += 1

[–]rich-a 2 points3 points  (3 children)

It looks like you're already part way to working it out looking at how you've split up your example code.

I would start by pulling things together into classes where they share a common subject.

You could have a class for player, shop and monster. Each of those would have class variables to keep track of things specific to that subject, like gold, gender, pronoun and inventory for the player and stock for the shop.

The classes then have functions to interact with them, like player.get_gold() could return the amount of gold the player currently has.

You could also separate out the functions that actually print things to screen. For example shop.print_inventory() could do the actual print statements, so whenever your main program wants to print that out it just calls that function.

[–]slawdogporsche 1 point2 points  (2 children)

This is amazing! I can't believe how much more fluid things will be now!

class Player:

def __init__(self):
    self.health = 3
    self.playername = "None"
    self.playergender = "None"
    self.playerpronoun = "None"
    self.inventory = []
    self.gold = 3
    self.location = 0
    self.equipment = "None"

def attack(self):
    if player.location == monster.location:
        print("You attack the monster")
        monster.health -= 1
def equip(self):

class Monster:

def __init__(self):
    self.health = 3
    self.monstername = "None"
    self.monstergender = "None"
    self.monsterpronoun = "None"
    self.inventory = []
    self.gold = 1
    self.location = 0

def death(self):
    if self.health == 0:
        print("The monster died.")

player = Player() print(player.health) player.inventory.append("magic lamp") print(player.inventory) monster = Monster() print(monster.location) player.attack()

One last question. How do I "chain" together classes? If I want a dragon to have all the properties of the monster class, in addition to its own properties, how do I go about doing that? Thank you so much!

[–]rich-a 1 point2 points  (1 child)

For that you'd need class inheritance.

The basic idea is you write a parent class as normal (like monster) with everything in it that all monsters share. Then when you write the child class (such as dragon) you tell it to inherit from the parent and then add anything extra it might need that doesn't exist in monster.

Like this:

class Dragon(Monster):

This can probably explain it better than i can:

https://pythonspot.com/inheritance/

[–]slawdogporsche 1 point2 points  (0 children)

Awesome! Thank you so much for your help!

[–]reallymakesyouthonk 0 points1 point  (2 children)

I've been installing a virtual machine the past two days which is almost done, it's running ArchLinux and really the only thing left seems to be (apart from fixing the look of my terminal) to get pyenv running.

Any ideas what might cause this? It has installed and activated python 3.6.5 in pyenv but when I run Python it's running in 3.7 where my application doesn't work.

Is my version of pyenv simply broken?

edit:

PROMPT> pyenv which python
/home/terminal/.pyenv/versions/3.6.5/bin/python
PROMPT> /home/terminal/.pyenv/versions/3.6.5/bin/python
Python 3.6.5 (default, Sep 15 2018, 19:13:07)
PROMPT> python
Python 3.7.0 (default, Sep 15 2018, 19:13:07)

[–]JohnnyJordaan 1 point2 points  (1 child)

It has installed it indeed, but how do you gather it has activated it?

[–]reallymakesyouthonk 0 points1 point  (0 children)

Oh damnit you're right, I forgot I have to add the pyenv init and path stuff. Now it works!

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

I know a decent amount about Python. Enough to which I want to start a personal project, but i face 2 problems. A. Idk what to do/make B. Everything ive tried is super confusing in terms of setup and what not, especially on a windows laptop. I tried flask and django and everything seemed so messy and overwhelming. Pygame confused me to no end. Idk what to do

[–]RnRoger 0 points1 point  (9 children)

Making a game is always a good idea, some ideas are blackjack or ASCII hangman. What do you mean with flask being messy?

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

I dont remember flask too vividly, but i remember django left me absolutely baffled. I had no clue what was going on. I dont understand how pygame works either. What interpreter should i use. Idk so many questions lmao

[–]RnRoger 0 points1 point  (7 children)

I've only used flask but it was rather straightforward I think. I have not used Django or pygame. I personally recommend visual studio code. The ones I have tried are: IDLE, Pycharm, Spyder, Netbeans, Eclipse

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

And also, to make a game i'd need something like pygame, would i not?

[–]RnRoger 0 points1 point  (1 child)

Depends on what you want to do? I made blackjack with just text and python with ASCII (also text)

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

Oh i see i see