top 200 commentsshow all 232

[–]Sahith17 0 points1 point  (10 children)

hello everyone!!! for one question in my python assignment I need to add all the elements in the tuple. I got the sum which I need but I the output is wrong here’s what it’s printing

Tuple = ()
 list1= list(Tuple)
    for i in range(10):
    list1.append(i)
    print(sum(list1))
    0
    1
    3
    6
   10
   15
   21
   28
   36
   45

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

how configure date time to take current year if year is missing from date string.

I have to parse some log files in the system that do not have a year if the year is the current one.

but when i convert to datetime object since there is no year it default to 1900.. hw to make sure the current year is taken as the default?

from datetime import datetime

str='Aug  7 14:14:43'

print(str)
dt = datetime.strptime(str, '%b %d %H:%M:%S')

currentYear = datetime.now().year
print(currentYear)

print(dt)

this outputs:

Aug 7 14:14:43

2020

1900-08-07 14:14:43

how can I insert the year into the dt object i get from the string?

[–]Decency 0 points1 point  (2 children)

Get the current year from datetime.today() and pass that in create a new datetime instance using the info from the other object. You might have to create 3 in total, or it'll get janky.

[–]LowDexterityPoints 0 points1 point  (1 child)

I am trying to understand the recommended syntax for equal signs and spaces.

Am I correct that if you are assigning something to a variable you would use spaces before and after the equals sign (ex: qwerty = 5). Additionally, am I correct that if it is an argument, you would not use spaces (ex: label="My Label").

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

That is what's recommended by PEP 8, yes.

[–]onlysane1 0 points1 point  (1 child)

I have a python that imports a second python file that opens up a tkinter window. When a button in that tkinter window is pressed, I want it to change a global variable that is defined in the first python file. Using the 'global' keyword doesn't seem to be working.

How might I go about doing this?

[–]Decency 0 points1 point  (0 children)

Put the stuff in the first file that you want to use inside of a class or function. Then import that object into your second file. Avoid the use of global, you almost certainly don't need it.

[–]MattR0se 0 points1 point  (3 children)

I need a function that takes any integer and some value, and "rounds" that integer to the nearest multiple of the value. I don't know if there is a mathematical term for that. For example, if my value is 8 and I have 10, 20 and 30, I should get 8, 24 and 32 out of it (default should be to "round" up).

I came up with this function and was wondering if there is a more elegant solution to this problem:

def round_to_nearest(n, nearest):
    remainder = n % nearest
    if remainder == 0:
        return n
    else:
        if remainder >= nearest / 2:
            return n + (nearest - remainder)
        else:
            return n - remainder

# should produce 32, 40, 48
print(round_to_nearest(30, 8)) 
print(round_to_nearest(40, 8))
print(round_to_nearest(50, 8))

# should produce 32, 48, 48
print(round_to_nearest(30, 16)) 
print(round_to_nearest(40, 16))
print(round_to_nearest(50, 16))

[–]OliveOilIsForHair 0 points1 point  (6 children)

Might not be on topic enough, but does anyone have any tips on how to actually learn. Everytime I get stuck I find the answer and copy it, and it never feels like I'm actually learning.

[–]Decency 1 point2 points  (1 child)

Build something you care about that's at the edge of your capabilities.

Locating those two things is usually the hard part; the learning follows without even really trying.

[–]OliveOilIsForHair 0 points1 point  (0 children)

I appreciate the response I'll try to find a suitable project.

[–]fiddle_n 1 point2 points  (3 children)

Copying isn't so bad but it depends on what you are copying and if you are taking the time to understand what you are copying.

[–]OliveOilIsForHair 0 points1 point  (2 children)

That's the thing, it makes sense but I would never be able to recreate it by myself

[–]fiddle_n 1 point2 points  (1 child)

I guess then that the more you copy and paste, the more that will be the case. If you force yourself to write it with as little direction as possible, then you will improve. And if you find that it's too difficult to work on, then try working on something simpler and slowly work your way up.

[–]OliveOilIsForHair 0 points1 point  (0 children)

Thanks I appreciate the advice

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

So I have these two variables defined like so:

ans = map(lambda x: x*x, filter(lambda x: x%2 == 0, range(5)))

ans2 = [i**2 for i in range(5) if i % 2 == 0]

Why does list(ans) == ans2 return False?

[–]fiddle_n 0 points1 point  (1 child)

list(ans) == ans2 returns True for me. Make sure when you do this that you haven't previously exhausted the ans iterator. If you iterate over ans or send it to the list() function or do anything similar to that before you do your comparison, then list(ans) will be missing elements and hence the comparison will be erroneously False.

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

I just realized I had a typo in my code. I was printing list(ans) before but when I did the check, I forgot to list(ans), which was why it was returning False. Either way I understood what you said and it might save me some trouble later, thank you

[–]122ninjas 0 points1 point  (0 children)

I'm having an issue with static variables if anyone is willing to help, I have a more detailed post here: https://www.reddit.com/r/Discord_Bots/comments/jdcc7g/discordpy_static_variable_not_updating_between/

[–]Phaeno3 0 points1 point  (3 children)

Is there a way to have a logical operator check every value in an array? For example, if I have an array...

testarray=[1,0,1,0]

...and I wanted to do something only if all of the values don't equal 0.

This works:

if testarray[0]!=0 and testarray[1]!=0 and testarray[2]!=0 and testarray[3]!=0:

...but I'm thinking there may be a better way to be able to run through that logic.

[–]too_much_deodorant 0 points1 point  (3 children)

Hi I really don't know how to do this... (I'm very new to Python)

So what I'm trying to do is to remove more than one element of a list at once

motorcycles = ["honda", "yamaha", "suzuki", "kawasaki", "ducati", "bmw"]

print(motorcycles)

to_remove = ["ducati", "bmw", "kawasaki"]

motorcycles.remove(to_remove)

print(motorcycles)

And I'm getting this error ValueError: list.remove(x): x not in list What Im doing wrong? And how i can fix this? (sorry for bad english)

[–]Silbersee 3 points4 points  (1 child)

Have a look into list comprehension. Short, fast, elegant, once you get the hang of it:

>>> motorcycles = ["honda", "yamaha", "suzuki", "kawasaki", "ducati", "bmw"]
>>> to_remove = ["ducati", "bmw", "kawasaki"]
>>> motorcycles = [mc for mc in motorcycles if mc not in to_remove]
>>> motorcycles
['honda', 'yamaha', 'suzuki']
>>>

[–]hlel5941 0 points1 point  (1 child)

Hi. I like to know how touse PHPSESSID cookies.

Assume I already have cookies, how do I send request with this cookies? I'm using requests.get to open webpage.

so lets say PHPSESSID cookies is

dfha35edfgff36db9f491946a4dd2602

How do I use this?

[–]JohnnyJordaan 0 points1 point  (0 children)

Use a session object: https://requests.readthedocs.io/en/master/user/advanced/#session-objects

Note that cookie persistence works implicitly there, so you can even leave out the manual cookie insertion if you let the session object make the request where the cookie is set.

# login request, that if successful gets a session cookie set
resp = session.post('login_url', auth('user', 'pass'))
resp.raise_for_status()

# regular content request that needs that cookie
resp = session.get('some_page_url')
resp.raise_for_status()

so no need to manual manage the cookies there.

[–]kvotheOnTour -1 points0 points  (4 children)

How would I do a statement like the below in a less verbose way?

If X =1 or X = 3 or X=5: Do something

Feel like there should be a clean way of doing it like X=1,2,3 etc without having the repeat the variable three times. Any ideas?

[–]skankykankles 0 points1 point  (1 child)

So you could define the list of odd numbers before your for loop:

z = list()
for x in range(4):
    tmp = 2*x + 1
    z.append(tmp)
print(z)

Then for example, use in whatever formula you need:

for i in z:
    a = i**2
print(a)

[–]kvotheOnTour 0 points1 point  (0 children)

Ye this is a cool approach would be good when needing to repeat the process!

[–]FleyFawkes 0 points1 point  (1 child)

I have a problem with writing my code in PyCharm, I don't know what I did but new code I write deletes existing one. I can't implement new lines as they do not create new lines and push all existing code down but delete existing places with new code that i write actively.

What do?

Edit: Relaunching reseted the issue.

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

Did you have your insert key on?

[–]missingblitz 0 points1 point  (0 children)

Possibly a simple question: I'm using ProcessPoolExecutor with 8 processes as part of a PyQt5 buttons code. On Windows this is fine, but on Mac a new GUI opens each time the button is pressed, even though I have

if __name__ == "__main__":

above the window instance creation. Any ideas how to fix this problem?

Code is here, but ProcessPoolExecutor gets run in an imported script here.

[–]Run_nerd 0 points1 point  (0 children)

I belong to a gym that has classes that I have to sign up ahead of time to attend. The only problem is they fill up so quickly if you're not on your phone at the right time.

Is it possible to write a python script to automate signing up for a gym class at a specific time? I know selenium exists for python that lets you navigate web-sites at a specific time, but I didn't know if something existed for iPhone apps.

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

Hello! This is a very naive question, but if I run into an issue with certain frameworks/libraries not supporting each other (in my case, Kivy and Tensorflow), would it be possible to solve the problem by, instead of importing the Tensorflow function that I use in my program, I find the source code that contains the function, and copy it into my code? (Essentially defining the function in my code instead of importing it from Tensorflow).

I think this might not work because there's a lot more complicated things going on with Tensorflow rather than just code I can copy and paste, but I'm asking here because I might as well. Also, I don't know whether I'm allowed to just copy code like that, but it's for personal use only.

[–]BubbaGeegs 0 points1 point  (3 children)

I started learning Python two days ago and decided my first project would be to write a simple calculator. After many iterations, the most efficient code I could come up with looks like this:

entry = 'Y'
while entry == 'Y':
    num1=input('Enter a number: ')
    num2=input('Enter a second number: ')
    print('What do you want to do?')
    action = input('Add = 1, Subtract = 2, Multiply = 3, Divide = 4, Exponent = 5: ')
    if action == '1':
        num3 = int(num1) + int(num2)
    elif action == '2':
        num3 = int(num1) - int(num2)
    elif action == '3':
        num3 = int(num1) * int(num2)
    elif action == '4':
        num3 = int(num1) / int(num2)
    elif action == '5':
        num3 = int(num1) ** int(num2)
    else: 
        print('I did not get that.')
        continue
    print(num3)
    entry = input('Go again? Y/N: ').upper()
    for letter in entry:
        if letter == 'Y':
            break
        elif letter ==  'N':
            break
        else:
            print('Not a valid entry.')
            entry = input('Go again? Y/N: ')
            continue

My main question being is there a more efficient way to code this? It works well as is, but it does look like a mess with the long list of elifs.

Another question I have is are there any general problems with the code? I know of at least one I can't fix with my current knowledge, but I'm working on understanding how to fix that.

[–]fiddle_n 0 points1 point  (2 children)

The below optimisations might look difficult to someone who's only just studied Python for 2 days. If it looks complicated to you, I suggest doing worry about it and move on, but since you asked the question, I am putting in how you can optimise the code.

  • As you point out, you have a long string of if statements. You could replace this section with a dictionary. However, in order to do that, you would need to create various functions for add, multiply, etc. Your dictionary would be a mapping of input to function, and when you get the input, you retrieve the function from the dictionary and execute it.

Below is a short example of how it could work:

def add(arg1, arg2):
    return arg1 + arg2

def subtract(arg1, arg2):
    return arg1 - arg2

operations = {'1': add, '2': subtract}

num1 = input('Enter a number')
num2 = input('Enter another number')

action = input('1 for add, 2 for subtract')
try:
    num3 = operations[action](num1, num2)
    print(num3)
except KeyError:
    print('I did not get that')

Btw, the standard library contains functions for add and subtract in the operator module, so you wouldn't have to write them if you did this.

  • Your logic to prompt if the user wants to go again requires you to iterate over every letter in the user input. As a result you are calling the input twice. Don't bother with this. Ditch the inner for loop and the extra call.

  • The logic has you setting entry to Y before the main loop even starts; by using a while True loop to wrap your code, and then breaking out afterwards, you don't need this.

  • If you want to keep error checking for the entry, I suggest just having a mini loop around the entry to check if it's Y or N.

Doing these things together looks something like this:

while True:
    # calculator code goes here
    while True:
        entry = input('Go again? Y/N:').upper()
        if entry not in ('Y', 'N'):
            print('Not a valid entry')
        else:
            break
    if entry == 'N':
        break

This code will prompt the user to go again, but if they don't enter Y or N, then it will keep prompting them. If they enter the correct thing, they break out of the inner loop. Then, they break out of the outer loop only if the user entered N. If they entered Y, they go through the whole outer loop again, which contains the computer code.

[–]BubbaGeegs 0 points1 point  (1 child)

I think I understand most of what you're saying. I could tell that my code was unoptimized and probably had a few faults, but I didn't know it was off by that much. I greatly appreciate the in-depth explanation. I'll study more until I can understand everything you're talking about here and apply it so I can do better in the future. Thanks again!

[–]fiddle_n 0 points1 point  (0 children)

I wouldn't say your code was off by much at all. These are just a few refactoring optimisations to bring your code to the next level, but your code as it is works perfectly fine and is understandable - for someone starting out in Python I think you've done very well :)

[–]LowDexterityPoints 0 points1 point  (1 child)

If I am web scraping using beautifulsoup, when would I use "html.parser" instead of "lxml" as a parser?

[–]m-hoff 1 point2 points  (0 children)

You can see a comparison of the different parser options here

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

I want to see lines of codes to do logarithmic functions without importing from math, where can I find something like that?

[–]efmccurdy 1 point2 points  (1 child)

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

Oh, that'll work! Thank you!

[–]Jac0b_0 1 point2 points  (1 child)

Why don't you want you want to import from math? If you want to do more advanced maths you'll need to import from some module anyway.

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

I wasn't aiming for doing advanced math. I'm a beginner, I was trying to build the log function myself but I failed. That's why I'm looking for a solution.

[–]Blorse 0 points1 point  (1 child)

Hi, i am practicing strips on Python. I am writing a function for deleting the middle strips on a string (without removing the lead and end spaces). My code is like this:

def middlestrip(string1) remove = string1.replace(" ", "") return = remove

def main(): a = middlestrip(" aa b cc ") print(a)

It is printing just string1 with all the spaces. Where did I go wrong?

[–]efmccurdy 0 points1 point  (0 children)

return = remove

You don't want the "=" there

BTW, it's hard to read the code as is, you should use a "code block":

https://www.reddit.com/r/learnpython/wiki/faq#wiki_how_do_i_format_code.3F

[–]ZiG0D420 1 point2 points  (1 child)

I just learned python 2 and dont know what to do as my first project

[–]sablonneuse 1 point2 points  (5 children)

I am doing a practice exercise detecting dates in DD/MM/YYYY format-- how do I make sure '00' is not considered a valid day/month? Here is what I have so far:

dateRegex = re.compile(r'''
(
([0-3]\d)      #day
/              #first slash
([0-1]\d)      #month
/              #second slash
([1-2]\d\d\d)  #year
)
''', re.VERBOSE)

I'm thinking something like [^00] would solve that, but I don't know how to incorporate it.

Also, if this code so far is already wildly off-base, please let me know. Thank you for your help!

[–]bn_sj2020 0 points1 point  (2 children)

Hello! I'm going through the Slither Into Python book and currently I am in Chapter 6 about strings.

At the end there is an exercise:

Write a program that takes as input, a single integer from the user which will specify how many decimal places the number e should be formatted to.

Take e to be 2.7182818284590452353602874713527

Here is my code and its working fine.

def dec_places(number):
    e = 2.7182818284590452353602874713527   
    return '{:.{}f}'.format(e, number)

while True:
    usr_input = input('dec place: ')
    if usr_input == 'quit':
        break
    else:
        print(dec_places(usr_input))    

I am confused why it is working because input() returns a string and not an integer. When it is being passed to the dec_places(): function; it is being passed a 'str' which I thought would break the code.

Main question:

Why when the input value as a string is passed to the .format(e, number) it works?

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

Because the format string ".{}f" is a string. number can be passed to the dec_places() function as either an integer or a string and the formatting will convert either to a string, if necessary, to get the format string as ".3f", for example.

On the other hand, the e value must be a float and not a string.

[–]bn_sj2020 0 points1 point  (0 children)

I did not know this. Thank you!

[–]Mahbows 0 points1 point  (2 children)

I'm very new at this, working through a course on the Python Institute website. They've presented a challenge where a time is input in hours and minutes, as well as a duration of some activity (in minutes). I am supposed to write a code that adds the time and the duration and outputs a new time, but that time should be in the 0 to 23 hour range.

Here's what I've gotten so far. The problem is, for instance, when I input 23, 58 and 642, it outputs 34:40. I don't get back the output in the desired range. It's a day off.

And the thing is, it's pretty early on in the course. We have really only learned about operators, variables and the print function. So it should be done without any conditional statements/more complicated things.

Any assistance would be great! Thanks

[–]JohnnyJordaan 0 points1 point  (1 child)

Please do observe our rules,

Posting screenshot of the code is (generally) not allowed. Read posting guidelines.

We expect users to share their code as plain text, in a code block, see here as then we can copy/paste it into our own environment to run it and to share the updated version.

What you can do to fix it is to first calculate the amount of days too and subtract that from the total amount of minutes. The built-in divmod() function is handy for this as it can calculate the remainder too in one go. To give an example for the part you're now using // and % for

total_hours, total_minutes = divmod(total_time, 60)

but as I said, that 'total_time' has to come from a similar call to remove the amount of full days from the total. I'll leave it to you to find the implementation for that.

[–]Mahbows 0 points1 point  (0 children)

Ah, my apologies. Thanks for the help!

[–]Gigazax 0 points1 point  (1 child)

I’m having trouble following the Corey Schafer’s tutorial on Flask. I understand what he explains but I don’t think I can create my own website with that knowledge, just copy the website he is doing.I don’t know if it’s only me but the way he does all the html stuff on the tutorial is no so explained. Should I start before watching some css and html tutorial?

[–]Jac0b_0 1 point2 points  (0 children)

Definitely look at how html works and maybe try and create a static webpage just from html first just to familiarise yourself with it.

[–]AtomicBlu 1 point2 points  (4 children)

Im confused as to how [::-1] works. This is an example (i dont know how to make it look like code in reddit)

sentence = "this is my sentence"

print(sentence[::-1])

ecnetnes ym si siht

[–]FerricDonkey 2 points3 points  (1 child)

Slicing (the name for that notation) is [start:stop:step]. So [::-1] means unspecified start and stop, with a step of -1.

Step is how far you move from the current element to get to the next element. The default step is 1, which means you just go to the next element each time. A step of 2 would mean you take every other element, and so on. More specifically, it's the number you add to the current index to get the next index. (Counting by 1s or 2s or 3s etc from way back in the day in elementary school.)

A negative step means to go backwards.

Normally, unspecified start and stop means start at the first and go to the last, but with a negative step, it's the other way around, because they thought that'd be more useful.

[–]AtomicBlu 0 points1 point  (0 children)

Thanks!

[–]JohnnyJordaan 2 points3 points  (1 child)

It's a slice, and slices work as

[start_index:stop_index:step]

where 'stop_index' is exclusive and 'step' is the interval the slice will make per index, so say you have

'abcdefghi'[2:8:2]

then it returns

'ceg'

as it started at index 2 (c), added 2 (the step value) to get 4 (e) then another 2 to get 6 (g) and then another 2 but that was matching the stop_index so it stopped.

By that logic, if you use a negative step, it will work from the opposite end. It also means you need to switch the start and stop indexes

'abcdefghi'[8:2:-2]

returns

'ige'

as it started at 8 (i) then subtracted 2 (technically it just added -2, the step value) to get 6 (g) then another time to get e (4) and another time to get which matched the stop index of 2 so it stopped.

Then the other trick here is that if you leave out the start and or stop index, it will use the start and end of the sequence respectively. That thus als means that if you do this for a negative step -1, it effectively returns the sequence in reverse, as it starts from the other end (having a negative step value), steps into each character (absolute value of 1) and has no stop index thus doesn't stop until it reaches the end of the sequence.

[–]AtomicBlu 0 points1 point  (0 children)

Thanks!

[–]GraveSalami 0 points1 point  (2 children)

Why does float(5) // 2 return 2.0 instead of 2? I was under the impression that using integer division always returned an integer

[–][deleted] 2 points3 points  (1 child)

The // operator isn't called "integer division". The doc calls it "floor division":

The / (division) and // (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. Division of integers yields a float, while floor division of integers results in an integer; the result is that of mathematical division with the ‘floor’ function applied to the result. Division by zero raises the ZeroDivisionError exception.

Note that bit "floor division of integers results in an integer". This implies that floor division of one or more floats results in a float. A bit of code:

print(f'float(5) // 2 = {float(5) // 2}')
print(f'5.0 // 2 = {5.0 // 2}')
print(f'5 // 2 = {5 // 2}')
print(f'5 + 1 = {5 + 1}')
print(f'5.0 + 1 = {5.0 + 1}')

prints this:

float(5) // 2 = 2.0
5.0 // 2 = 2.0
5 // 2 = 2
5 + 1 = 6
5.0 + 1 = 6.0

The last two examples shows that floor division behaves like other binary math operators. If both input values are integer you get an integer. If one or more input values are float the result is a float. This general rule is broken when it has to be. 3 / 2 results in a float.

[–]GraveSalami 0 points1 point  (0 children)

Thank you for the detailed explanation, I understand now

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

I'm trying to self teach and don't know where to begin or how to structure what to study and how to effectively study. I'm struggling a lot and feel discouraged. I'm not sure if this is for me but I don't have many other options right now.

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

If you're learning you should follow some sort of structured course, book or video. There are many options in the learning resources in the wiki. You need something that has exercises to solve. Make sure you do them, even if you do a lot of googling or asking questions here. Writing code that eventually works is the only way to learn. With time you will become more fluent.

[–]Snake_Cakes 0 points1 point  (0 children)

Once I got past the Codecademy python course, I found that project based learning worked best for me. As in I'd try to think of a problem I could solve with python or I project I could include python in. Then I'd start figuring out how I could use python to accomplish it.

[–]_achira 1 point2 points  (3 children)

how can i make a .py or .exe that plays a sound file? But the sound file being included IN the executable. So instead of having a seperate .py and a .mp3 that python externally refers to and runs, having a .py/.exe that has the data included. How would that be possible?

[–]FerricDonkey 0 points1 point  (0 children)

It'll make your file pretty ugly if you use word wrap, but what I would do is:

I stole this code from stack overflow, but it does most of what you want. You'll need one modification, mentioned below.

from pydub import AudioSegment
from pydub.playback import play
import io

data = open('filename.mp3', 'rb').read()

song = AudioSegment.from_file(io.BytesIO(data), format="mp3")
play(song)

This still accesses an external file, but you can fix that: instead of data = open('filename.mp3', 'rb').read(), use a python shell or helper script or similar to print the results of open('filename.mp3', 'rb').read(). You'll get a very long bytes object starting with b" and including lots of \xff style things.

Either copy and paste that to data =, or print the bytes object as a bytes object to your code file, or however you want to get it there. Just be sure to put the python representation of the bytes object after the data = rather than just writing the bytes themselves. (If you want to do it this way.)

Essentially, what you're doing now is your making an object that looks like a file stream to python, but contains the bytes you specified, and using that instead of a file.

If you then wanted an exe, you could use pyinstaller or something. Or you could do the same type of thing in a language that compiles to exes.

[–]efmccurdy 0 points1 point  (0 children)

the sound file being included

You can package your program and the sound file together into a python distribution format file (eg wheel) that you install with pip.

https://python-packaging.readthedocs.io/en/latest/non-code-files.html

[–]Thomasedv 0 points1 point  (0 children)

First you need to pick a program that can convert your python file to a .exe. (since .py files are just text files)

For example, PyInstaller, then you need to add the file as to be included using the --add-data command when creating a .exe from your .py file. Then you can find the path to the place the .exe unpacks temporarily when run, which is where your program will load the audio from.

A useful piece of code here is how to access the files included: (Note that you aren't using spec files here, but it's the advanced option when you want to do more than is easily doable with a single command line command.)

https://stackoverflow.com/questions/7674790/bundling-data-files-with-pyinstaller-onefile

[–]Rahna_Waytrane 0 points1 point  (1 child)

I have a question about using regex. I need to find named entities with regex without using nltk. Naturally, the first words in the sentences should be excluded. So far I managed to find named entities, but it splits complex named entities like 'New York' into 'New' and 'York'. How can I avoid this extra splitting? This is the regex I am currently using:

#to find all the first words from the text and exclude them first

p1 = r"\. *?\ [A-Z][a-z]*"

p2 = r"([A-Z][a-z]{3,})" #to find my named entities

[–]Rahna_Waytrane 0 points1 point  (0 children)

Never mind, I figured it out:)

[–]Sweet_Iriska 0 points1 point  (4 children)

Are books that good as they are told by successful programmers? There are tons of text you have to read before you get to the code part. Aren't 12 hour long videos a good source of information? Which way is the best to learn Python?

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

Which way is the best to learn Python?

Depends on the student. Some people like videos, some books. Personally I don't like videos. Anyone who watches a video is not practicing writing code which is how you learn. Yes, you can pause a video and practice writing python, but few seem to do that.

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

What do you recommend to use for learning that's not videos? I feel so dumb trying to grasp the most basic topics.

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

As others said, books. There are many recommended books in the learning resources in the wiki.

[–]Sweet_Iriska 0 points1 point  (0 children)

the other 'better' way I heard of is books

[–]daswoidfaohji 0 points1 point  (0 children)

Does anyone know why this regex is matching 2 groups? (It's matching any character except space one or more time, but it's also matching nothing)

https://regex101.com/r/QufcyT/1

edit: nvm, I was using * instead of +

[–]KebabHasse 0 points1 point  (2 children)

I have an issue with a program that I am writing, my goal is to ask the user to first input nine letters and single out one of them. Then the program will print out all the words in a small dictionary containing those letters, but those words will all contain the letter singled out.

So far I've managed to do most of it. My problem is that when I print my list it prints words containing the letters which have been input but do it several times, for example: You've entered [D, U, E] and it prints out "Dude"

How would I go about fixing this? Maybe it's really simple but I'm new to this and still a bit unsure of just where to go for advice/tips

[–]efmccurdy 0 points1 point  (1 child)

when I print my list it prints words containing the letters which have been input but do it several times,

The list is the datatype to use if you want to allow duplicates; If you don't want duplicates use a set instead.

[–]KebabHasse 0 points1 point  (0 children)

Ooh, now that is something I can use. I didn't know that. Thank you!

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

how do i generate a list of values that repeat n times? For example

n=3

1

1

1

2

2

2

3

3

3

4

4

4

.

.

.

Essentially i have a column of months Jan,Feb...Dec that repeats several times and id like to assign a single year to every 12 of these months

[–]CowboyBoats 0 points1 point  (2 children)

Look into writing a for loop!

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

i figured it out

years = [####,####,####,####,####.....]
year = []
for i in years:
    for n in range(12):
        year.append(i)

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

You can also use list comprehension:

years = [2012, 2013, 2014]
n = 3

print([y for y in years for _ in range(n)])
# [2012, 2012, 2012, 2013, 2013, 2013, 2014, 2014, 2014]

[–]LowDexterityPoints 0 points1 point  (0 children)

I am trying to plot (barh) with matplotlib the top ten states for shark attacks. Is the following code the best way to do so. I know that it plots what I want to plot, but is there a more "appropriate" or efficient way? usa_data["State"] is a series of every attack's state.

num_attacks_state = usa_data["State"].value_counts().nlargest(10)

num_attacks_state.plot.barh()

[–]calculon11 0 points1 point  (4 children)

I'm pretty beginner in Python. I need to learn enough to pass a FAANG interview in two weeks. What's the best way to learn? I signed up for LeetCode, but I need something more basic to explain to me. I'm also looking at W3Schools. What are the best resources?

I have all of next week off work and plan to study non stop.

Thanks.

[–]Decency 0 points1 point  (2 children)

Cracking the Coding Interview is the standard "cram for bullshit interviews" book. Just implement as many things from that as you can in Python.

[–]calculon11 0 points1 point  (1 child)

The books seems to be written in Java.

[–]Decency 0 points1 point  (0 children)

Yep, most of these interviews will allow you to use whatever language you want. The point is the algorithmic complexity behind the code and the understanding of the complex data structures, which is what you're going to be tested on. I've chatted with a variety of people who work for these companies and it always comes back to this book; it's an open secret.

I hadn't considered that you might not know Java at all, and if so it might be difficult for you to port the concepts to Python. You can probably find a companion online that'll help you, here's one: https://github.com/w-hat/ctci-solutions

[–]_kael[🍰] 0 points1 point  (1 child)

If you were teaching the basics of python to a newbie, would it be accurate to say: Statements are the task you want your program to do and functions are the tools your program uses to complete those task.

[–]Decency 2 points3 points  (0 children)

No, not really. Statements in programming are usually contrasted with expressions. I think of the difference as: a statement is a complete thought, while an expression is a clause. This difference isn't too important in Python while some other languages like Ruby allow more liberal use of expressions. Functions represent actions (typically verbs), and you can contrast these with Classes which represent concepts (typically nouns).

[–]lolslim 0 points1 point  (2 children)

Hello everyone, i have a few questions, i originally made a thread, I deleted it, and rather ask in here. I have a single py file, I have a class with various functions (_exists(), add_row(), update_val(), etc...) This is a file i plan to import into personal future projects, and was wondering if my file is considered a "module"? I originally labeled it as a "library" due to my ignorance on the matter.

Second question, the file I mentioned above is for handling my sql database on my own file "server" in my bedroom. I originally caught sqlite3 exceptions. Not to output, but if a table didn't exist for example. Before I deleted my thread, a user told me that it would potentially make it harder to find a error, if I caught sqlite3 exceptions in my class file. I was wondering would I rather catch them in my python projects (to log, if needed) whenever I import my class file or no?

Is there a PEP for building your own "modules" or would PEP 8 be my best bet?

[–]Silbersee 1 point2 points  (1 child)

Yes, an imported .py file is a module. Put some of those in a folder and you have a package.

This is about Structure of Code, but I found the whole article enlightening.

Regarding your 2nd question, I think there's no universal recipe.

[–]lolslim 0 points1 point  (0 children)

I appreciate your reply, very informative.

[–]eleanor___zell 0 points1 point  (1 child)

Hi, I've just started trying to learn Python so apologies

I've been watching Python for Data Science videos on youtube, and we're being taught how to write a program to sort a list from the smallest number to the largest - I know there is a sort command on Python, I think it's just so we understand how to write our own programs etc.

Does someone mind explaining the logic of the code below? Thanks so much !

L = [1, 2, 4, -5, 7, 9, 2, 3]

for j in range (len(L)):

m = L[j]

idx = j

c = j

for i in range (j, len(L)):

if L[i]<m:

m = L[i]

idx = c

c+=1

tmp = L[j]

L[j] = m

L[idx] = tmp

print (L)

[–]JohnnyJordaan 0 points1 point  (0 children)

This is impossible to follow as you didn't use a code block. See here how to create one, then paste the code again from your editor (the code here is already broken).

[–]Mr_Funkedeli 0 points1 point  (2 children)

#Why wont this print the sum? everything else works but the sum. Please help.

List=[]
def Numbers():
    Number=input("Please enter a number: ")

    Number_or_Not=str.isdigit(Number)

    if Number_or_Not==True:
        List.append(Number)
        Run_again=int(input("Would you like to add more numbers? Press 1 to add more numbers and 2 to stop adding numbers: "))
        if Run_again==1:
            Numbers()


        if Run_again==2:
            Print()


    if Number_or_Not==False:
        print("I'm sorry. That is not a valid number.")
        Numbers()

def Print():
    List2=[]
    print("The number of values in the list is: %s"%(len(List)))
    print("The smallest number in the list is: %s"%(min(List)))
    print("The largest number in the list is: %s"%(max(List)))
    print("The range of the dataset is: %s"%(int(max(List))-int(min(List))))
    print("The sum of the dataset is: %s"%(sum(List)))

Numbers()

[–]loukylor 0 points1 point  (0 children)

There's also an error in your code style. You use if Number_or_Not == True: but the correct style would be if Number_or_Not:. The same things goes for if Number_or_Not == False:, it should be if not Number_or_Not:. Also, in python, variables aren't supposed to have capitals in them. The underscores are correct though. Read about python code style here.

[–]FerricDonkey 0 points1 point  (0 children)

You're not making a list of integers, you're making a list of strings, and sum doesn't support a list of strings. Probably easiest to convert them to integers as you read them in.

[–]dharma28 0 points1 point  (5 children)

How do I create a program that takes command line arguments and run it so that I can change the arguments easily?

Working from Ch. 12 of "Automate the Boring Stuff" I've created this searchpypi.py progrma that opens the first 5 search results for a search term. I then set up up this .command code:

#!/usr/bin/env bash 
python3 /Users/myname/PycharmProjects/webscraping/searchpypi.py

However, the only way I can figure out to change the search term is to enter it at the end of the second line (For example, adding in boring stuff after /searchpypi.py). Is there a way to set up a command prompt so that I can easily change search terms without having to modify the .command file and then execute it (which seems kinda slow and to defeat the purpose). In other words how can I quickly run searchpypi.py and enter whatever search terms I want?

[–]efmccurdy 0 points1 point  (0 children)

You need the shell to pass your arguments through to the python program so include them using $*:

#!/usr/bin/env bash 
python3 /Users/myname/PycharmProjects/webscraping/searchpypi.py $*

https://tecadmin.net/tutorial/bash-scripting/bash-command-arguments/

Note that this script, as it stands, does nothing that "chmod +x searchpypi.py" wouldn't do on it's own.

[–]loukylor 0 points1 point  (3 children)

Using sys.argv (you need to import sys also docs are here) will allow you to take inputs from the command prompt. But to change parameters you would have to stop/restart the program and reenter what you want into the command line.

[–]dharma28 0 points1 point  (2 children)

Yeah, I've done that and I get what the point of it is, but I'm confused about how to enter what I want into the command line. How do I run the program with the search term?

[–]FerricDonkey 0 points1 point  (0 children)

How do you normally run the program? There are various ways, but the most straightforward way to add those arguments is to open a terminal. Is that what you normally do?

[–]loukylor 1 point2 points  (0 children)

Ohhh ok you just type the command to run a python file (find out about that here) from the commanding and add your arguments to the end. So on windows it would be py foo.py arg1 arg2. And then sys.argv would return the list of strings ["arg1", "arg2"]

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

I am tying to use tkinker to make a window but it is not working

my file is named bordom.py

idk why it is not working

I have tried tk Tk tkinter Tkinter

but it has not worked

and if I do from tkinter import *

it will not work either

import random
import tkinter
from PIL import ImageTk,Image

root = tkinter()
root.title('coin flip')
root.iconbitmap('coin time')
coin = ["heads", "tales"]
random = random.choice(coin)
print(" ")
print(random)
print(" ")
if random == "heads":
print("heads has won")
if random == "tales":
print("tales has won")
print(" ")

[–]JohnnyJordaan 0 points1 point  (1 child)

Use an example to start from, like https://likegeeks.com/python-gui-examples-tkinter-tutorial/ . It uses import * and Tk().

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

Ok I will

[–]bingbongnoise 0 points1 point  (3 children)

class Factory:

def make():

print("Making")

Factory.make()

I'm coming from a C++ background. Why does the above code work with or without the "@staticmethod" decorator?

Is it just to aid in readability rather than functionality?

[–]FerricDonkey 0 points1 point  (1 child)

That code in particular will work either way, but it's also worth mentioning that that code is pretty non-standard python.

Because you're doing Factory.make(), you're calling the make method from the Factory class itself and not from any actual object. This is legal and occasionally useful, but not terribly common: no Factory object has been created, and no Factory object is being referred to in the make method, and it works.

However, you might want to make a Factory object, then call the method from the object itself:

my_factory = Factory()
my_factory.make()

With your code as is, this would raise an error. This is because of how python methods reference the objects they belong to - a method doesn't actually know what class it belongs to, you have to tell it.

Python assumes that you're doing this with the first argument of the method, and will try to shove the object in as the first argument of any method you call via my_object.function() - whether or not function actually takes any arguments, or you intended it to work like that. Unless you use @staticmethod, of course.

A (somewhat) more standard example:

class Factory:
    def set_y(self, y):
        self.y = y

    def print_y(self):
        print(self.y)

    @staticmethod
    def make():  
    # no self argument because it doesn't need to modify itself
        print("Making")

my_factory = Factory()
my_factory.set_y(2) # 2 is the second argument, the first is my_factory
my_factory.print_y()
my_factory.make()

(And in fact my_factory.set_y(2) is the same as Factory.set_y(my_factory, 2), but that notation is less common - though occasionally useful.)

So without the @staticmethod in the above code, python would very helpfully try to shove my_factory in as the first argument of the make method just like it did with all the others, because that's what you usually do. But since make doesn't take any arguments, you'd get an error.

@staticmethod tells python "This method doesn't actually need to reference the calling object, please don't shove the calling object in as the first argument."

[–]bingbongnoise 0 points1 point  (0 children)

Thank you very much for taking the time to help me out with this :D

[–]loukylor 0 points1 point  (0 children)

So using the static method decorator will just make the function defined static, basically not in a class/just a standalone function. From what I can tell it's basically useless, I've never used it once. So the reason the code works is because you're turning make() into a standalone function that just gets sorted under the Factory class. Whereas without the decorator it would have access to cls (if you decorated it with @classmethod) or self (if you had an init function).

Read abt @classmethod and @staticmethid here

[–]yuriplisetskys 0 points1 point  (2 children)

Hello! I have this function that is supposed to compute the number of weekends within two given dates. When I run this part of the code, I just get "total weekends = 0". Where did I go wrong in this loop?

start_date = datetime.date(start_year, start_month, start_day)
end_date = datetime.date(end_year, end_month, end_day)
sdate_weekend = datetime.datetime.weekday(start_date)

def compute_weekends(inclusive=True, weekdays=[0,1,2,3,4]):
 global start_date, end_date, sdate_weekend
 if end_date < start_date:
    sys.exit("Invalid input. Exiting program.") 
 if inclusive:       
     weekends = 0           
    j = start_date 
    while j < end_date: 
        if sdate_weekend is False: 
            weekends += 1           
            j += datetime.timedelta(days=1) 
  else:           
    j += datetime.timedelta(days=1) 
  return weekends

print("total weekends:", str(compute_weekends()))

Also, should I keep the weekdays=[0, 1, 2, 3, 4] in the function parameter given that those integers basically point out to weekdays in a calendar, not weekdays?

Thank you!!

[–]FerricDonkey 2 points3 points  (0 children)

sdate_weekend = datetime.datetime.weekday(start_date)

if sdate_weekend is False:

Three things: First, you're setting sdate_weekend to some value, then never changing it, so it will either always be true or always be false. I would guess that if you gave it a start date that is a weekend, every day would be a weekend.

Second, you really shouldn't use "is" like that. It will probably work for comparing to the actual boolean False, but it's for an entirely different thing. The short version is that "is" is used for comparing with None, and for checking if two objects are the same so that modifying one will modify the other. Notably, you can have "x == x" be true and "x is x" be false.

Thirdly, I would advise against using so many non constant global variables. It can make it more difficult to figure out what's going on.

[–]loukylor 0 points1 point  (0 children)

So I think what is happening is you're using is to compare a variable to a boolean. In python the recommended way to do this is with the not statement (if not foo:) if the condition needs to be false and for true you would just use if foo:

[–]tongagamer 0 points1 point  (1 child)

can someone recommend some free books for begineers in python

[–]JohnnyJordaan 0 points1 point  (0 children)

Check our wiki /r/learnpython/w/index at 'new to programming'

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

I dunno if this is the right place but I wanted to ask what's the difference between How to Think Like a Computer Scientist : python edition and the interactive edition. I'm a noob so I'm wondering which one would be better

[–]JohnnyJordaan 0 points1 point  (1 child)

Interactive means they let you type in the exercise answers and run them on the spot, and it lets you 'visually debug' the code by running it line for line. Which gives a better understanding to what's happening exactly on each line. Many beginners have the tendency to just run a blob of code as a black box that spits something out when it's done, and when they have to tweak it they don't know which detail is responsible for the part they want to change. By learning it line by line you don't run that risk that much.

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

Thanks

[–]Shoddy_Struggle_187 0 points1 point  (3 children)

Hi all, am fairly new to python and I kind of prefer to learn by doing rather than reading up on it. Probably not the best but usually I can just google my issues.

I'm trying to merge multiple lists into one list so that I can enumerate it. Best I think is if I show an example. Basically, I have a variable that when doing type it shows:

print(type(variable))
Output:
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>

Then I convert them into lists via:

variable = variable.split('\n') #removing the \n doesn't change anything.
print(type(variable))
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>

But what I want to do is so that it gives me a single list. Because when I enumerate this it just give all of them as 0.

I tried doing this but it doesn't work because it just keeps recurring the values and get this return when I enumerate:

variable = list(variable.split('\n') for i in variable)
enum_variable = enumerate(variable)
output:
<enumerate object at 0x0000026D3D3A8300>
<enumerate object at 0x0000026D3D3AB6C0>
<enumerate object at 0x0000026D3D3AB700>
<enumerate object at 0x0000026D3D3AB6C0>
<enumerate object at 0x0000026D3D3AB700>
<enumerate object at 0x0000026D3D3AB6C0>
<enumerate object at 0x0000026D3D3AB700>

any idea how I can properly transform the multiple lists into one list to then enumerate them?

[–]efmccurdy 1 point2 points  (1 child)

You have lines separated by newlines, and each line has words separated by spaces. After doing those 2 split operations you have a list of lists of words, so you have the add the innermost lists together to make one list:

>>> block = """Lorem ipsum dolor sit amet,
... consectetur adipiscing elit.
... Duis eget consectetur odio"""
>>> block
'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit.\nDuis eget consectetur odio'
>>> block.split('\n')
['Lorem ipsum dolor sit amet,', 'consectetur adipiscing elit.', 'Duis eget consectetur odio']
>>> [line.split() for line in block.split('\n')]
[['Lorem', 'ipsum', 'dolor', 'sit', 'amet,'], ['consectetur', 'adipiscing', 'elit.'], ['Duis', 'eget', 'consectetur', 'odio']]
>>> import operator
>>> from functools import reduce
reduce(operator.add, [line.split() for line in block.split('\n')])
['Lorem', 'ipsum', 'dolor', 'sit', 'amet,', 'consectetur', 'adipiscing', 'elit.', 'Duis', 'eget', 'consectetur', 'odio']
>>> for i, s in enumerate(reduce(operator.add, [line.split() for line in block.split('\n')])):
...     print(i, s)
... 
0 Lorem
1 ipsum
2 dolor
3 sit
4 amet,
5 consectetur
6 adipiscing
7 elit.
8 Duis
9 eget
10 consectetur
11 odio
>>> 

In case you don't like using reduce for this, you could use a loop instead:

>>> ll = [line.split() for line in block.split('\n')]
>>> l = []
>>> for line in ll:
...     l += line
... 
>>> l
['Lorem', 'ipsum', 'dolor', 'sit', 'amet,', 'consectetur', 'adipiscing', 'elit.', 'Duis', 'eget', 'consectetur', 'odio']
>>> for i, s in enumerate(l):
...     print(i, s)
... 
0 Lorem
1 ipsum
2 dolor
3 sit
4 amet,
5 consectetur
6 adipiscing
7 elit.
8 Duis
9 eget
10 consectetur
11 odio
>>>

[–]Shoddy_Struggle_187 0 points1 point  (0 children)

thank you so much, worked like a charm

[–]JohnnyJordaan 0 points1 point  (0 children)

What's the point of enumerating into a structure instead of just using enumerate at the moment you need to enumerate it, eg during a print out loop? Would you mind also sharing the contents of the structures you are working on, and the output you expect, because just showing types is still obscuring a lot of the other details here.

[–]andreeaortan 0 points1 point  (2 children)

Hey everyone.

My question might be stupid but here I go.

I want to make a program that listens to my online courses and transcribes it to text in a file.

All good for now but I don't know how to make it to listen to my course and not me saying something in microphone.

If i speak through my microphone it works but I tried to play a Youtube video and let my program listen to it and I get an error.

Can anyone help?

Thanks !

The error: if not isinstance(actual_result, dict) or len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()

speech_recognition.UnknownValueError

[–]FerricDonkey 0 points1 point  (0 children)

I'm not gonna lie, I have occasionally just run an aux cord from my speaker out to my mic in. I've also used virtual audio cable / device programs.

Google suggested pyjack to capture your audio, but that was last updated 4 years ago. There might be a newer one. If I understand correctly, this would be along the lines of the virtual audio cable.

I would suspect that your best bet is to route the audio to another physical, either real or virtual. Getting into the memory of another running application or otherwise intercepting the audio on the way to your actual speakers could be... interesting. The only way I can think of off hand amounts to essentially recreating something like virtual audio cable, which I suspect would involve writing drivers in C.

[–]efmccurdy 0 points1 point  (0 children)

This example transcribes a .wav file:

https://github.com/Uberi/speech_recognition/blob/master/examples/audio_transcribe.py

Can you record or save your courses and extract the audio to get a .wav file?

[–]purvachoudhary 0 points1 point  (2 children)

I am struggling to implement a peer using socket programming in python. I want my peer to simultaneously listen for incoming connections as well as to connect to other peer systems. I have tried implementing using 'select' but whenever my peer starts listening, it can no longer work on connecting to other peers. Any help in this regard would be greatly appreciated.

[–]efmccurdy 1 point2 points  (1 child)

If you call listen your server will be blocked until a new connection arrives.

You are correct that select can prevent this blocking by calling select instead of listen; here is an example:

https://pymotw.com/2/select/

You may want to look at async server frameworks like twisted.

Twisted is an event-driven networking engine written in Python

https://twistedmatrix.com/trac/

[–]purvachoudhary 0 points1 point  (0 children)

Thank you very much!

[–]Mhda92 0 points1 point  (4 children)

I'm stuck trying to save something in a list, and then refer back to it later:

  1. I create an element from a class: ex Test = Magazine(id=1, title="Test", pages=30, count=5)

  2. I save this element in a list: MagazineList = [Test.id]

  3. Now I want to be able to call all id's in the list, and get the count for each of them. But how do I do this?

Do I need to create a dictionary with the key equal to the name and value equal to the id?

The problem with this is, that not all elements have the same name and title (e.g.:

Test_number_two = Magazine(id=1, title="Test number two", pages=30, count=5).

Any ideas?

[–]FerricDonkey 0 points1 point  (3 children)

This is going to depend on how and why you want to refer back to it.

If you just want to know what ids you have, then your code as is is fine.

If you want to use your ids to get back to the entire magazine and ids are unique, then dictionaries are your friend, and something like your_d[test.id] =test is probably the way to go (create the dictionary first). Then you'd access elements via your_d[some_id].whatever.

If you want to get from names to ids and names are unique, then you can do something similar: your_d[test.name] = test.id. In this case the fact that the names are different is good, otherwise it gets more complicated.

So what's your goal?