r/pythonhelp • • Oct 27 '21

Python IDLE cannot open file, says "the open file operation failed to connect to the open and save panel service"

3 Upvotes

Just upgraded to a new MBP with an m1 pro chip. I'm encountering some weird issues trying to open files through IDLE. It throws an error saying "the open file operation failed to connect to the open and save panel service" I have tried reinstalling python, and when looking under the services settings for IDLE I couldn't find such a service. Both macOS Big Sur and macOS Monterrey have this issue. Otherwise, it seems like IDLE is performing as should. Any ideas on how to fix the issue?


r/pythonhelp • • Oct 10 '21

HOMEWORK List Slicing going over my head in LeetCode 189 Rotate Array

3 Upvotes

I understand the process by which the answer to the question is found: list slicing, or using 3 while loops or a helper function to just reverse and re-reverse by k and so forth. By it is the list slicing answer that currently makes no sense to me:

x = k % l
n[-x:], n[:0] = n[:0], n[-x:]

Is n[:0] just an empty copy of the array? What purpose does it serve? I understand that n[-x:] is grabbing the k elements we want to rotate by I'm just so confused by n[:0]


r/pythonhelp • • Oct 07 '21

An absolute newbie here. I don't know what's wrong that the statement isn't coming.

Thumbnail
gallery
3 Upvotes

r/pythonhelp • • Sep 19 '21

Creating three nested dictionaries from a text file

3 Upvotes

Hi, I’m currently trying to create three nested dictionaries from my text file (a play script) and can’t quite get the coding correct and was wondering if someone would be able to help me find where I am going wrong. My first dictionary is meant to be the acts, the second the scenes, and then the third the characters, with the values of the character dictionary being the lines of each character. I believe I have made a list for the last one, rather than a dictionary and I cannot figure out how to parse a third nested dictionary.

actDict = {}

with open ("Macbeth.txt", 'r') as inFile:
    for lines in inFile:
        if 'ACT' in lines:
            a = lines.strip()
            actKey = a.split(' ')[1]

            actDict[actKey] = {}
        else:
            if 'SCENE' in lines:
                a = lines.strip()
                sceneKey = a.split(' ')[1]
                
                actDict[actKey][sceneKey] = {}
            else:
                if len(actDict[actKey][sceneKey]) == 0:
                    if '    ' in lines:
                        a = lines.strip()
                        b =  a.split('\n')
                    else:
                        a = lines.strip()
                        characterKey =  a.split('\n')
                        actDict[actKey][sceneKey] = characterKey[0]
                        
print(actDict)

I have tried looking up nested dictionary examples and they format them quite differently, and more often than not end up defining the values from inside the code, rather than from a text file, and I am very new to coding so I'm having difficulty applying it to my own situation. I have tried actDict[actKey][sceneKey][characterKey] = {} and actKey[sceneKey][characterKey] = {} for my last line of code. Neither of which end up with intended results. 


r/pythonhelp • • Sep 17 '21

HOMEWORK Need help fixing this syntax error.

3 Upvotes

I’m getting a syntax error at the print part and I don’t know why. I started coding recently and I’m a noob. I would appreciate any help.

item1 = (input("Please enter the price of the first item : ")) item2 = (input("Please enter the price of the second item : ")) item3 = (input("Please enter the price of the third item : ")) item4 = (input("Please enter the price of the fourth item : ")) item5 = (input("Please enter the price of the fifth item : ")) total = item1 + item2 + item3 + item4 + item5 salesTax = 0.7 subTotal = (total + (total * salesTax) print = total, salesTax, subTotal


r/pythonhelp • • Sep 09 '21

Help understanding functions

3 Upvotes

Number of days per month

month_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 

def is_leap(x): 
    return x % 4 == 0 and (x % 100 != 0 or x % 400 == 0) 

def days_in_month(year, month):  
        if not 1 <= month <= 12: 
            return "invalid month" 
        if month == 2 and is_leap(year): 
            return 29 
        return month_days[month]

print(days_in_month(2017, 2))

In the function: days_in_month(year, month) in the 2nd if statement how can the is_leap take in the arguement year and still be able to complete its function.

To clarify what I mean is how does the program pick up that when I assign something to the year arguement it has to run the is_leap function even though the is_leap function is coded to have the arguement of x.

If year was 12, would is_leap(year) take that 12 in and replace x with it and then run it?


r/pythonhelp • • Aug 31 '21

HOMEWORK Help with Python exponential function

3 Upvotes

So, I started my coding adventure yesterday and started from "4 hours full course for beginners of python". I had problems understanding how below code works, it's exponential function and I can't really understand It.After defining a function, we make container called "result" where we store below list of numbers and I can't understand how its gonna make 2^3=8? How can list of numbers be multiplied by 2? Someone can help?


r/pythonhelp • • Aug 28 '21

Asing list_1 to list_2 and clear list_2 and also not clearing list_1

3 Upvotes

This have me crazy, when I clear list2 it also clears list1 because it is equal to it, but I need list1 to just save it and not get cleared when I clear list2.

list2 = ["2", "hello"]
list1 = list2
list2.clear()
print(list1)

I need the output to be ["2", "hello"] and not []

I hope it aint too stupid of a question.

Thanks.


r/pythonhelp • • Aug 03 '21

How do I print a custom error message without Python returning a traceback?

3 Upvotes

I have 2 programs that require a numerical input. One takes a float, the other takes an integer.

Program 1

Program 2

If they detect letters or symbols, it's supposed to return the error message "That wasn't a float/number!"
While it does return the error message, they also return Traceback (most recent call last): NameError: name 'Example' is not defined together with the error message.

How do I make it return ONLY the error message without the Traceback thing?


r/pythonhelp • • Aug 01 '21

how to remove uneseccary lines form a a string?

3 Upvotes

say i have a string that looks like this:

"hi hi hi

hi hi hi"

And i want to chop off the bottom row hi hi hi so it looks like just this:

"hi hi hi"


r/pythonhelp • • Jul 30 '21

HOMEWORK need help with python tax calculator

3 Upvotes

I'm new to python. Made a simple calculator for tax but want to add 12000 personal allowance in - so if the salary is <= 12,000 the 20% tax should no be deducted - also if the salary is 13,000 the 20% should be deducted from the 1000.

right now it works - but the 20% is deducted from everything

hours = input ("Number of Hours Per Week? ")

rate = input ("Your Hourly Rate? ")

wp = float(hours) * float(rate)

#wp is weekly pay

print ("weekly pay: ", wp)

#mp is monthly pay

mp = float(wp) * 4

print ("Monthly Pay: ", mp)

salary = float(mp) * 12

print ("Yearly Salary: ", salary)

pa = 12000

print ("Personal Allowance: ", pa)

quotient = 1 / 5

tax = float(salary) * float(quotient)

print ("20% tax: ", tax)

#sat means salary after tax

sat = float(salary) - float(tax)

print ("Salary after tax & PA: ", sat)

mat = float(sat) / 12

print ("Monthly Pay after tax & PA: " ,mat)


r/pythonhelp • • Jul 29 '21

My Script Runs in Pycharm but Will Not Run in Python

3 Upvotes

I wrote a piece of code and I have been testing it in Pycharm and it works exactly as intended, but when I go to run it through regular Python, it doesn't complete the code.

The program allows for the user to name and save a file to their device, when I run it in Python after it asks for the file name it will automatically close out without saving the file. It is not supposed to do this. It is supposed to save the file and after asking the user to repeat the program, iterate through the code again or then close the program.

Every other feature of the code works but it will not save the file and just crashes. Why is this? Do I need to change the code or something? And if not, is there another way to run this script? I tried doing it through the terminal as well but made no progress.

I will leave the part of the code that deals with the file saving below;

Ask_User_To_Save_Dataframe = input("Do you want to save your Dataframe, above, as a file to this computer? Yes or No: ")
if Ask_User_To_Save_Dataframe == str("yes") or Ask_User_To_Save_Dataframe == str("Yes"):
User_Names_Save_File = input("What do you want to name the file of the above Dataframe?: ")
f = open(User_Names_Save_File, "x+")
Turn_Dataframe_To_String = Drop_All_Na_From_Dataframe.to_string()
f.write(Turn_Dataframe_To_String)
f.close()


r/pythonhelp • • Jun 22 '21

How do I add a Python project to a webpage?

3 Upvotes

Hello all, I’m trying to add a Python project I finished a week ago to my portfolio webpage and am having a hard time doing so. The website will only accept ipynb files in terms of coding. I managed to get the file and post it, but when I try to play it it doesn’t work. What else can I do? Thanks for your help.


r/pythonhelp • • Jun 13 '21

Coding a discord bot on Repl.it , and came across this error, any ideas on how to fix it?

3 Upvotes

r/pythonhelp • • Jun 11 '21

HOMEWORK Unexpected Output (printing and returning a string space instead of a word)

3 Upvotes

I am doing an assignment where it requires me to create a code that takes a string sentence and returns and prints the longest word in the sentence. I am not allowed to use .Split() to separate each word, as the assignment is trying to get me to use iteration. However, the output I am getting is only a space and I do not know what I am doing wrong with my iteration.

Here is my code:

def longestWord(sentence):
    longerWord = ""
    currentWord = ""
    for count in sentence:
        count = 0
        if (sentence == " "):
            count += 1
        elif len(currentWord) > len(longerWord):
            longerWord = currentWord
            count += 1
    return longerWord
    print (longerWord)

r/pythonhelp • • May 14 '21

SOLVED Unpacking function return in list comprehension amidst other values

3 Upvotes

I've paraphrased a bit on the code (leaving out quotes or whatever) but you should definitely be able to understand what I'm getting at.

I have a function to manipulate a couple values but there are other values that need to remain the same. I've tried to restructure the function to ingest variable lengths of iterables but not having much luck.

software = {
    'software_1' = {
        'var1' = 'publisher',
        'var2' = 'product',
        'var3' = 'version'
    }
}

def func(publisher, product):
    publisher = publisher.replace(',', '')
    product = product.replace(',', '')
    return publisher, product

In my mind, it would just work like this but it seems you can't unpack at this level of the comprehension...

manipulated_software = [line_item['var3'], *func(line_item['var1'], line_item['var2']) for line_item in software]

And hoping for output like...

manipulated_software = [version, publisher, product]

As opposed to what I'm getting now which is more...

manipulated_software = [version, (publisher, product)]

r/pythonhelp • • May 09 '21

Why does professional code have a bunch of functions with naming convention __something__ ?

3 Upvotes

I am not an expert but I have done several things in python and never had to use those, what am I missing?


r/pythonhelp • • May 08 '21

HOMEWORK Does anyone know an easy way to calculate the wavelength and angle of this 2D wave? (units dont matter, I only need to compare it relative to other waves)

Post image
3 Upvotes

r/pythonhelp • • Apr 17 '21

Using Python How Do I send FFMPEG stderr and stdout to Multiple Files?

Thumbnail self.codinghelp
3 Upvotes

r/pythonhelp • • Apr 06 '21

HOMEWORK Hi everyone I need to write a code that plots graph for vertical height and time of the space craft took to land. The question and a sample code is shown below. I just need to complete the part where there are three dots given but I dont understand how to do it.

Thumbnail
gallery
3 Upvotes

r/pythonhelp • • Apr 02 '21

HOMEWORK Nested loops assignment

3 Upvotes

I am doing a hw assignment in programming that asks to make the following:

  1. The program will ask the user for a number between 2 and 12

  2. The program will roll two virtual dice using the random library

  3. If the number rolled is the number the user chose the program will print “you win” or a similar message

  4. If the number rolled is not the number the user chose the program will tell the user you rolled a __ but your number is ___ hit any key to roll again

  5. The user will continue to roll the dice until they get the right number. The program will tell them how many turns it took them to roll their number


r/pythonhelp • • Apr 01 '21

Help with getting return from Class

3 Upvotes

I am trying call a function inside a class, have it send another function a value and then return it. But the return variable is always None? Can someone help me? In the pinto() function below it prints the correct value (2), but when returned to the variable (v) below to print it prints None?

class Testy():

def sec(self):

ri = 2

self.pinto(ri)

def pinto(self, ri):

print(ri)

return(ri)

r = Testy()

v = r.sec()

print(v)


r/pythonhelp • • Mar 13 '21

Python script: Learning to Webscrape local businesses email and phone number from search engine

3 Upvotes

Hi,

I run a small local business that was unfortunately heavily hit by the covid-19 crisis through the last year. Trying to improve our situation by finding smarter ways of reaching out to potential business customers and recently discovered the concept of webscraping. I have started to learn a little python at home and am trying to write a webscraping script with the following properties:

  1. used in connection with search engines like google, google maps, bing, etc.

  2. finds all local businesses in a geographically defined area with their associated websites

  3. clicks on every business-website, looks for, and extracts the following business information: Business Name, website url, email, telephone number, address (here I noticed that there may be a challenge due to the fact that not everything is marked as such and may just be plain text, thus I believe that one might have to write something that looks for "some_characters"@"some_other_characters"."x_characters" to identify e.g. an email address hidden in the text of the website?)

  4. moves this information into a csv. file

As I am still fairly inexperienced and trying to learn from others by reading already existing scripts, I was wondering if anyone here knows about a publicly available python script that does something similar as described above that I could read through to understand more and perhaps customize. So excited to learn more about the world of programming and webscraping, thank you in advance for your help and time! :)

- Amy
P.s.: If you're just starting to learn webscraping in python like me I am very happy to recommend this tutorial as it helped me a lot with understanding the basics: https://oxylabs.io/blog/python-web-scraping / https://www.youtube.com/watch?v=mDveiNIpqyw


r/pythonhelp • • Mar 09 '21

SOLVED Need help with an "if" and "input" code

3 Upvotes

Hello

I am having a problem with this code I am trying to make for my friends, every time I run it it works fine, however when I input "a" it dosent print("Welcome User")

a = (14451444)

a = input("Insert Code: ")

if a == b:

print("Welcome User")

any help with this?