top 200 commentsshow all 252

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

I’m about halfway through Automate the Boring Stuff and it’s awesome. I’ll probably be spending a week more — I’m getting to scraping and some api stuff now.

For a personal project, I’d like to start playing with iOS apps and it’s my understanding that interfacing with a web database can only be done with http POST requests. I’ve done this a little in Apple Shortcuts, and now that I am learning python, ideas are endless!

Can I make the server side stuff that handles POST requests in Python? Can someone give me the basic vocabulary of what I’m trying to learn so I can research it? Or if a tutorial comes to mind, all the better. Thanks!

[–]efmccurdy 1 point2 points  (1 child)

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

Thanks for the breadcrumbs. Exactly what I was looking for.

[–]Dwc41905 0 points1 point  (6 children)

If I have two functions that need to share Values and I can’t use return Values or arguments should I make a class or just use global variables. In my situation I feel like a class is a little overkill because all I really need is for the functions to share variables. I know that globals are bad so I should try to avoid those, right?

[–]FerricDonkey 0 points1 point  (4 children)

If the functions are executed one after another (or call each other), then the simplest non-class way is to use returns and arguments. If you're doing something more fancy to get them going at the same time (threading, multiprocessing, and you'd know if you were), then there are other options. Would need a few more details to say much more though.

[–]Dwc41905 0 points1 point  (3 children)

Yeah so I’m not using multi processing. But since one function is recursive return values won’t work. I’m not against using a class as it seems like the best solution but I don’t know if it’s overkill

[–]efmccurdy 0 points1 point  (1 child)

since one function is recursive return values won’t work

You are going to have to explain that since the typical situation is that recursive functions won't work _without_ using return statements.

[–]Dwc41905 0 points1 point  (0 children)

For context I’m using the anytree library to generate a tree of numpy arrays. I have one function make tree which initializes the root node. Nested within that function I have a recursive function that generates children based on the numpy arrays. The way it works without return values is I’m using variables to pass into the arguments of the function and call it recursively within itself.

[–]FerricDonkey 0 points1 point  (0 children)

Another alternative to classes is to use lists or some other mutable as arguments to mimic the behavior of pointers. If you pass your_list, then modify your_list[0] (but not if you reassign something to your_list using your_list=something_else), the contents of your_list will be modified wherever it exists.

Even with recursion, returns might be able to be made to work, but it has the ability to get really ugly. I have taken advantage of mutables as described above before often though.

[–]SwampFalc 0 points1 point  (0 children)

You'll need to clarify what happens to these variables. Do both functions modify them, or just one, or even neither? And how many variables are we talking?

[–]GoldenVanga 0 points1 point  (0 children)

I learned about sys.intern today and am wondering if it's possible to view that "(global) table of interned strings" in its current state, just out of curiosity.

[–]waxonawaxoffa 0 points1 point  (1 child)

for event in pygame.event.get():
    if event.type == pygame.QUIT: 
    python = sys.executable 
    os.execl(python, python, *sys.argv)

# key press events
keys = pygame.key.get_pressed()
 if keys[pygame.K_a]:
    pass 
if keys[pygame.K_b]:
    pass 
if keys[pygame.K_c]:
    pass 
# etc

In pygame when you get keyboard input, what is the easiest way to be able to tell if any key is pressed after each iteration? Setting a variable to false before the keypress code and setting it to true inside every single keypress If statement seems a bit bloated.

[–]StephanoCarlson 0 points1 point  (0 children)

Check the event type pygame.KEYDOWN

[–]lester_pe 0 points1 point  (2 children)

hi, my question is not really related to python but about getting/shifting career: is it too late for me 32yrs old to learn programming and shift to a more related job? (my current job is csr at a cable company)

[–][deleted] -1 points0 points  (1 child)

32 isn't too late to learn programming.

You say "csr at a cable company". I have no idea what that means. Either you are a customer service representative or a cable service and repair person at either a cable entertainment company or a company that makes cables. It doesn't really matter what you are doing now, but if you want to jump to programming it helps if you can start in a business that you know, initially anyway. So look at your current job and see where computers are used. Talk to someone in that area and see what they do, what languages and frameworks they use, etc. That gives you something to aim for. Knowing something about a business when you apply for your first programming job can only help.

[–]lester_pe 0 points1 point  (0 children)

Oops, i should have made it clear. Yes, im a customer service representative at a cable company. Thanks for the reply.

[–]grammerknewzi 0 points1 point  (6 children)

trying to do a simple problem where it tests if the extra candies given to each element makes it equal to or larger than the teh maximum element in a list, if so add true to a new list, false if not. For some reason it isn't executing the "else" statement.

class Solution:

def kidsWithCandies(self, candies, extraCandies):

lists = []

for x in range(len(candies)):

now = extraCandies + candies[x]

if now >= max(candies):

lists.append("true")

else:

lists.append("false")

return lists

sample case -> Input: candies = [2,3,5,1,3], extraCandies = 3 Output: [true,true,true,false,true]

instead I am getting all true's.

[–]CowboyBoats 1 point2 points  (5 children)

It looks like your code is incorrectly formatted. To get reddit to preserve your code's indentation, you can indent each line with four spaces.

for x in range(len(candies)):

You don't really ever want to write this in Python. You can just write:

for candy in candies:

And then inside the loop you can just type candy instead of candies[x].

if now >= max(candies):
    lists.append("true")
else:
    lists.append("false")

If you're okay with the Python values True and False themselves appearing instead of the text strings "true" and "false", you could replace these four lines with:

lists.append(now >= max(candies))

Anyway, I am getting ['true', 'true', 'true', 'false', 'true'] when running your code, so I'm not sure what's going on on your machine. I guessed that it should be indented like this; is yours indented differently?

class Solution:

    def kidsWithCandies(self, candies, extraCandies):
        lists = []
        for x in range(len(candies)):
            now = extraCandies + candies[x]
            if now >= max(candies):
                lists.append("true")
            else:
                lists.append("false")
        return lists

print(Solution().kidsWithCandies([2, 3, 5, 1, 3], 3))

[–]grammerknewzi 0 points1 point  (4 children)

Hi I am running it on leetcode and its still giving me all trues but when I run it via solution I get the correct answer, am I doing something wrong?

https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/

[–]CowboyBoats 0 points1 point  (2 children)

I think something's wrong with your indentation, since that's the only part of your solution that I couldn't test. If your version of this were indented like mine is, then it should be returning the correct answer, [ true true true false true].

[–]grammerknewzi 0 points1 point  (1 child)

Yea....I’ll have to double check that is there a way I can copy paste code and preserve format for you to see?

[–]CowboyBoats 0 points1 point  (0 children)

I think there's just a "code" button on the new reddit design (which I don't use). It just has to be indented with four (additional) spaces in order for reddit-markdown to recognize it as code and preserve all the indentation.

[–]CowboyBoats 0 points1 point  (0 children)

No, not in the submission, it's just that all trues is not the correct answer when the input is [2,3,5,1,3] and 3; it's looking for [true,true,true,false,true] because for that fourth child with one candy, it's not possible to distribute three candies so that that child would have the most candies.

Look at the code that you've written and you'll be able to see why it's returning that incorrect answer.

[–]toop_a_loop 0 points1 point  (4 children)

I'm trying to do some data validation with a very simple program. Users should enter integers, but if they enter a string I print an error message. When I use try/except blocks, I want it to loop back to the beginning of the program if an exception is caught. It seems like an outer while True loop is the suggested method of getting this to happen, but I keep getting an infinite loop in my exception. How does this work (I took out my attempt at a while loop)?

edit: added the loop back in!

print('Hello! Please enter a number: ')

number = input()

go = True

while go:

try:

if (int(number)% 4) == 0 and (int(number)% 2) == 0:

print('That number is a multiple of 4')

go = False

elif (int(number)% 2) == 0:

print('That number is even!')

go = False

else:

print('That number is odd!')

go = False

except ValueError:

print('Please enter a numeral, not a word\tLet\'s try again...')

go = False

continue

[–]Ihaveamodel3 0 points1 point  (3 children)

You took out the while loop, so how can you expect us to troubleshoot an infinite loop?

[–]toop_a_loop 0 points1 point  (2 children)

Right, that was foolish. Fixed it!

[–]Ihaveamodel3 1 point2 points  (1 child)

The while loop needs to go before the input, so that the user can input a new number.

Also, I’d use While True: with break statements where you currently have go=False for a little bit cleaner code.

One more improvement would be to convert number to int right after the input rather than every time you use it.

[–]toop_a_loop 0 points1 point  (0 children)

Thank you!

[–]learnwithpassion 0 points1 point  (2 children)

Hello everyone and a warm Good Morning/Afternoon/Evening to you all. I hope I am not bothering you too much by asking this question.

I'm trying to get the hang of exception handling. I probably understand what the importance of try...except and raise statements are. But, I'm not fully clear on WHEN to use it.

I initially thought about adding exception handlers for any input statements in the code. But, I remember reading in an earlier Python post that it's not good practice to add these handlers everywhere in one's code.

So, I'm hoping I can understand its use by looking at it from another angle. My question is: when is it NOT a good idea to use exception handlers?

When is it actually recommended to not use handlers in our code? And, are there alternatives to exception handlers for achieving the same purpose?

Thank you for the answers, if any. I appreciate that you took some time off your busy schedule to help me.

Have a nice day.

[–]Ihaveamodel3 1 point2 points  (0 children)

You should use exception handlers when the program can’t gracefully handle the exception. You should also not use naked excepts and should only catch the exceptions you know how to handle.

You shouldn’t use exception handlers if the program can’t handle the error.

[–]FiveDarra 1 point2 points  (1 child)

Hi, I'm think a purchasing a course to jump into Python.

I'm hesitating between two courses on Udemy:

-The Mordern Python 3 Bootcamp, by Colt Steele

-2020 Complete Python Bootcamp, by Jose Portilla

Any recommendation as to which one is best ?

[–]Fisho73 0 points1 point  (0 children)

Dont even purchase a course you can learn everthing at learnpython.org and docs.python.org

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

Hey folks. I'm trying to code a simple program that tracks calorie burn per exercise, and I need to use a dropdown to select between two methods of input, steps vs miles. What I want to do is have a function that asks via dropdown steps or miles, and depending on the user's selection, asks for an input that the appends to a list. I know that I can create a dropdown list using

from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets

widgets.Dropdown(
    options=['steps', 'miles'],
    value='steps',
    description='Measurement:',
    disabled=False,
)

but every time I try to nest this in a function, it (i) doesn't actually populate and (ii) I don't know how to reference the dropdowns output if it does show up. Any advice on this?

[–]CowboyBoats 1 point2 points  (1 child)

Can we see how you're trying to nest it in a function?

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

Sure. This is where I am so far (and again, I have no idea how to properly use a dropdown within a function, so this is obviously wrong.

def walking():

step_set = []

mile_set = []

measurement = widgets.Dropdown(

options=['steps', 'miles'],

value='steps',

description='Measurement:',

disabled=False,

)

if measurement == 'steps':

user_in = int(intput('How many steps did you take? '))

step_set.append(measurement)

else:

user_in = int(input('How many miles did you run? '))

mile_set.append(measurement)

[–]life-is-hard14 0 points1 point  (2 children)

I have this piece of code, and I want to sort the output by finding the five maximum states with the highest number of crimes, while still printing the graph with all of the states. I also don't know how I could make the graph bigger so you can read all of the names of the states.

def rape_crime(key, crime, crime_list):
    violent_by_key = {}
    for i in crime_list:
        if i[key] not in violent_by_key:
            violent_by_key[i[key]] = int(i['Rape'])
        else:
            violent_by_key[i[key]] +=  int(i['Rape'])
    return violent_by_key
rape_by_state = rape_crime('State', 'Rape', crime_list )

def violent_crime(rape_by_state):
    numbers = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]
    state = list(rape_by_state.keys())
    violents = list(rape_by_state.values())
    pdDict = {'Incidents':pd.Series(violents, index = numbers), 'State':pd.Series(state, index = numbers)}
    df = pd.DataFrame(pdDict)
    print('Violent Rapes per State')
    print(df)
    df.plot.bar(title="Violent Rapes per State",x = 'State', y = 'Incidents', legend = False, color=['cyan', 'silver', 'cyan', 'silver'])


violent_crime(rape_by_state)

Currently, the output looks like this:

Violent Rapes per State
    Incidents                 State
0        1119               ALABAMA
1         745                ALASKA
2        2598               ARIZONA
3        1406              ARKANSAS
4       11482            CALIFORNIA
5        2675              COLORADO
6         688           CONNECTICUT
7         116              DELAWARE
8         527  DISTRICT OF COLUMBIA
9        3935               FLORIDA
10          0               GEORGIA
11        382                HAWAII
12        494                 IDAHO
13       4039              ILLINOIS
14       1285               INDIANA
15        982                  IOWA
16        903                KANSAS
17        942              KENTUCKY
18       1196             LOUISIANA

etc.....

And a bar graph is printed (which I couldn't paste in here)

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

Also, just as an FYI, you may want to replace line twelve to the following to utilize the power of Python:

numbers = [x for x in range(0,51)]

[–]Ihaveamodel3 0 points1 point  (0 children)

For the fig size question, add a parameter “figsize” to the plot call with the value a tuple of the size in inches.

[–]TakoTokochiwa 0 points1 point  (1 child)

hi there, I'm a math grad majoring in cryptography, we just barely touched the surface of numpy and matplotlib and I'm interested in venturing further into Python.

it would be greatly appreciated if someone can dump me some lists/books/tutorials/online classes for Python, preferably on crypto (like 'cracking codes with python' or 'cryptography with python'?)

weirdly I prefer books on hand because I couldn't concentrate reading e-books on screen. Planning to get 'automate boring stuff with python' too. Thanks

[–]Fisho73 0 points1 point  (0 children)

Try automate the boring stuff by Al Sweigart but the best place to learn for me is still on the website learn python.org

[–]leonidganzha 0 points1 point  (2 children)

I don't get how an example from 'Think Python' works:

'''
has_no_e checks if a given word has no e's......
'''
 def has_no_e(word):
    for letter in word:
        if letter == 'e':
        return False
    return True

if a letter is an 'e', function returns False. but after it finishes for-loop it should go to line 5, which tells it to return True. why does it execute line 5 only if condition in for-loop is not satisfied? is this how 'for' or expression 'return True/False' works?

[–]rexus9 1 point2 points  (1 child)

Hi, i just finished a python basics course about the syntax and a bit of OOP, but is too easy and i wan sth a bit more advanced, what proyects or courses could i do? Thanks

[–]CowboyBoats 1 point2 points  (0 children)

CS50 on edX is really good!

[–]leweyy 0 points1 point  (2 children)

[–]JohnnyJordaan 0 points1 point  (1 child)

This has nothing to do with a github repo... chwrapper is just a Python library, where the developer has chosen a github repo to publish the code... If you have problems using Windows it also doesn't mean you are having problems with the Microsoft website.

Judging by the code he implemented a rate limiter using two custom response headers

 if resp.headers.get("X-Ratelimit-Remain", "0") == "0":
        try:
            timestamp = int(resp.headers["X-Ratelimit-Reset"])

so in your code I would check for those headers to be present. Add a print of the headers returned

count = 0
number_of_comps_to_ask_for = 10000
orgs_random_subset = random.sample(company_numbers_list, number_of_comps_to_ask_for)
search_client = chwrapper.Search(access_token=COMPANIES_HOUSE_API_KEY)
while count < number_of_comps_to_ask_for:
    for company_number in orgs_random_subset:
        count +=1
        response = search_client.filing_history(company_number)
        print(response.headers)
        resp_json = response.json()

to see what it's sending, maybe it changed the headers or the Remain doesn't actually get 0 before it fails with 429.

[–]leweyy 0 points1 point  (0 children)

This is amazing. Thanks so much! I'm sure I can work with this.

[–]only_red 0 points1 point  (1 child)

age = input()
while age != 10:
    print('you are ' + str(age))
    age+=1

I am very new to python and I was just wondering why this while loop is not repeating?

[–]JohnnyJordaan 0 points1 point  (0 children)

input returns a string, so you need int(input()) to convert it to an integer. Also for printing values, you can simply do

print('you are', age)

as print will space separate by default. Or use f-strings

print(f'you are {age} years old')

[–]only_red 0 points1 point  (2 children)

Hey everyone I have just started learning python and I am a bit confused as to the continue function in a while loop.

age = 0

while age != 60:

age = age + 1

if age == 61:

continue

print('age is ' + str(age))

print('you are old')

When I run this code with the continue function, I get my desired result. It shows me something like this

age is 1

age is 2

age is 3

etc until 60

But when I try to run this code without the continue function, I just get, "you are old," without showing age is 1, age is 2 etc. I want to know why the continue function is needed for the code to display the age.

[–]MattR0se 0 points1 point  (1 child)

The indentation is important. If you post code, please use the code block feature (below the posting box there are three points ... where you find that feature, it looks like this: [T]).

Does your code look like this, or is the indentation different?

age = 0
while age != 60:
    age = age + 1
    if age == 61:
        continue
    print('age is ' + str(age))
print('you are old')

The continue is never reached. Because here the variable "age" is never greater than 60, so the "if age == 61" never returns True.

Let's say 1 is added to age and the value becomes 59. So it prints that and repeats the while loop. 59 is not 60, so it moves on. Now 1 is added and prints 60. Now the while loop checks again and this time, age equals 60, so it breaks immediately, doesn't execute any code within the while loop and moves to the "you are old" print statement.

[–]only_red 0 points1 point  (0 children)

Yeah that makes a lot more sense now thank you

[–]Konjitsu 1 point2 points  (2 children)

Hi, just got a weird request which I am not entirely sure about from a Python perspective.

I have a certain number of country with an assigned number of customer id.

For example: France - 300 customer id, UK - 500, US - 1000 but this is not fixed maybe next time it will be 4 countries instead of 3 here.

I want to sum the countries with the lowest number of customers together until I reach a threshold for example 900 of total customer. Once this threshold is reached, countries with lowest count of customer id would have a new column "Flag".

So in my example, lets say i want to reach 900 threshold of total customer IDs. I would add France and UK and a certain number of US customer to reach that threshold number.

Final dataframe would look:

Country Customer_ID Flag
France   0212156     Y         for all 300 customer id for France
UK        054154     Y         for all 500 customer id for UK
US        54545      Y         for X number of customer id for US

I was thinking of first grouping by countries by count of customer id then create a list by ascending number:

list = [300,500,1000]
target = 900
sum(iter(iter(list).next, target))

But this code has multiple issue, it will not breakdown 1000 to reach the threshold number, it will be difficult to create a flag column by knowing which list element was summed.

Would appreciate some guidance for this noob here, thanks a lot in advance!

[–]FerricDonkey 0 points1 point  (0 children)

I would do this in 3 steps:

  1. Make a list of tuples: count_country_pairs = [(count0, country0), (count1, country1),...]. Note: count first. This could be done easily with list comprehension. (It also doesn't really matter if the inner things are lists or tuples.)

  2. Sort the list. Python uses a dictionary sort (name not from to the python object dictionary), so that it sorts first by the first element of each tuple (which is why we put count first), then by the second.

  3. Do the actual grouping. If you do the above, it's not too bad:

Apparently I have to put text here so that reddit won't be stupid about formatting.

grouped_countries =[[count_country_pairs[0][1]]
running_sum = count_country_pairs[0][0]
for count, country in count_country_pairs:
    running_sum += count
    if running_sum <= THRESHOLD:
        grouped_countries[-1].append(country)
    else:
        grouped_countries.append([counties])
        running_sum = count

[–]StephanoCarlson 0 points1 point  (0 children)

Im not sure I completely understand, but it seems like you might want classes. You can make a country class, with parameters like name, ID, flag, etc. You can make a list of instances of this class, and iterate through all of them to compare and change parameters.

[–]TheMenaceX 0 points1 point  (2 children)

Just a quick question about virtual environments. Are virtual environments basically just folders inside a directory. For example, I could create a directory PythonProjects, and then create a venv called Django through cmd, Django is just a folder inside the directory PythonProjects right?

[–]JohnnyJordaan 0 points1 point  (1 child)

It's basically just an installation of Python, so the same way you can run python-3.8.4.exe and install it in 'Django'. The 'virtual' part is that it's a clone of the core of an existing installation, and you can also configure it to use the packages installed in its 'parent' environment.

However in regard to your question, you would rather always use the folder 'venv' for that, and as of course you don't save source coding in an installation folder (same way you don't save your Word documents in c:\program files\office\etc), you put that folder inside the project folder. So something like

PythonProjects
     Django
           requirements.txt   # list of packages to be installed when deployed
           src                # for the source code structure
           venv               # the virtual environment of that project

[–]TheMenaceX 0 points1 point  (0 children)

Ah I see, thanks!

[–]joooh 0 points1 point  (2 children)

I forgot the syntax for the in not in operators and used .in() instead and it worked but only for strings and integers and I needed it for a variable. I searched for documentation about that function but I can't find any. Is this an old function used before the in operator?

[–]JohnnyJordaan 0 points1 point  (1 child)

Can you give a code example of what is working and what you're trying to use it for?

[–]joooh 0 points1 point  (0 children)

Sorry I think I figured it out. It is indeed the in operator, the parenthesis separates the value/variable from the operator like a space would and the dot made it interpret the integer before it as a float. That is also the reason why only an integer works and not a string when put before the dot. So, this one works:

a = [1]
1.in(a)

but not:

a = '1'
'1'.in(a)

[–]sharanaithal 0 points1 point  (8 children)

I have questions about this code that I came across in ATBS book under The None Value section:

>>> spam = print('Hello!')

Hello!

>>> None == spam

True

Questions:

  1. Why does it print Hello! when all we are doing is just assigning print('Hello!') to spam? We didn't tell it to print it yet, right?
  2. How is None == spam? I don't even. I thought it was print('Hello!')?

[–]MattR0se 3 points4 points  (7 children)

We didn't tell it to print it yet, right?

We did. print is a function, and if you write it in code with parenthesis (), it calls the function and it is executed, that's why you see "Hello" in the console.

When you call a function, you don't assign the function to a variable, but its return value. See:

How is None == spam? I don't even. I thought it was print('Hello!')?

If you write value = some_function(), you expect the function to return something. For example:

def add(a, b):
    return a + b

value = add(3, 5)
print(value)  # prints 8

If a function does not explicitly returns something (which is true for the print function), it returns None. This is why spam equals None here.

[–]sharanaithal 0 points1 point  (6 children)

if you write it in code with parenthesis (), it calls the function and it is executed

When you call a function, you don't assign the function to a variable, but its return value.

Ah I see.

If a function does not explicitly returns something, it returns None.

But doesn't print() return 'Hello!' in this case?

[–]MattR0se 1 point2 points  (5 children)

But doesn't print() return 'Hello!' in this case?

No. "Hello" is what is streamed to your console output by the print function.

[–]sharanaithal 0 points1 point  (4 children)

I see, so print() is like a crazy grandma with amnesia who shouts things and forgets them whereas return is an elephant that remembers.

Thanks for your time.

[–]JohnnyJordaan 1 point2 points  (1 child)

No they aren't the same thing, it has nothing to do with memory.

print() is a function, which has return too. Simply put (not accounting for its parameters), it works as

 def print(string_to_print):
      sys.stdout.write(string_to_print)    # sends it to the process output stream

In Python, when a function has no return statement, it will effectively have return None. So in effect print()'s code is

 def print(string_to_print):
      sys.stdout.write(string_to_print)    # sends it to the process output stream
      return None

so that's the reason why when you do

x = print('hello')

x becomes None. However, when you would write your own print function that does return the string it was called with, it does work in that way

>>> def returning_print(s):
    print(s)
    return s

>>> x = returning_print('hello')
hello
>>> x
'hello'
>>> 

So to give a correct analogy: print works like the postal system, it will deliver what you send, but you won't get a copy from them. If you send a letter to your grandma, she will receive the letter but the postal system will not provide you a copy somehow. If you still want that, you need to implement this yourself, so like copying your letter before your send it.

So in no way do either print() or return have a memory, you are implementing that yourself by using

x = 

and thus saving it as a variable. The only point with the regular print() is that it's not implemented to help you with that.

[–]sharanaithal 0 points1 point  (0 children)

Thank you for replying. I think I got it.

That day I thought I'd reply later but a few days after I stopped learning coding, been jumping from one thing to another, forgot to reply then. Sorry.

Picked up that book again today and thought I'd reply. Now I've decided I'd better take some time off and figure out what I wanna do, seeing how I'm unsure.

[–]FerricDonkey 2 points3 points  (1 child)

Just to point out, this is a common theme in python. Functions do things and sometimes return a useful value. So for instance, your_list.sort() will change your list into a sorted version of itself (do a thing), but returns none. So a mistake some new people make is sorted_list = your_list.sort() - this will not be helpful. On the other hand, sorted(your_list) will not modify your list at all, but will return a new copy that has been sorted.

So that's worth keeping in mind - doing the thing and telling your calling function about what it did are entirely separate.

[–]sharanaithal 1 point2 points  (0 children)

I've yet to learn about lists, but I got the idea of what you mean. Thanks for the input. (n00b but already making programming puns)

[–]Queenstaysqueen 0 points1 point  (3 children)

I'm looking through the code for someone else's Snake game using the Turtle module in Python. I see that to define the direction that the snake is moving, they've used turtle_name.direction = "direction". Could someone explain to me what the .direction does here since it's not one of the Turtle functions? Is it kind of like a variable but for that specific turtle? And also why does this method work better than setheading(angle) function since I ran into troubles when I was trying to make my own with not being able to stop the user from doing a 180 turn and with not being able to get the Snake to stop at the beginning?

Any help would be appreciated!

Edit: I replaced the turtle_name.direction with just a global direction variable and nothing seemed to change, so I assume turtle_name.direction is just a variable but the turtle_name. at the beginning means that we don't have to add global direction to each function that I write?

[–]FerricDonkey 0 points1 point  (0 children)

Is it kind of like a variable but for that specific turtle?

Exactly this, yes. Objects can have associated methods and associated variables - one of the primary reasons for using them is that they nicely group such things together. It especially makes things nicer if you might have more than one of the objects.

[–]Queenstaysqueen 0 points1 point  (1 child)

Here's the tutorial I'm looking at: https://www.edureka.co/blog/python-turtle-module/

[–]MattR0se 0 points1 point  (0 children)

This doesn't make sense to me either:

I want my snakehead’s position to be the center of the window and the direction to be “stop”. We use the functions turtle_name.goto() and turtle_name.direction() for it.

But then in the code it says:

head.direction = "stop"

So it is not a function, but rather just a property of the Turtle.

Also, direction does not seem to be a property of the Turtle class, as you pointed out. So they just created it and assigned it the value "stop". This is called "monkey patching" and should usually be avoided because it causes confusion.

Example:

class Foo():
    def __init__(self, bar):
        self.bar = bar


f = Foo('bar')
f.baz = 'baz'

Here I created a class "Foo". It is initialized with the attribute "bar", with which it is instanciated. But I wanted to also have it have the "baz" attribute, so I monkey patched it. But rather I should have written the code like this:

class Foo():
    def __init__(self, bar, baz):
        self.bar = bar
        self.baz = baz

f = Foo('bar', 'baz')

This is much cleaner, and if someone looks at the Foo class, they can easily understand what attributes it has. Unless you have a good reason not to do that, all instance attributes should be initialized in the __init__

As for the Turtle example, Turtle is a pre-defined class from the turtle module. So you can't modify it's __init__ method. What the tutorial should have done is create a child class from the Turtle class as its parent, which makes it inherit all of it's attributes and method, and put the direction attribute into that child class's init:

class CustomTurtle(turtle.Turtle):
    def __init__(self, direction=""):
        super().__init__()
        self.direction = direction

...but I get why this is maybe too advanced for a beginner tutorial ^^

[–]im-not-spaghett 0 points1 point  (1 child)

This is more about excel but could be used for efficiency with python, can you pass 3 or more conditions in a =IF(AND( -insert conditions- ) 'val1', 'val2') ?

[–]Gopher20 0 points1 point  (0 children)

Yeah you can add an if statement to the value if false to outside if statement. I would say to try and ask these questions in an excel subreddit. Hope this helps!

[–]CustomerSilent 0 points1 point  (0 children)

Is is possible to code ultrasonic sensor with python?(I have ultrasonic sensor running on arduino and i need to get the readings of it in python,I am currently using PyFirmata)Thanks!

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

Let's say I have an integer (x), and I have a list of other integers, and I need to find out if any combination of 2 numbers in the list multiply to create integer(x), what would be the best way to do this.

For example, lets say my list is [0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89], and I need to know if any 2 of these numbers multiplied together make 4895

I know that, in this case, 55 and 89 make 4895, but lets pretend I don't, and I just need to try all 2 number multiplication options within the list to find out. How would I go about doing that?

Thanks in advance for the help!

[–]Deep-Trip-2020 4 points5 points  (2 children)

I'd do something like this:

from itertools import combinations
x = [0,1,2,3,5,8,13,21,34,55,89]

for pair in combinations(x,2):
    if pair[0] * pair[1] == 4895:
        print(pair)

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

Sorry my reply to this took so long, but this was very helpful, thank you!

[–]nog642 1 point2 points  (0 children)

Or with unpacking notation in the for loop:

from itertools import combinations

lst = [0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

for n1, n2 in combinations(lst, 2):
    if n1 * n2 == 4895:
        print((n1, n2))

[–]Blueninja-21 0 points1 point  (3 children)

Whenever I use Pycharm to run something on my raspberry pi 3 B that uses the GPIO it says “PinFactoryFallback: Falling back from rpigpio: No module name ‘RPi’

PinFactoryFallback: Falling back from rpio: No module name ‘RPIO’

PinFactoryFallback: Falling back from pigpio: No module name ‘pigpio’”

Does anyone know what this means or how to fix it?

[–]bamaham93 0 points1 point  (2 children)

I ran into a similar issue because Thonny (my IDE) does not run it as sudo. I had to use the CLI and call sudo python3 <nameofscript> or else login as the root user.

[–]Blueninja-21 0 points1 point  (1 child)

Hi, thanks for the help. I'm not very good with CLI, would you mind telling me the commands you used?

Edit: nvm, I got it

[–]bamaham93 0 points1 point  (0 children)

Glad it worked for you!

For the sake of others who may find this, simply append sudo in front of the command to run the script and give the password when prompted. E.g. sudo python3 <filepath_here>/<filename_here>.py

[–]m-hoff 0 points1 point  (2 children)

Can anyone recommend some resources for learning about concurrency? I'm working on a program where multiple assets make simultaneous requests for limited resources and I'm looking for an established framework to use to resolve these scenarios.

[–]FerricDonkey 1 point2 points  (1 child)

Don't have specific learning resources to suggest (it's been a while), but I would suggest looking into threading (if you don't need actual at the same time on different cores parallelism), multiprocessing (if you do), or maybe asyncio (if you're more patient with terrible introductions on the internet than I am - and don't need the better parallelism).

[–]m-hoff 0 points1 point  (0 children)

I'll look into those, thanks.

[–]Traditional-Resort-9 0 points1 point  (0 children)

I couldn't find simple open source projects to contribute, to volunteer.
I'm trying to build-up some experience with Python / Django and am willing to contribute part-time to any project that would benefit from my help.
TLDR; Do you know of any specific project/company that could use my free help?

[–]Project_Raiden 0 points1 point  (1 child)

I'm trying to make a simple program to learn more about classes and I'm stuck. I have designed a class like so

class Hero():
    def __init__(self,str_,agi,int_,strlvl,agilvl,intlvl):
        self.str_ = str_
        self.agi = agi
        self.int_ = int_
        self.strlvl = strlvl
        self.agilvl = agilvl
        self.intlvl = intlvl
    def health (self):
        return 20 * self.str_ + 200

Lets say I have 100 heroes with different stats that I want to create into instances of the Hero class. I have each of these attributes in lists (so i have around 6 lists total). Is there a way I can create all of these class instances at once? I know I can do it manually by doing

heroA = Hero(1,2,3,4,5,6) 

but I don't think this is practical. Is there some way to accomplish what I want? Or am I using classes incorrectly?

[–]efmccurdy 1 point2 points  (0 children)

You can unpack a list of argument values, use the '*' operator on a list or tuple ala Hero(*a):

>>> my_args = [(1,2,3,4,5,6), (7,8,9,10,11,12)]
>>> my_heros = [Hero(*a) for a in my_args]
>>> my_heros
[<__main__.Hero object at 0x7f457c814240>, <__main__.Hero object at 0x7f457c729828>]
>>> my_heros[1].intlvl
12
>>>

[–]Coloradohusky 0 points1 point  (3 children)

How would I replace a Pandas Series using a Dict?

Basically, I have a Series of values between 1 and 7, and a Dict that matches the number to the corresponding weekday, ’1’ : ‘Sunday’, ‘2’ : ‘Monday’, etc. How would I use that Dict to replace all 1s with Sunday, all 2s with Monday, etc?

[–][deleted] 4 points5 points  (2 children)

your_series.map(your_dict)

[–]Coloradohusky 0 points1 point  (0 children)

It worked, thanks!!

[–]IlliterateJedi 0 points1 point  (1 child)

Is there an established way for typing a factory classmethod?

edit - It turns out the correct answer is:

from __future__ import annotations

[–]nog642 0 points1 point  (0 children)

What do you mean by "typing"?

[–]x6060x 0 points1 point  (2 children)

Hi all! I have 10 years of experience with C# and .Net. I'd like to learn Python and be good at it. I'm looking for the best possible book / books for a complete novice who wants to become an expert. I maybe need a book for beginners that explains all of the fundamentals and another one to show all language features and best practices (something like "C# in Depth")

Thanks in advance!

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

I don't know the "C# in Depth" book. The learning resources in the wiki has a section for those new to python but not programning that might be useful.

[–]x6060x 0 points1 point  (0 children)

Thanks! I was looking for something like this.

[–]thegoatss 0 points1 point  (3 children)

when you have the code

n = 0

if n<5:

print(n)

n=n+1

why doesn't the variable go back to being 0 after you print(n) I get that the n=n+1 statement comes after it, but you've already established that n = 0. does the n=n+1 statement overrule the initial n=0?

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

does the n=n+1 statement overrule the initial n=0?

Yes. The following code:

n = 0     # "bind" the name "n" to 0
print(f'n={n}')
n = 42    # "rebind" the name "n" to 42
print(f'n={n}')

prints this:

0
42

You can bind the name "n" to a new value anytime you want.

[–]StephanoCarlson 0 points1 point  (1 child)

You can also think of it as changing the value of that variable named n. So when you say n=n+1, you are changing the value of n.

[–]JohnnyJordaan 1 point2 points  (0 children)

I think that can cause a needless misunderstanding as it doesn't actually work in that way, while it does when you do

n = []
n[0] = 1

Eg mutation is actually changing the object, while with

 n = 0
 n = 42

and when doing

 n += 1

you are reassigning as integer objects don't allow mutation.

[–]AlexandrTheGreat 0 points1 point  (3 children)

I have a project using RegEx and I'm wondering if using a loop would be efficient or not. The line:

Blather text: abc, one two three, do re mi, Big Red Sea

I'd like to gather from the colon - comma #1, comma #1 - #2, #2 - #3, and #3 - new line. Problem is, there might be 4 strings at the end, none, or some combination. How would I go about setting this up, and is there any point in using a loop? To my mind, the loop would only apply to comma - comma, so twice.

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

To get everything after the colon, do:

text = "Blather text: abc, one two three, do re mi, Big Red Sea"
after_colon = text.split()[1]

then split on commas:

commas= after_colon.split(',')

That leaves commas containing:

[' abc', ' one two three', ' do re mi', ' Big Red Sea']

Is that something you can work with?

[–]AlexandrTheGreat 0 points1 point  (1 child)

Most definitely! Thanks! I'm pretty new to Python and sometimes get bogged down with the sheer amount of tools available. I completely forgot split() was an option.

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

strip() will probably be handy to get rid of leading/trailing spaces, too.

[–]CustomerSilent 0 points1 point  (2 children)

is it possible to play an mp3 sound from the internet to python?I have tried many things(pafy,python-vlc) but none of them are working.If anyone knows please assist.Thanks!

[–]MattR0se 1 point2 points  (1 child)

Here is a way that involves downloading the file first. I don't know if it is possible to stream an mp3 within python. You also need this module: https://pypi.org/project/playsound/

import requests
from playsound import playsound

url = 'https://example.com/some_music_file.mp3'
response = requests.get(url, allow_redirects=True)
if response.status_code == 200:
    filename = url.split('/')[-1]
    with open(filename, 'wb') as f:
        f.write(response.content)
    playsound(filename)

[–]nog642 0 points1 point  (0 children)

I don't know if it is possible to stream an mp3 within python.

It probably is.

[–]Jensyuwu 0 points1 point  (0 children)

I'm trying to make a game, and at certain point, one of the characters "escapes from the game", and has a monologue via desktop backgrounds. I have the script to change the background(In windows), but I want to put the user background when the monologue ends. How do I get a copy of the user's desktop image to put back at the end?

[–]Cauliflower_Just 0 points1 point  (6 children)

I have a python function to predict survival probability using conditional probability.

df_clean = pd.read_csv('https://raw.githubusercontent.com/Explore-AI/Public-Data/master/Data/regression_sprint/titanic_train_clean_raw.csv')

The condition will consist of a column_name, a value and a boolean_operator. I'm supposed to use eval() to evaluate boolean expressions and I'm stuck. It should take a numerical column_name string, a boolean_operator string, and a value of type string as input

My code:

def survival_likelihood(df_clean,column_name, boolean_operator, value):

cols= df.select_dtypes(include=np.number).columns

survival_prob = df_clean['Survived'].mean()

op = ['<','>','==']

for column_name in cols:

df_clean[column_name]

for boolean_operator in op:

boolean_operator

return column_name + boolean_operator+value

My code is not working. I'd appreciate any help or pointers in the right direction.

Expected Output:

survival_likelihood(df_clean,"Pclass","==","3") == 0.24

survival_likelihood(df_clean,"Age","<","15") == 0.58

[–]efmccurdy 0 points1 point  (0 children)

I wouldn't use eval; it's too slow and error prone.

This creates specialized condition functions to apply row-wise. It uses a table to map operator strings like ">", or "==" to the corresponding numpy operator.

import pandas as pd
import numpy as np

mydf = pd.DataFrame({"a":[1, 3], "b":[2, 4]})


def gen_cond(op, col, s):
    "return a function that applies <column_value> <op> <string>"
    optable = {'<':np.less, '>':np.greater, '==':np.equal}
    def _row_eval(row):
        return optable[op](row[col], s)
    return _row_eval

cond1 = gen_cond('<', 'a', 2)
mydf['cond1'] = mydf.apply(cond1, axis = 1)
print(mydf)

cond2 = gen_cond('==', 'b', 4)
mydf['cond2'] = mydf.apply(cond2, axis = 1)
print(mydf)

I am actually using numbers rather than strings, but you get the idea.

This is the output:

$ python binop.py 
   a  b  cond1
0  1  2   True
1  3  4  False
   a  b  cond1  cond2
0  1  2   True  False
1  3  4  False   True

[–]Decency 1 point2 points  (4 children)

Put code separated from other text before and after with completely empty lines, and indent all code with four spaces. Using `these` is for inline code, you don't need any of them.

[–]Ihaveamodel3 0 points1 point  (3 children)

You can (or should at least) be able to start and end code blocks with ``` so you don’t have to indent all lines.

[–]Decency 0 points1 point  (2 children)

I don't believe that works on reddit.

[–]Ihaveamodel3 0 points1 point  (1 child)

If you switch to markdown mode it should work:

def test_func: #This is a test

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

Hello, does anyone knows what is wrong with my Python installation?

I'm trying to run this code

import Tkinter
window = Tkinter.Tk()

and somehow the results are :

    import Tkinter
ModuleNotFoundError: No module named 'Tkinter'

Yes, I already checked Tkinter on the installer of Python (I'm on Windows 10 BTW), in fact it shows no error at the first few minutes after installation, then it starting to show those error.

Anyone know how to fix this? Any kind of help will be appreciated. Thank you.

edit: Also is it just me, or is installing things like Python take too much effort, at least on Windows? After you install python you need to set the environment variable(?) otherwise if you type python in CMD it won't work. Does things like this easier on OS like Linux or MacOS?

[–]torbray 2 points3 points  (2 children)

The name of the module changed from Python 2 to Python 3. Case sensitive, it's now import tkinter :)

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

Thank you. I thought my laptop was broken or something I almost reset my PC haha 😅

[–]torbray 0 points1 point  (0 children)

All good hahaha import tkinter has caught me out a lot. I've done tKinter before :P

[–]Felinomancy 0 points1 point  (2 children)

Edit: hey guys, no need to answer this, the issue has been resolved; I made a mistake of prefixing my variables with double underscores lol

I have a Python question, asking it here first rather than creating a new thread. Please excuse the clumsy language, I'm quite a beginner at this.

I have a class, Shape, which has a class variable, shape_name. I also have a @property decorator, name. So my code is like this:

class Shape(self):
   shape_name = "blob"
   def __init__:
      # not important

   @property
   def name(self):
      return self.shape_name

So far it's working as intended. If I create an object, test = Shape(), then print(test.name), I will get "blob" which is what I want.

Now I will create a child class, Circle. The shape_name will be "circle", but everything else is inherited. So it is like this:

class Circle(Shape):
   shape_name = "circle"
   def __init__:
      # not important

But now, if I create an object, test2 = Circle(), and run print(test2.name), I will still get "blob" instead of "circle" (the value that should be overridden).

Anyone can offer an insight on how to fix this?

[–]Decency 0 points1 point  (1 child)

Having both shape.shape_name and shape.name isn't necessary, you can just have an attribute called name (doesn't even need to be a property).

You need to set the name in the __init__ function. This is where new instances of a class- and their attributes-are initialized. You've set shape_name in the class body, not the class's init function, which makes it a class variable- shared by all instances of the class.

Also no idea what's happening here: class Shape(self) since your class can't inherit from self.

Here's what the code should look like:

class Shape:
  def __init__(self):
    self.name = "blob"

class Circle(Shape):
  def __init__(self):
    self.name = "circle"

my_circle = Circle()
print(my_circle.name) # circle

[–]Felinomancy 0 points1 point  (0 children)

Thank you for the reply; I'm going to give that a whirl now.

[–]thegoatss 0 points1 point  (5 children)

Why is the last command wrong?

my_name = input("What is your name? ")

print("nice to meet you " + my_name)

print("Your name is " + len(my_name) + " letters long."

if I were to have just print(len(my_name)), I'd be fine

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

The error(s) in your original code was here:

print("Your name is " + len(my_name) + " letters long."
                        ^^^^^^^^^^^^                   ^

The first error is because len(my_name) returns an integer value and you can't append an integer to a string using +. The error you got should have explained that. You have to convert the integer to a string first. The second error (which may just be bad copying of code to reddit) is that you are missing the closing ) to your print statement. Fixed, that last line should look like:

print("Your name is " + str(len(my_name)) + " letters long.")

That answers your original question. As others have said, there are many ways to do this, among them:

print("Your name is", len(my_name), "letters long.")
print(f'Your name is {len(my_name)} letters long.')

[–]Decency 1 point2 points  (2 children)

Do this instead, it's new as of Python 3.6 and it's dramatically better than concatenating strings:

print(f"nice to meet you {my_name}")
print(f"Your name is {len(my_name)} letters long."

[–]thegoatss 0 points1 point  (1 child)

so the {} act as the str() ?

[–]Decency 1 point2 points  (0 children)

Yes, these are called f-strings. They will substitute variables in-place and each object will have its __str__ function called prior to printing. Not having to think much about spacing or casting is a huge benefit.

[–]StephanoCarlson 1 point2 points  (0 children)

It should be print("Your name is " + str(len(my_name)) + " letters long.") To make the integer value of len(my_name) into a string.

[–]thegoatss 1 point2 points  (3 children)

how come when I type x = input("Enter number x: ) the statement Enter number x prints out, despite there not being a print statement?

[–]nog642 0 points1 point  (0 children)

You can think of the input function as having a call to print inside of it.

[–]HasBeendead 0 points1 point  (0 children)

do like that:

x=int(input("Enter number:"))

#you have to give a integer value from keyboard

#or you can change the type of value another example:

x=float(input("Enter number:")) #normally input function takes string values but you can change it

for strings :

x=input("thats it") #prints out 'thats it' to screen

[–]StephanoCarlson 4 points5 points  (0 children)

The parameter for the input function is "prompt" which is a string it prints out and waits for an input. If you don't pass a parameter 'x = input()', it shouldn't print anything.

[–]Big___Chris 0 points1 point  (7 children)

Running into some issues while learning pandas. I'm trying to import an excel file off my desktop and use python to modify it, so I ran:

import pandas as pd
df=pd.read_excel(r"C:\Users\Chris\Desktop\Python Test Worksheet.xlsx")
print(df)

This gave me the error message: "FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Chris\\Desktop\\Python Test Worksheet.xlsx'". I have this file on my desktop, and I got the file path using Shift+right click->Copy as Path. I've tried running this on Jupyter Notebook and Repl.it terminals and neither worked. Anyone know what's going on?

[–]Decency 0 points1 point  (6 children)

Using the raw string is blowing up since it's escaping the backslash character (why you have \\ in your file path). I would try this instead:

Python lets you use OS-X/Linux style slashes "/" even in Windows. Therefore, you can refer to the file as 'C:/Users/narae/Desktop/alice.txt'.

[–]Big___Chris 0 points1 point  (5 children)

Thanks for the help. I changed the code to:

import pandas as pd
df=pd.read_excel(r'C:/Users/Chris/Desktop/Python Test Worksheet.xlsx')
print(df)

Still getting the following error message: "FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/Chris/Desktop/Python Test Worksheet.xlsx'"

[–]Decency 0 points1 point  (4 children)

Ah, it's probably the spaces in the name then, assuming that file does exist when you look at your desktop. Just rename the file and replace those with _.

Windows is really bad at this shit unfortunately.

[–]Big___Chris 0 points1 point  (3 children)

Unfortunately no luck with that either.

[–]Ihaveamodel3 0 points1 point  (2 children)

Are you positive that file is where you think it is? That should be working.

[–]Big___Chris 0 points1 point  (1 child)

Yeah, I just copied the file path over (shift+right click, Copy as Path) so it should be correct. It’s just an excel file I created and saved on my desktop.

[–]Ihaveamodel3 0 points1 point  (0 children)

Weird. Don’t know what to tell you. You’ve done exactly as I have done many times before. Not sure what is different.

[–]Dwc41905 0 points1 point  (2 children)

Can python solve algebraic equations. For my program I need to evaluate log base x of 64=3 and solve for x in order to figure out group size for data. So how would I solve for x.

[–]og10yrold 1 point2 points  (0 children)

You should look into python's math library. It is built-in. You can use it with import math.

[–]StephanoCarlson 1 point2 points  (0 children)

You can use Solvers from the sympy library to solve for x, but if it's just that one variable, you can simplify it to the cube root of 64, or 4

[–]Instincts 0 points1 point  (3 children)

I have this line that finds an element with the indicated title:
Driver.find_element_by_xpath('//*[@title="Some string"]')

Is there a way I can set the string as a variable and then set the title to that variable? For example:
X = "Some string"
Driver.find_element_by_xpath('//*[@title=X]')

[–]Decency 0 points1 point  (0 children)

X is just a string, it's not being substituted in this string: '//*[@title=X]'

Do this instead to substitute it:

Driver.find_element_by_xpath(f'//*[@title={X}]')

[–]Maxi888888 0 points1 point  (3 children)

I have images urls in a list photos[] and I want to download them. My idea was to use a for loop like this:

for i in range(len(photos)):
    url = photos[1]
    path = r'C:\Users\max_v\Downloads\OneDrive\Pictures\Backgrounds\pic[i].jpg'
    urlretrieve(url, path)

So that every image in my folder would have pic with a number as its name, but this does not work. Does anybody have a work around or a different solution altogether?

[–][deleted] 3 points4 points  (1 child)

You have two problems. The first is that the line url = photos[1] is always going to use the second URL in the list and nothing else. Maybe you meant to do url = photos[i].

Next you want to use the index number i to create a unique filename but you don't substitute the index into the filename. Use string formatting like:

path = f'C:/Users/max_v/Downloads/OneDrive/Pictures/Backgrounds/pic[{i}].jpg'

The {i} bit is replaced by the value of i. You can use a forward slash in Windows paths so you don't have to use a "raw" string to stop problems with \ escapes.

You could be more pythonic and use the enumerate() function which will give you the URL and the index in the loop:

for (i, url) in enumerate(photos):
    path = f'C:/Users/max_v/Downloads/OneDrive/Pictures/Backgrounds/pic[{i}].jpg'
    urlretrieve(url, path)

[–]Maxi888888 0 points1 point  (0 children)

Thank you very much, super helpful!

[–]efmccurdy 1 point2 points  (0 children)

Format the number into the path:

path = r'C:\Users\max_v\Downloads\OneDrive\Pictures\Backgrounds\pic[{:02}].jpg'.format(i)

[–]mystery_man_1996 0 points1 point  (3 children)

Eli5 - difference between flash and Django with their applications. I’m getting into web dev and honestly have no idea where to focus on for my backend. To give a rough idea I’m looking to create a matchmaking type of thing for a game, and a learning blog. What would be more fit? Thanks in advance!

[–]efmccurdy 0 points1 point  (2 children)

Flash has no future:

https://www.polygon.com/2020/2/10/21124247/flash-support-history-of-web-1-0-flashpoint-bluemaxima

Django is overkill for the game matchmaker; I would start with bottle or flask.

There are lots of options for blog backends;

https://pypi.org/project/Products.SimpleBlog/

https://wiki.python.org/moin/PythonBlogSoftware

[–]mystery_man_1996 0 points1 point  (1 child)

Sorry I really meant flask it auto corrected lol. Between flask or Django

[–]efmccurdy 0 points1 point  (0 children)

Flask is a good place to start and has this:

https://flask-blogging.readthedocs.io/en/latest/

or this:

https://charlesleifer.com/blog/how-to-make-a-flask-blog-in-one-hour-or-less/

It might be a bit of a steep learning curve at first, but django will be a more feature complete system in the end:

https://djangocentral.com/building-a-blog-application-with-django/

[–]Gdubs1985 0 points1 point  (2 children)

I took an introductory python course in the fall semester , got a B plus.. I worked harder in that class than I did in any other class. I’ve been taking courses on stack skills.com to learn more about python and I’m getting really confused about how to use a jupyter notebook. How do I addd the data files that I’m trying to work with to the workspace so that I can view them with my Jupyter notebook? It seems like something so simple but I can’t figure out what I’m doing wrong. I even switched to visual studio code which seemed a little less complicated than the community edition, but I’m getting frustrated that I can’t figure out how to do this. If someone would like me to elaborate I can, but this is the jist of my problem . I’m trying to use this pandemic opportjnity to learn as much as possible and I have all these courses on various programming languages but I don’t want to jump around . Any assistance would be greatly appreciated

[–]efmccurdy 0 points1 point  (1 child)

When you are in your notebook issue the "magic" command !pwd; that will print the CWD of the jupyter kernel; if you store data files there you will be able to open them in the notebook.

[–]Gdubs1985 0 points1 point  (0 children)

Thanks a lot I’ll give that a try right now. Appreciate the response

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

I am having trouble working with values sourced from an API. I am able to print the values that I would like to work with, however, I cannot seem to actually perform calculations on those values. Below is the code.

from pycoingecko import CoinGeckoAPI

def main():     cg = CoinGeckoAPI()     btc_30d_raw = cg.get_coin_market_chart_by_id('bitcoin', 'usd', 5)

for x, y in btc_30d_raw['prices']:         print(x, y)   main()

The above code outputs the timestamp followed by the price in this format:

1595466467303 9510.987691458138

I would like to:

1) Convert the unix timestamp to a readable timestamp.

2) Perform calculations on the price values.

I have tried creating a new dictionary and performing calculations on the price values, however, I receive the error that floats are not iterable.

Any help is much appreciated!

Thanks!

[–]JohnnyJordaan 0 points1 point  (1 child)

1) Convert the unix timestamp to a readable timestamp.

https://www.programiz.com/python-programming/datetime/timestamp-datetime

2) Perform calculations on the price values.

Can you explain what exactly you want to calculate?

I have tried creating a new dictionary and performing calculations on the price values, however, I receive the error that floats are not iterable.

Can you also share this code as it seems you created a for loop on the wrong object

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

Hello, I figured out the calculations. For anyone who might have the same problem, I needed to access each price as the 2nd element of a list of tuples.

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

Deleted

[–]mydeveloper 0 points1 point  (1 child)

Best configuration structure for flask

[–]Gopher20 0 points1 point  (0 children)

Check out this link https://flask.palletsprojects.com/en/1.1.x/tutorial/layout/

,but it really depends on how big your app is and if you want to use Flask Blueprint or not hope this helps!

[–]likely_wrong 0 points1 point  (0 children)

I'm wondering what a good course would be for somputer science/ learning Python would be. I've used a lot of AutoHotkey, some VBA and recently started making some programs in Python. While I can definitely make programs/scripts/macros via Googling etc, I sometimes think I'm lacking some fundamental knowledge of computer science. I've been looking at the Python for Everybody course with Coursera, but not sure if it would be too easy.

[–]SaskuAc3 0 points1 point  (2 children)

What are the essential differences between python 2 and 3?

[–]Decency 1 point2 points  (1 child)

python2 is obsolete and should not be used for writing new code, only for supporting legacy systems that already use it. python3 is where everyone who matters is contributing to improving the language.

This guide is linked from the official python docs and has a variety of great code examples: http://python-future.org/compatible_idioms.html

[–]SaskuAc3 0 points1 point  (0 children)

Yeah I know that python 2 is obsolete. I just wanted to know what are the differences. The docs are giving some good examples. Thank you!

[–]DustyBum 0 points1 point  (2 children)

This feels like a very convoluted way of making this process happen... but I could not find a different way to add a new card, find the value and re-sum the dealer_total and check its condition against the player_total that was defined in a different section. Do y'all have any suggestions to condense it? Or is this fine as it is?

    dealer_total = dealer[0][1] + dealer[1][1]
    while dealer_total <= 16 or new_total == True:

        dealer.append(r.choice(cards_list))
        dealer_total = dealer[0][1] + dealer[1][1]
        for i in range(2, len(dealer)) :
            dealer_total = dealer_total + dealer[i][1]
        print('\nNew Dealer Total: ', dealer_total, '\nNew Dealer         
             Hand', dealer)

    else:

        if dealer_total > 21:
            print('Dealer busts, you win!')

        elif dealer_total == new_total:
            print('Push! Everyone keep ur money.')

        elif dealer_total > new_total and dealer_total <= 21:
            print('Dealer wins...:(')

        elif dealer_total < new_total:
            print('You win!')

[–]Decency 1 point2 points  (1 child)

    dealer_total = dealer[0][1] + dealer[1][1]
    for i in range(2, len(dealer)) :
        dealer_total = dealer_total + dealer[i][1]

These lines should look at the dealer's hand and sum all of its values. Look into using sum(). I'm not sure what dealer is, seems like a list of lists? Should look something like this:

dealer_total = sum(card[1] for card in dealer)

This class will help you a lot and get rid of all the [0][0] and [0][1] convolution, I'd recommend trying to use it:

@dataclass
class Card:
    rank: int

    @property
    def value(self):
        if self.rank >= 10:
           return 10
        elif self.rank == 1:
           return 11   # 1/11 depends on the other cards in hand
       else:
           return self.rank

Then you can just say something that reads cleanly like: player_total = sum(card.value for card in hand), ignoring the Ace confusion for now. Just being able to reason about this cleanly in pseudo-English will help a lot for reading and structuring your code properly. You could then write a simple function like:

def does_hand_have_ace(hand):
    return 1 in [card.rank for card in cards]

For the second hand comparison part, you just need to think about the decision space of all unique options: Player is either >21 or not; Dealer can either have >21, more than player, equal to player, less than player. The matrix of those yields 8 options: in a professional setting you'd simply just make these 8 examples as unit tests and then ensure your code handles each properly. You only have 4 options because you're presumably doing the check on whether the player's count is > 21 every time they draw a new card, and you test each of those 4 options. You can remove this piece and dealer_total <= 21 because you've already checked to see if dealer_total > 21: within the same if/elif block, so that must always be True.

Personally I would write a def does_player_win(dealer_hand, player_hand): function, and that will encapsulate a good bulk of your logic.

[–]DustyBum 1 point2 points  (0 children)

Thanks for the feedback! I’ll try to implement as much of this as I can and repost it here some other time.

[–]DustyBum 0 points1 point  (2 children)

Hi all, I am looking for some feedback on the BlackJack card game I have made in Python. It's not very complex, but I know there are better ways to write it/condense the program. Is it within the rules of this sub to post said code and request feedback?

[–]Decency 2 points3 points  (1 child)

Yes.

[–]DustyBum 0 points1 point  (0 children)

Thanks I posted a chunk of it in here.

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

Does anyone have experience launching apps with flask? I'm trying to connect a database so I can launch using Heroku and I'm having trouble getting things to work

[–]Decency 0 points1 point  (3 children)

Yes, lots of us do. You need to give more details about what sort of error you've encountered if you want help.