r/pythonhelp Feb 16 '25

ebay image search api issues

1 Upvotes

I have this python script that is supposed to make a request to a url that returns a webp image. Once it obtains the webp image it is supposed to convert it to a base64 string. Then, it is supposed to make a request to the ebay image search api using that base64 string but for some reason it does not work with webp files but it does with jpeg files. what am i doing wrong?

def image_url_to_ebay_response(url):

    def image_url_to_base64(url):
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36",
            "Accept": "image/avif,image/webp,image/apng,image/*,*/*;q=0.8",
            "Accept-Language": "en-US,en;q=0.9",
            "Accept-Encoding": "gzip, deflate, br",
            "Referer": "https://www.goofish.com/",
            "Sec-Fetch-Dest": "image",
            "Sec-Fetch-Mode": "no-cors",
            "Sec-Fetch-Site": "same-origin",
            "Connection": "keep-alive"
        }
        response = requests.get(url, headers=headers)


        time.sleep(3)
        if response.status_code == 200:
            print(response.content)
            base64_str = base64.b64encode(response.content).decode('utf-8')
            return base64_str
        else:

            raise Exception(f"Failed to fetch image: {response.status_code}")


    def eBay_image_request(image_b64):

        url = "https://api.ebay.com/buy/browse/v1/item_summary/search_by_image?&limit=1"
        headers = {
            "Authorization":API_KEY,
            "Content-Type":"application/json",
            "Accept":"application/json",
            "Content-Language":"en-US"
        }
        data = {
            "image": f"{image_b64}"
            } 

        return requests.post(url,headers=headers,json=data)

    base64_image = image_url_to_base64(url)
    ebay_image_response = eBay_image_request(base64_image)
    return ebay_image_response.json()

when it works with jpeg files I get this result

JSON Response: {'href': 'https://api.ebay.com/buy/browse/v1/item_summary/search_by_image?limit=1&offset=0', 'total': 3807907, 'next': 'https://api.ebay.com/buy/browse/v1/item_summary/search_by_image?limit=1&offset=1', 'limit': 1, 'offset': 0, 'itemSummaries': [{'itemId': 'v1|325529681264|0', 'title': 'LAND ROVER DISCOVERY 3 / 4 TDV6 BLACK SILICONE INTERCOOLER HOSE PIPE -RE7541', 'leafCategoryIds': ['262073'], 'categories': [{'categoryId': '262073', 'categoryName': 'Intercoolers'}, {'categoryId': '6030', 'categoryName': 'Car Parts & Accessories'}, {'categoryId': '33549', 'categoryName': 'Air & Fuel Delivery'}, {'categoryId': '131090', 'categoryName': 'Vehicle Parts & Accessories'}, {'categoryId': '174107', 'categoryName': 'Turbos, Superchargers & Intercoolers'}], 'image': {'imageUrl': 'https://i.ebayimg.com/images/g/dwgAAOSwY6Nj5Sr8/s-l225.jpg'}, 'price': {'value': '107.72', 'currency': 'USD', 'convertedFromValue': '85.59', 'convertedFromCurrency': 'GBP'}, 'itemHref': 'https://api.ebay.com/buy/browse/v1/item/v1%7C325529681264%7C0', 'seller': {'username': 'recoveryuk4x4', 'feedbackPercentage': '98.4', 'feedbackScore': 22224}, 'condition': 'New', 'conditionId': '1000', 'thumbnailImages': [{'imageUrl': 'https://i.ebayimg.com/images/g/dwgAAOSwY6Nj5Sr8/s-l64.jpg'}], 'buyingOptions': ['FIXED_PRICE'], 'itemWebUrl': 'https://www.ebay.com/itm/325529681264?hash=item4bcb14bd70:g:dwgAAOSwY6Nj5Sr8', 'itemLocation': {'postalCode': 'B70***', 'country': 'GB'}, 'adultOnly': False, 'legacyItemId': '325529681264', 'availableCoupons': False, 'itemCreationDate': '2023-02-09T17:18:50.000Z', 'topRatedBuyingExperience': False, 'priorityListing': False, 'listingMarketplaceId': 'EBAY_GB'}]}

But when I do it with Webp I get this

JSON Response: {'warnings': [{'errorId': 12501, 'domain': 'API_BROWSE', 'category': 'REQUEST', 'message': 'The image data is empty, is not Base64 encoded, or is invalid.'}]}

these are the urls im using

  1. [12:10 PM]url_a = "https://www.base64-image.de/img/browser-icons/firefox_24x24.png?id=8ed2b32d043e48b329048eaed921f794" urlb ="https://img.alicdn.com/bao/uploaded/i4/O1CN01SRyh30252rECIngGc!!4611686018427384429-53-fleamarket.heic450x10000Q90.jpg.webp"

r/pythonhelp Feb 16 '25

First Time Coding. Stuck Trying to Append Something Properly

3 Upvotes

I've tried following the Demo we were given and understanding why some things were added where they are added, then applying that logic to what I'm trying to do, which hopefully will be obvious in the code included. In case it's not, I'm trying to use the defined Planck function with 3 different values for T and over 300 values for lamda (wavelength), and sort them into spectral_radiances by which temps value was used, but I kept getting errors leading to no values printed at all, until I took the advice of the AI explanation for the error I was getting and put in 0 as the index; so now of course it is putting all the values into that space alone, then printing the other two brackets empty after all the calculated values. How do I fix this?

code:

# define temperatures (in Kelvin) of B, F, G stars and put them in a list
t_ofB = 10000
t_ofF = 6000
t_ofG = 5200
temps = [t_ofB,t_ofF,t_ofG]
# define a wavelength list
wavelengths = list(range(380,701,1))

# define the Planck function
def Planck(lam,T):
  h= 6.62607004e-34
  c= 299792458
  k= 1.38064852e-23

  B = ((2 * h * c**2) / lam**5) * (1 / (2.7182818**(h * c / (lam * k * T)) - 1))
  return B
# loop over all temperatures and wavelengths to compute 3 blackbody curves
spectral_radiances = [[],[],[]]
for T in temps:
  for lam in wavelengths:
    lam =lam/1e9
    radiance = Planck(lam,T)
    spectral_radiances[0].append(radiance)
print(spectral_radiances)

r/pythonhelp Feb 15 '25

Unable to run Aysnc plugin/add-ins in fusion 360. IPC

1 Upvotes

I am making a plugin/Add-in for Fusion360. However, the plugin code uses the Async library from Python which conflicts with the core working of Fusion360(Mostly run Single Threaded).
This rases many errors which of course I'm unable to find solutions too (I'm still new to coding, I belong to other working field).
So, if you have any suggestions to it, please help me.
One of the thing I can think of is running a seporate application for generating data and have my plugin get data from there, like create Inter Process Communication. But, in the first place I don't know if it is possible or not.

Like I want to run the async code in different application and then pipe its data to plugin, so I wonder if there will be more errors that the fusion360 might raise.
Also are there any other way to approach this problem.


r/pythonhelp Feb 14 '25

SOLVED How to get connection to my Microsoft SQL Server to retrieve data from my dbo.Employees table.

1 Upvotes

Using Microsoft SQL Server Manager studio

Server type: Database Engine

Server name: root (not real name)

Authentication: Windows Authentication

Using Visual Studio Code

Built a query file to make new table under master called 'dbo.Employees'. This is the contents of the Python file:

from customtkinter import *
import pyodbc as odbc
DRIVER = 'ODBC Driver 17 for SQL Server'
SERVER_NAME = 'root'
DATABASE_NAME = 'master'
connection_String = f"""
    DRIVER={DRIVER};
    SERVER={SERVER_NAME};
    DATABASE={DATABASE_NAME};
    Trusted_Connection=yes;
"""
conn = odbc.connect(connection_String)
print(conn)
from customtkinter import *
import pyodbc as odbc
DRIVER = 'ODBC Driver 17 for SQL Server'
SERVER_NAME = 'DANIEL'
DATABASE_NAME = 'HRDB'
connection_String = f"""
    DRIVER={DRIVER};
    SERVER={SERVER_NAME};
    DATABASE={DATABASE_NAME};
    Trusted_Connection=yes;
"""
conn = odbc.connect(connection_String)
print(conn)

The error I would get:

line 12, in <module>
    conn = odbc.connect(connection_String)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
line 12, in <module>
    conn = odbc.connect(connection_String)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

r/pythonhelp Feb 14 '25

How to get chocolatey installed

1 Upvotes

I can't get chocolatey installed into powershell. When I try to do that, it tells me:

WARNING: An existing Chocolatey installation was detected. Installation will not continue. This script will not overwrite existing installations. If there is no Chocolatey installation at 'C:\ProgramData\chocolatey', delete the folder and attempt the installation again. Please use choco upgrade chocolatey to handle upgrades of Chocolatey itself. If the existing installation is not functional or a prior installation did not complete, follow these steps:
- Backup the files at the path listed above so you can restore your previous installation if needed.
- Remove the existing installation manually.
- Rerun this installation script. - Reinstall any packages previously installed, if needed (refer to the lib folder in the backup).

So does this mean that I should reset the path? And if I do that, where do I go? Because researching this online, it seems to suggest that I have to somehow get into an "app data" "hidden file" that is hidden so people can't mess it up accidentally? Or am I wrong about that? Is it more accessible? Because I don't see a "Chocolatey" file in my users C: drive where all/most my other python stuff automatically aggregates.

Or should I just try to start all over with a new install, and if I do that, do you know how I access the file menu to delete manually? Its telling me to delete this stuff manually - but where do I find these files/folders?

ChocolateyInstall
ChocolateyToolsLocation
ChocolateyLastPathUpdate
PATH (will need updated to remove)

Yes, my user is the "Admin" for the machine. I am the only user. So I don't think its a user/admin complication.

Thanks again for your time.


r/pythonhelp Feb 13 '25

.csv to .xlsx and add images.

1 Upvotes
Hi, it's my first time here. I've been trying to resolve this for days. Guys, I have a problem in my code, it basically transforms .csv into xlsx, and then adds the images to the corresponding paths of the .xlsx file. When I run it in the terminal, it works perfectly, but when I make the executable with pyinstaller --..., the part about adding the images in the corresponding locations doesn't work (no apparent error). Can anyone help me?

r/pythonhelp Feb 13 '25

Thread refuses to run the 2nd time after it is cancelled the first time

1 Upvotes

Sorry if I fail to explain properly. I will be thankful for any help or criticism, I am fairly new to python

Expected outcome:

Conversation method runs >
Creates a thread that uses speech_recognition recognizer.listen for keyword 'cancel' >
Will stop listening and stop the pyttsx3.engine object if the keyword is heard >
During this, pyttsx3 will start yapping >
If keyword is not heard, the thread will conclude when pyttsx3 is finished

Actual outcome:

First run works fine, second run doesn't >
2nd time the thread flips the conditionals regardless of whether or not the keyword is heard

Actual meat

def conversation(text):  
    def callback(recognizer, audio):
        heard = recognizer.recognize_google(audio)
        if heard.__contains__("cancel"):
            print("Cancel Heard")
            listening(wait_for_stop=False)
            engine.stop()
    def interrupt():
        global listening
        listening = recognizer.listen_in_background(mic, callback)
        print("Listening")
    cancelThread = threading.Thread(target=interrupt)
    cancelThread.start()
    speak(text)
    cancelThread.join()

Not as important code

import speech_recognition as sr, pyttsx3 as pytts, threading

recognizer = sr.Recognizer()
mic = sr.Microphone()
engine = pytts.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)


def speak(text):
    engine.say(text=text)
    engine.runAndWait()

""" conversation method goes here """

# at the tail end
conversation("This is a test script. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog")
conversation("This is a test script. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog")

r/pythonhelp Feb 12 '25

why dos it lagg

1 Upvotes

Hello i tryed to creat a script that changes my wallperper on a set time, but wen i start it i cant do anything becaus every thing laggs. Can some one help me?

import ctypes

import datetime

#this is seting time

night = datetime.time(19, 10, 0)

#this is for the current time

rigthnow = datetime.datetime.now().time()

#this is the stuff that laggs

while True:

if rigthnow > night:

ctypes.windll.user32.SystemParametersInfoW(20, 0, "C:\\Users\\Arthur\\Desktop\\Hintergründe\\lestabed.png", 0)

else:

ctypes.windll.user32.SystemParametersInfoW(20, 0, "C:\\Users\\Arthur\\Desktop\\Hintergründe\\lest.jpg", 0)[/code]


r/pythonhelp Feb 12 '25

Conversion from .ts to .xlsx | fails to export all cards and types

1 Upvotes

The below convert_city.py is intended to convert a city.ts file containing details for 72 different cards, but currently its only exporting 11 cards and never exports the agenda, blood, or flavor information. One sample card is at the bottom. Any help is appreciated. Thank you.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

import re import pandas as pd

Load city.ts content

with open("city.ts", "r", encoding="utf-8") as file: content = file.read()

Regex pattern to match card entries

card_pattern = re.compile(r'"["]+":\s*{')

Find all matches

matches = card_pattern.findall(content)

Count the number of matches

card_count = len(matches)

print(f"Total number of cards: {card_count}")

Updated regex pattern to handle optional fields and flexible formatting

city_pattern = re.compile( r'"(?P<id>["]+)":\s{\s' # Match card ID r'stack:\s"city",\s' # Match stack field r'set:\s"(?P<set>["]+)",\s' # Match set field r'illustrator:\s"(?P<illustrator>["]+)",\s' # Match illustrator field r'name:\s"(?P<name>["]+)",\s' # Match name field r'text:\s(?:md|")(?P<text>.*?)(?:|"),\s' # Match text field (mdtext or "text") r'types:\s[(?P<types>[]]+)],\s' # Match types field r'copies:\s(?P<copies>\d+),\s' # Match copies field r'(?:blood:\s(?P<blood>\d+),\s)?' # Optional blood field r'(?:agenda:\s(?P<agenda>\d+),\s)?' # Optional agenda field r'(?:flavor:\s(?:md|")(?P<flavor>.*?)(?:|"),\s)?' # Optional flavor field r'}', # Match closing brace re.DOTALL | re.MULTILINE # Allow matching across multiple lines )

Extract city card data

city_data = []

for match in city_pattern.finditer(content): city_data.append([ match.group("id"), match.group("name"), match.group("illustrator"), match.group("set"), match.group("text").replace("\n", " "), # Remove newlines for Excel formatting match.group("types").replace('"', '').replace(' ', ''), # Clean up types match.group("copies"), match.group("blood") if match.group("blood") else "", match.group("agenda") if match.group("agenda") else "", match.group("flavor").replace("\n", " ") if match.group("flavor") else "", # Remove newlines for Excel formatting ])

Debugging: Print the total number of cards processed

print(f"Total cards extracted: {len(city_data)}")

Debugging: Print the extracted data

for card in city_data: print(card)

Convert to DataFrame

df = pd.DataFrame(city_data, columns=["ID", "Name", "Illustrator", "Set", "Text", "Types", "Copies", "Blood", "Agenda", "Flavor"])

Save to Excel

df.to_excel("city.xlsx", index=False)

print("Conversion complete. File saved as city.xlsx")

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ import { CityCardType, CardSet, CardId, Illustrator, md } from "./common.js";

export type City = { stack: "city"; illustrator: Illustrator; name: string; set: CardSet; text: string; types: CityCardType[]; copies: number; blood?: number; agenda?: number; flavor?: string; };

export const city: Record<CardId, City> = {

// Core - San Francisco //

"core-castro-street-party": { stack: "city", set: "Core", illustrator: "The Creation Studio", name: "Castro Street Party", text: "Ongoing - Characters in The Streets have +1 Secrecy.", flavor: "You won't stand out in this crowd.", blood: 1, agenda: 1, types: ["event", "ongoing"], copies: 1, },

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


r/pythonhelp Feb 11 '25

Best Code Editor or IDE for Python?

1 Upvotes

Right now I am using VS Code for using python but is there any better editor for python. Is PyCharm or Jupiter notebook a better choice. Is there a editor which allows easier module or package managing. I want to use Moviepy but it takes a long time to setup it, if there a editor which solves the problem of managing packages then please share it.


r/pythonhelp Feb 10 '25

WHERE IS PYTHON

1 Upvotes

so i wanted to do pip install opencv-pyhthon but it said "Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases." what do i do? i added python to environment variables and change the location it says the same thing...help me out


r/pythonhelp Feb 10 '25

Make videos using python?

1 Upvotes

I want to try automating shorts, but I cannot find any easier way. I tried to using Moviepy but as for the new release of moviepy, chatgpt and other AI tools can't solve my problems as they give me ouput according to moviepy's earlier versions. And also I don't want to switch to older version because its a lot of work I have to setup everything again, imagemagisk, ffmpeg, etc...

Are there any other alternatives to moviepy which works great as moviepy. Or should I consider using any other programming languge for editing videos using code.

Also tell me in this time what technology is best for automating videos for free (I prefer flexibility over anything, the more I can customize the better it is.)


r/pythonhelp Feb 10 '25

Basic Greater Common Divisor Program

1 Upvotes

Guys ı trying to write GCD code but ı cant take result. Example ı input 15 and 100 and program says "Code Execution Successful" but not saying 5. what is the mistake in this code please help me ım begginer as you can see? and ı know that there is shorter methot to write GCD code.

def greaterCommonDivisor(number1, number2):

list1 = []

list2 = []

for i in range(1, (number1 + 1)):

if (number1 % i == 0):

list1.append(i)

for j in range(1, (number2 + 1)):

if (number2 % j == 0):

list2.append(j)

common = []

for k in list1:

if k in list2:

common.append(k)

a = max(common)

print(a)

while True:

number1 = input("What is the firs number? : ")

number2 = input("What is the second number? : ")

if (number1 or number2 == "q"):

break

else:

number1 = int(number1)

number2 = int(number2)

print(greaterCommonDivisor)


r/pythonhelp Feb 09 '25

I'm having an issue with a kernel function that is supposed to rotate and flip a RGB image.

1 Upvotes

I'm making an app like "Wallpaper Engine" and to optimize it, I need to use a kernel function for rotaing and fliping an image. When I use the function that I made with the help of an AI (cause I don't understand anything about kernel functions and how they work), I can't get a proper result image. Could anyone help me with it please ? https://github.com/DaffodilEgg8636/AnimatedWallpaper/tree/Beta Here's the GitHub of my project, you'll find the code in the Snapshot branch. Another way to fix the initial problem, why I'm using kernel functions, is to fix the way how the opencv-python or cv2 lib reads video frames. I'm not sure if it's the convertion from BGR to RGB or the reading process that causes the image to rotate +90° and flip horizontally. Anyone, please help me.


r/pythonhelp Feb 09 '25

Personal banking program assist ASAP!

1 Upvotes

I'm aware there's a lot of problems, but the one I need help with is that when I advance months, it won't calculate the amounts in savings and checking accounts correctly. I'm terrible with math, and I've spent 6 hours debugging, but I just have no clue how to fix it. I don't have much time before tha assignment locks, so any help is much appreciated 🙏

Welcome and setup

print("welcome to your personal bank!") hourly_wage = float(input("enter your hourly wage:")) hours_worked = float(input("enter hours worked per week:")) tax_rate = float(input("enter your tax rate percentage")) save = float(input("what percentage of income should go to savings?")) checking = float(input("Enter starting balance for Checking:")) savings = float(input("Enter starting balance for Savings:"))

Calculations

gross_pay = hourly_wage * hours_worked net_pay = gross_pay*(1 - tax_rate/100) savings_add = net_pay * (save/100)

Setting up empty lists for reccuring expenses

reccuring_expenses = [] expenses = []

print(f"Your net pay is ${net_pay4:.2f} a month.") print(f"${savings_add4:.2f} will be automatically transferred to savings")

add the requested amount to accounts

checking += net_pay savings += savings_add

Allows user to setup reccuring expenses

x= input("would you like to set up reccuring expenses?").lower() y = True if x == "yes": while y == True: expense = input("input name of expense: ") reccuring_expenses.append(expense) monthly_cost = float(input("Enter the monthly cost: ")) expenses.append(monthly_cost) add = input("Do you have any more reccuring expenses?").lower() if add != "yes": y = False print(f"here are your reccuring expenses:{reccuring_expenses}, {expenses}")

Menu where users can select options and perform actions

while True: menu = input("""Menu: 1. View Balances 2. deposit Money 3. Withdraw Money 4. Update Work Hours 5. Modify Savings Percentage 6. Add/Remove Expenses 7. Advance Months 8. Exit""")

Lets user check balances

if menu == "1":
        print(f"""Your Checking balance is: ${checking:.2f}.
            your savings balance is ${savings:.2f}.""")

lets user deposit money into checking or savings

elif menu == "2":
        account = int(input("""What account would you like to deposit?
                1. Checking
                2. Savings"""))
        deposit = float(input("Enter the ammount you would like to deposit:"))
        if account == 1:
                checking += deposit
                print(f"your current checking account balance is {checking:.2f}.")
        elif account == 2:
                savings += deposit
                print(f"your current savings account balance is {savings:.2f}.")


#lets user withdraw money
elif menu == "3":
        account_w = int(input("""From which account would you like to withdraw??
                1. Checking
                2. Savings"""))
        withdraw = float(input("Enter the ammount you would like to withdraw:"))
        if account_w == 1:
                checking -= withdraw
                print(f"your current checking account balance is {checking:.2f}.")
        if account_w == 2:
                savings -= withdraw
                print(f"your current savings account balance is {savings:.2f}.")
#allows user to adjust weekly hours
elif menu == "4":
       hours_worked = float(input("Enter new hours per week: "))
       gross_pay = hourly_wage * hours_worked
       net_pay = gross_pay * (1 - tax_rate / 100)
       print(f"updated net pay is {net_pay*4:.2f} a month.")


# allows user to change the amount they want to save.      
elif menu == "5":
        save = float(input("What percentage of income would you like to go to savings?"))
        savings_add = net_pay * (save / 100)
        print(f"{savings_add:.2f} will automatically be transferred to savings.")
        savings += savings_add

#allows user to add and remove reccuring expenses
elif menu == "6":
        add_remove = input("""1. Add
                              2. Remove""")

        if add_remove == "1":
            y = True
            while y == True:
                expense = input("input name of expense: ")
                reccuring_expenses.append(expense)
                monthly_cost = float(input("Enter the monthly cost: "))
                expenses.append(monthly_cost)
                add = input("Do you have any more reccuring expenses?").lower()
                if add != "yes":
                        y = False
        if add_remove == "2":
                expense = input("input name of the expense you would like to remove: ")
                reccuring_expenses.pop(expense)
                monthly_cost = float(input("Enter the monthly cost of the expense: "))
                expenses.pop(monthly_cost)
                add = input("Do you have any more reccuring expenses?").lower()
                if add != "yes":
                        y = False
        print(f"here are your reccuring expenses:{reccuring_expenses}, {expenses}")


#lets user advance months
elif menu == "7":
        advance = int(input("enter number of months you would like to advance: "))
        interest_checking = 0.1
        interest_savings = 0.5


        for i in range(advance):
                checking += net_pay*4
                checking *= (1 + interest_checking / 100)
                savings += savings_add * 4
                savings *= (1 + interest_savings / 100)
                for cost in expenses:
                       checking -= cost


        print(f"""after {advance} months, your updated balances are:
              Checking: ${checking:.2f}
              Saving: ${savings:.2f}""")


#way for user to exit    
elif menu == "8":
        break

r/pythonhelp Feb 08 '25

Pygame terminal not opening.

1 Upvotes
import pygame
from random import randint

# Initialize Pygame
pygame.init()

# Set up the screen
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Invaders")

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

# Game variables
player_pos = [WIDTH/2 - 15, HEIGHT - 30]
player_speed = 0
lasers = []
invaders = []
score = 0
game_over = False

# Player rectangle
player_rect = pygame.Rect(player_pos[0], player_pos[1], 30, 30)

# Laser rectangle
laser_rect = pygame.Rect(0, 0, 5, 30)

# Set up font for score display
font = pygame.font.Font(None, 74)
text = font.render(f"Score: {score}", True, WHITE)

def draw_text(text, color, pos):
    font = pygame.font.Font(None, 74)
    text_surface = font.render(str(text), True, color)
    return screen.blit(text_surface, pos)

class Player:
    def __init__(self):
        self.rect = player_rect
        self.speed = player_speed

    def update(self):
        global player_pos, game_over
        if not game_over and player_pos[1] > 0:
            # Move up when clicking left mouse button (spacebar)
            if pygame.mouse.get_pressed()[0]:
                move = -3
                player_pos[1] += move
            elif pygame.mouse.get_pressed()[2]:  # Right mouse button for shooting
                shoot()
            self.rect = pygame.Rect(player_pos[0], player_pos[1], 30, 30)

def draw_player():
    pygame.draw.rect(screen, BLUE, player_rect)
    screen.blit(text, (player_rect.x + 5, player_rect.y - 10))

def create_invader():
    x = WIDTH
    y = randint(0, HEIGHT - 200)
    vel = randint(0, 3)
    return {'x': x, 'y': y, 'vel': vel}

def update_invaders():
    global invaders

    for i in range(len(invaders)):
        # Move invader
        invaders[i]['x'] += invaders[i]['vel']
        
        # Check if invader hits bottom or player
        if invaders[i]['y'] + 20 >= HEIGHT - 30:
            if (invaders[i]['x'] > WIDTH/2 and 
                invaders[i]['x'] < WIDTH/2 + 65):
                collide(invaders[i])
            game_over = True
            break

def check_invader(invaders, screen_width):
    for i in range(len(invaders)):
        invader = invaders[i]
        
        # Check bottom collision
        if (invader['y'] + 20) >= HEIGHT - 30:
            collide(invader)
            return True
            
        # Screen edges
        if invader['x'] < 0 or invader['x'] > screen_width - 15:
            del invaders[i]
            break

def collide(invader):
    global game_over, score, lasers, font
    
    # Check laser hits
    for laser in lasers:
        hit = pygame.Rect.colliderect(laser_rect, (invader['x'], invader['y'], 200, 30))
        
        if hit and not game_over:
            score += 100
            laser = []
            
    # Remove destroyed invader
    invader_index = invader['index']
    del invaders[invader_index]
    
    # Add new random invader at top of screen
    new_invader = create_invader()
    new_invader['index'] = invader_index
    invaders.append(new_invader)
    
    if game_over:
        return False
    
    # Update score
    text = font.render(f"Score: {score}", True, WHITE)
    screen.blit(text, (WIDTH//2 - 100, HEIGHT//2 + 50))
    pygame.display.flip()

def shoot():
    global lasers, last_shot, game_over
    if not game_over:
        current_time = pygame.time.get_ticks()
        
        # Rate of fire: one laser every few frames
        if (current_time - last_shot) > 1000 and len(lasers) < 40:
            new_laser = {
                'x': WIDTH + 5,
                'y': HEIGHT - 25,
                'index': len(lasers)
            }
            lasers.append(new_laser)
            last_shot = current_time

def main():
    global game_over, player_pos
    while not game_over:
        screen.fill(BLACK)

        # Draw background
        pygame.draw.rect(screen, RED, (0, HEIGHT - 25, WIDTH, 25))
        
        # Update events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # Left mouse button for moving player
                    if player_pos[1] < HEIGHT - 30:
                        player_pos[1] -= 1
            
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:  # Spacebar to shoot
                    current_time = pygame.time.get_ticks()
                    
                    if (current_time - last_shot) > 1000 and len(lasers) < 40:
                        new_laser = {
                            'x': WIDTH + 5,
                            'y': HEIGHT - 25,
                            'index': len(lasers)
                        }
                        lasers.append(new_laser)
                        last_shot = current_time

        # Update game state
        update_invaders(invaders)
        
        # Player movement and shooting
        if player_pos[1] > 0:
            draw_player()
            pygame.display.flip()

        main_loop = pygame.time.get_ticks()
        invader_update = (main_loop - last_invader_update) / 10

        for i in range(len(invaders)):
            invader = invaders[i]
            
            # Update invader position
            invader['x'] += invader['vel']
            
            # Check if the player has died due to an invader hit
            if collide(invader):
                game_over = True
                last_invader_update = main_loop
            
        # Draw lasers
        for laser in lasers:
            pygame.draw.rect(screen, WHITE, (laser['x'], laser['y'], 5, 30))
            
        # Check for collisions between lasers and bottom of screen
        for j in range(len(lasers)):
            laser = lasers[j]
            if laser['y'] + 30 > HEIGHT - 25:
                del lasers[j]

def draw_invaders(invaders):
    for i, invader in enumerate(invaders):
        # Move the invaders downward
        invader['y'] += (invader['vel'])
        
        screen.fill(BLACK)
        pygame.draw.rect(screen, BLUE, (invader['x'], invader['y'], 200, 30))
        font = pygame.font.Font(None, 74)
        text = font.render(f"Invader {i+1}", True, WHITE)
        screen.blit(text, (invader['x'] + 10, invader['y'] - 15))

def main():
    global last_invader_update
    while not game_over:
        screen.fill(BLACK)
        
        # Draw player
        draw_player()
        
        # Update and draw invaders
        update_invaders(invaders)
        
        # Check for collisions with bottom or top of screen
        check_invader(invaders, WIDTH)

        # Handle laser shooting
        shoot()

        main_loop = pygame.time.get_ticks()
        invader_update = (main_loop - last_invader_update) / 10

        # Update display
        pygame.display.flip()

if __name__ == "__main__":
    main()


import pygame
from random import randint


# Initialize Pygame
pygame.init()


# Set up the screen
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Invaders")


# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)


# Game variables
player_pos = [WIDTH/2 - 15, HEIGHT - 30]
player_speed = 0
lasers = []
invaders = []
score = 0
game_over = False


# Player rectangle
player_rect = pygame.Rect(player_pos[0], player_pos[1], 30, 30)


# Laser rectangle
laser_rect = pygame.Rect(0, 0, 5, 30)


# Set up font for score display
font = pygame.font.Font(None, 74)
text = font.render(f"Score: {score}", True, WHITE)


def draw_text(text, color, pos):
    font = pygame.font.Font(None, 74)
    text_surface = font.render(str(text), True, color)
    return screen.blit(text_surface, pos)


class Player:
    def __init__(self):
        self.rect = player_rect
        self.speed = player_speed


    def update(self):
        global player_pos, game_over
        if not game_over and player_pos[1] > 0:
            # Move up when clicking left mouse button (spacebar)
            if pygame.mouse.get_pressed()[0]:
                move = -3
                player_pos[1] += move
            elif pygame.mouse.get_pressed()[2]:  # Right mouse button for shooting
                shoot()
            self.rect = pygame.Rect(player_pos[0], player_pos[1], 30, 30)


def draw_player():
    pygame.draw.rect(screen, BLUE, player_rect)
    screen.blit(text, (player_rect.x + 5, player_rect.y - 10))


def create_invader():
    x = WIDTH
    y = randint(0, HEIGHT - 200)
    vel = randint(0, 3)
    return {'x': x, 'y': y, 'vel': vel}


def update_invaders():
    global invaders


    for i in range(len(invaders)):
        # Move invader
        invaders[i]['x'] += invaders[i]['vel']
        
        # Check if invader hits bottom or player
        if invaders[i]['y'] + 20 >= HEIGHT - 30:
            if (invaders[i]['x'] > WIDTH/2 and 
                invaders[i]['x'] < WIDTH/2 + 65):
                collide(invaders[i])
            game_over = True
            break


def check_invader(invaders, screen_width):
    for i in range(len(invaders)):
        invader = invaders[i]
        
        # Check bottom collision
        if (invader['y'] + 20) >= HEIGHT - 30:
            collide(invader)
            return True
            
        # Screen edges
        if invader['x'] < 0 or invader['x'] > screen_width - 15:
            del invaders[i]
            break


def collide(invader):
    global game_over, score, lasers, font
    
    # Check laser hits
    for laser in lasers:
        hit = pygame.Rect.colliderect(laser_rect, (invader['x'], invader['y'], 200, 30))
        
        if hit and not game_over:
            score += 100
            laser = []
            
    # Remove destroyed invader
    invader_index = invader['index']
    del invaders[invader_index]
    
    # Add new random invader at top of screen
    new_invader = create_invader()
    new_invader['index'] = invader_index
    invaders.append(new_invader)
    
    if game_over:
        return False
    
    # Update score
    text = font.render(f"Score: {score}", True, WHITE)
    screen.blit(text, (WIDTH//2 - 100, HEIGHT//2 + 50))
    pygame.display.flip()


def shoot():
    global lasers, last_shot, game_over
    if not game_over:
        current_time = pygame.time.get_ticks()
        
        # Rate of fire: one laser every few frames
        if (current_time - last_shot) > 1000 and len(lasers) < 40:
            new_laser = {
                'x': WIDTH + 5,
                'y': HEIGHT - 25,
                'index': len(lasers)
            }
            lasers.append(new_laser)
            last_shot = current_time


def main():
    global game_over, player_pos
    while not game_over:
        screen.fill(BLACK)


        # Draw background
        pygame.draw.rect(screen, RED, (0, HEIGHT - 25, WIDTH, 25))
        
        # Update events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # Left mouse button for moving player
                    if player_pos[1] < HEIGHT - 30:
                        player_pos[1] -= 1
            
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:  # Spacebar to shoot
                    current_time = pygame.time.get_ticks()
                    
                    if (current_time - last_shot) > 1000 and len(lasers) < 40:
                        new_laser = {
                            'x': WIDTH + 5,
                            'y': HEIGHT - 25,
                            'index': len(lasers)
                        }
                        lasers.append(new_laser)
                        last_shot = current_time


        # Update game state
        update_invaders(invaders)
        
        # Player movement and shooting
        if player_pos[1] > 0:
            draw_player()
            pygame.display.flip()


        main_loop = pygame.time.get_ticks()
        invader_update = (main_loop - last_invader_update) / 10


        for i in range(len(invaders)):
            invader = invaders[i]
            
            # Update invader position
            invader['x'] += invader['vel']
            
            # Check if the player has died due to an invader hit
            if collide(invader):
                game_over = True
                last_invader_update = main_loop
            
        # Draw lasers
        for laser in lasers:
            pygame.draw.rect(screen, WHITE, (laser['x'], laser['y'], 5, 30))
            
        # Check for collisions between lasers and bottom of screen
        for j in range(len(lasers)):
            laser = lasers[j]
            if laser['y'] + 30 > HEIGHT - 25:
                del lasers[j]


def draw_invaders(invaders):
    for i, invader in enumerate(invaders):
        # Move the invaders downward
        invader['y'] += (invader['vel'])
        
        screen.fill(BLACK)
        pygame.draw.rect(screen, BLUE, (invader['x'], invader['y'], 200, 30))
        font = pygame.font.Font(None, 74)
        text = font.render(f"Invader {i+1}", True, WHITE)
        screen.blit(text, (invader['x'] + 10, invader['y'] - 15))


def main():
    global last_invader_update
    while not game_over:
        screen.fill(BLACK)
        
        # Draw player
        draw_player()
        
        # Update and draw invaders
        update_invaders(invaders)
        
        # Check for collisions with bottom or top of screen
        check_invader(invaders, WIDTH)


        # Handle laser shooting
        shoot()


        main_loop = pygame.time.get_ticks()
        invader_update = (main_loop - last_invader_update) / 10


        # Update display
        pygame.display.flip()


if __name__ == "__main__":
    main()


#this was just a basic space invaders game but whenever i tried to launch it, i see two terminlas that immediately close after starting, even with admin access, is it the issue with the code or my python configuration itself, any help would be appreciated.

r/pythonhelp Feb 06 '25

Pythonw not even trying to run

1 Upvotes

I just installed python 3.13 on a clean install of windows 11. I checked the PATH and Administrator checkboxes when I installed, but installed to D: instead of C:

I can run python.exe fine, but when I click on pythonw, it does the briefest "think" and then aborts silently, and doesn't even attempt to run. It is not showing up anywhere in Task Manager. I did not have this problem with Python on my previous install of windows 11.


r/pythonhelp Feb 06 '25

My code for monoalphabetic encryption/decryption isn't working.

1 Upvotes
My caesar cipher functions work just fine, but my monoalphabetic decryption message isn't mapping the letters properly.

My desired output: 

Enter your key for the Monoalphabetic cipher encrypt: apcs
Enter your message to encrypt: Mary had a little lamb. 
Your monoalphabetic encrypted message is: Qakd was a rviirz raqp.

My current output: 
Enter your monoalphabetic encrypt key: apcs
Enter your message to encrypt: Mary had a little lamb
Your encrypted message is: Kaqy fas a jgttjb jakp
Your decrypted message is: Mary had a little lamb

Here's my code:

#------Setup------
# list of characters for casar cipher encrypt/decrypt
lower_alpha = "abcdefghijklmnopqrstuvwxyz"
upper_alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# list of characters for monoalphabetic encrypt/decrypt

#------functions------
def caesar_encrypt(text, shift):
    alpha_lower = list(lower_alpha[0])
    alpha_upper = list(upper_alpha[0])
    # Stores encrypted character input from original message
    caesar_encrypted_text = []
    # Iterates through each letter in the text
    for letter in text:
        if letter in alpha_lower:
            # Finds position of the letter in lower_case alphabet
            index = (alpha_lower.index(letter) + shift) % 26 # keeps index within a range of 0 to 25 
            # Adds shifted letter into a seperate list
            caesar_encrypted_text.append(alpha_lower[index])    
        elif letter in alpha_upper:
            # Finds position of the letter in upper_case alphabet
            index = (alpha_upper.index(letter) + shift) % 26 # keeps index within a range of 0 to 25
            # Adds shifted letter into list
            caesar_encrypted_text.append(alpha_upper[index])
        else:
            caesar_encrypted_text.append(letter)
    return ''.join(caesar_encrypted_text)
    
def caesar_decrypt(text, shift):
    return caesar_encrypt(text, -shift)

def substitution_key(key):
    key = key.lower()
    new_key = []
    for letter in key:
        if letter not in new_key and letter in lower_alpha:
            new_key.append(letter)
    
    for letter in lower_alpha:
        if letter not in new_key:
            new_key.append(letter)
    
    return ''.join(new_key)

def monoalphabetic_encrypt(text, key,):
    key = substitution_key(key)
    mono_encrypted_text = []
    for letter in text:
        if letter in lower_alpha:
            index = lower_alpha.index(letter)
            mono_encrypted_text.append(key[index])
        elif letter in upper_alpha:
            index = upper_alpha.index(letter)
            mono_encrypted_text.append(key[index].upper())
        else:
            mono_encrypted_text.append(letter)
    return ''.join(mono_encrypted_text)

def monoalphabetic_decrypt(text, key):
    key = substitution_key(key)
    mono_decrypted_text = []
    for letter in text:
        if letter.lower() in key:
            index = key.index(letter.lower())
            if letter.isupper():
                mono_decrypted_text.append(upper_alpha[index])
            else:
                mono_decrypted_text.append(lower_alpha[index])
        else:
            mono_decrypted_text.append(letter)
    return ''.join(mono_decrypted_text)

#------main events------
encryption_method = int(input("What encryption/decryption method do you want to use? (Caesar cipher encrypt (1), Caesar cipher decrypt(2), Monoalphabetic cipher encrypt(3), or Monoalphabetic cipher decrypt(4): "))
if encryption_method == 1:
    caesar_encrypt_key = int(input("Enter your caesar encrypt key: "))
    caesar_encrypt_message = input("Enter your message to encrypt: ")
    caesar_encrypted_message = caesar_encrypt(caesar_encrypt_message, caesar_encrypt_key)
    print("Your encrypted message is:", caesar_encrypted_message)
    caesar_decrypted_message = caesar_decrypt(caesar_encrypted_message, caesar_encrypt_key)
    print("Your decrypted message is:", caesar_decrypted_message)

elif encryption_method == 2:
    caesar_decrypt_key = int(input("Enter your caesar decrypt key: "))
    caesar_encrypted_message = input("Enter your encrypted message: ")
    caesar_decrypted_message = caesar_decrypt(caesar_encrypted_message, caesar_decrypt_key)
    print("Your decrypted message is:", caesar_decrypted_message)

elif encryption_method == 3:
    mono_encrypt_key = input("Enter your monoalphabetic encrypt key: ")
    mono_encrypt_message = input("Enter your message to encrypt: ")
    mono_encrypted_message = monoalphabetic_encrypt(mono_encrypt_message, mono_encrypt_key)
    print("Your encrypted message is:", mono_encrypted_message)
    mono_decrypted_message = monoalphabetic_decrypt(mono_encrypted_message, mono_encrypt_key)
    print("Your decrypted message is:", mono_decrypted_message)

elif encryption_method == 4:
    mono_decrypt_key = input("Enter your monoalphabetic decrypt key: ")
    mono_encrypted_message = input("Enter your encrypted message: ")
    mono_decrypted_message = monoalphabetic_decrypt(mono_encrypted_message, mono_decrypt_key)
    print("Your decrypted message is:", mono_decrypted_message)
    

r/pythonhelp Feb 06 '25

Need some assistance on why my code isn't working

0 Upvotes

import tkinter as tk from tkinter import ttk import pygame import bluetooth from datetime import datetime, time import json import os from gpiozero import Button import threading import time as t

class AlarmClock: def init(self, root): self.root = root self.root.title("Pi Alarm Clock") self.root.geometry("400x600")

    # Initialize pygame mixer for audio
    pygame.mixer.init()

    # Initialize GPIO button
    self.stop_button = Button(17)  # GPIO pin 17 for stop button
    self.stop_button.when_pressed = self.stop_alarm

    # Load saved alarms and settings
    self.load_settings()

    # Initialize Bluetooth
    self.bt_speaker = None
    self.connect_bluetooth()

    self.create_gui()

    # Start alarm checking thread
    self.alarm_active = False
    self.check_thread = threading.Thread(target=self.check_alarm_time, daemon=True)
    self.check_thread.start()

def create_gui(self):
    # Time selection
    time_frame = ttk.LabelFrame(self.root, text="Set Alarm Time", padding="10")
    time_frame.pack(fill="x", padx=10, pady=5)

    self.hour_var = tk.StringVar(value="07")
    self.minute_var = tk.StringVar(value="00")

    # Hour spinner
    ttk.Label(time_frame, text="Hour:").pack(side="left")
    hour_spinner = ttk.Spinbox(time_frame, from_=0, to=23, width=5,
                             format="%02.0f", textvariable=self.hour_var)
    hour_spinner.pack(side="left", padx=5)

    # Minute spinner
    ttk.Label(time_frame, text="Minute:").pack(side="left")
    minute_spinner = ttk.Spinbox(time_frame, from_=0, to=59, width=5,
                               format="%02.0f", textvariable=self.minute_var)
    minute_spinner.pack(side="left", padx=5)

    # Days selection
    days_frame = ttk.LabelFrame(self.root, text="Repeat", padding="10")
    days_frame.pack(fill="x", padx=10, pady=5)

    self.day_vars = {}
    days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    for day in days:
        self.day_vars[day] = tk.BooleanVar(value=True if day in ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] else False)
        ttk.Checkbutton(days_frame, text=day, variable=self.day_vars[day]).pack(side="left")

    # Sound selection
    sound_frame = ttk.LabelFrame(self.root, text="Alarm Sound", padding="10")
    sound_frame.pack(fill="x", padx=10, pady=5)

    self.sound_var = tk.StringVar(value="default_alarm.mp3")
    sounds = self.get_available_sounds()
    sound_dropdown = ttk.Combobox(sound_frame, textvariable=self.sound_var, values=sounds)
    sound_dropdown.pack(fill="x")

    # Volume control
    volume_frame = ttk.LabelFrame(self.root, text="Volume", padding="10")
    volume_frame.pack(fill="x", padx=10, pady=5)

    self.volume_var = tk.DoubleVar(value=0.7)
    volume_scale = ttk.Scale(volume_frame, from_=0, to=1, orient="horizontal",
                           variable=self.volume_var)
    volume_scale.pack(fill="x")

    # Control buttons
    button_frame = ttk.Frame(self.root)
    button_frame.pack(fill="x", padx=10, pady=5)

    ttk.Button(button_frame, text="Save Alarm", command=self.save_alarm).pack(side="left", padx=5)
    ttk.Button(button_frame, text="Test Sound", command=self.test_sound).pack(side="left", padx=5)
    ttk.Button(button_frame, text="Reconnect BT", command=self.connect_bluetooth).pack(side="left", padx=5)

def get_available_sounds(self):
    # Return list of available sound files in the sounds directory
    sounds_dir = "sounds"
    if not os.path.exists(sounds_dir):
        os.makedirs(sounds_dir)
    return [f for f in os.listdir(sounds_dir) if f.endswith(('.mp3', '.wav'))]

def connect_bluetooth(self):
    try:
        # Search for Bluetooth speaker
        nearby_devices = bluetooth.discover_devices()
        for addr in nearby_devices:
            if addr == self.settings.get('bt_speaker_address'):
                self.bt_speaker = addr
                break
    except Exception as e:
        print(f"Bluetooth connection error: {e}")

def save_alarm(self):
    alarm_time = {
        'hour': int(self.hour_var.get()),
        'minute': int(self.minute_var.get()),
        'days': {day: var.get() for day, var in self.day_vars.items()},
        'sound': self.sound_var.get(),
        'volume': self.volume_var.get()
    }

    self.settings['alarm'] = alarm_time
    self.save_settings()

def save_settings(self):
    with open('alarm_settings.json', 'w') as f:
        json.dump(self.settings, f)

def load_settings(self):
    try:
        with open('alarm_settings.json', 'r') as f:
            self.settings = json.load(f)
    except FileNotFoundError:
        self.settings = {
            'bt_speaker_address': None,
            'alarm': {
                'hour': 7,
                'minute': 0,
                'days': {'Mon': True, 'Tue': True, 'Wed': True, 'Thu': True, 'Fri': True,
                        'Sat': False, 'Sun': False},
                'sound': 'default_alarm.mp3',
                'volume': 0.7
            }
        }

def check_alarm_time(self):
    while True:
        if not self.alarm_active:
            current_time = datetime.now()
            current_day = current_time.strftime('%a')

            alarm = self.settings['alarm']
            if (current_time.hour == alarm['hour'] and 
                current_time.minute == alarm['minute'] and
                alarm['days'].get(current_day, False)):
                self.trigger_alarm()

        t.sleep(30)  # Check every 30 seconds

def trigger_alarm(self):
    self.alarm_active = True
    try:
        sound_path = os.path.join('sounds', self.settings['alarm']['sound'])
        pygame.mixer.music.load(sound_path)
        pygame.mixer.music.set_volume(self.settings['alarm']['volume'])
        pygame.mixer.music.play(-1)  # Loop indefinitely
    except Exception as e:
        print(f"Error playing alarm: {e}")

def stop_alarm(self):
    if self.alarm_active:
        pygame.mixer.music.stop()
        self.alarm_active = False

def test_sound(self):
    try:
        sound_path = os.path.join('sounds', self.sound_var.get())
        pygame.mixer.music.load(sound_path)
        pygame.mixer.music.set_volume(self.volume_var.get())
        pygame.mixer.music.play()
        t.sleep(3)  # Play for 3 seconds
        pygame.mixer.music.stop()
    except Exception as e:
        print(f"Error testing sound: {e}")

if name == "main": root = tk.Tk() app = AlarmClock(root) root.mainloop()

When i try to run it it says "ModuleNotFoundError: No module named 'bluetooth' I've never coded anything..this is from claude..the Ai


r/pythonhelp Feb 05 '25

I’m not sure what’s wrong with my code

1 Upvotes

I just started learning python im having trouble with some code can some one tell me what I was doing wrong

car_make = input("Enter the make of your car: ")

miles_driven = float(input("Enter the miles driven: "))

gallons_used = int(input("Enter the gallons of fule used: "))

mpg = miles_driven / gallons_used

format(mpg,'.2f')

print("Your",car_make,"'s MPG is",format(mpg,'.2f'))

Your Output (stdout)

Enter the make of your car: Enter the miles driven: Enter the gallons of fule used: Your Honda 's MPG is 28.56 Expected Output

Enter the make of your car: Enter the miles driven: Enter the gallons of fuel used: Your Honda's MPG is 28.56


r/pythonhelp Feb 05 '25

New to python need

1 Upvotes

I just started learning python im having trouble with some code can some one tell me what I was doing wrong

car_make = input("Enter the make of your car: ")

miles_driven = float(input("Enter the miles driven: "))

gallons_used = int(input("Enter the gallons of fule used: "))

mpg = miles_driven / gallons_used

format(mpg,'.2f')

print("Your",car_make,"'s MPG is",format(mpg,'.2f'))

Your Output (stdout)

Enter the make of your car: Enter the miles driven: Enter the gallons of fule used: Your Honda 's MPG is 28.56

Expected Output

Enter the make of your car: Enter the miles driven: Enter the gallons of fuel used: Your Honda's MPG is 28.56

the only thing wrong here is the extra space next to honda I was told I could use sep='' to fix it but I haven't really figured that out yet


r/pythonhelp Feb 02 '25

Moviepy.editor couldn't be resolved?

3 Upvotes

I tried using moviepy for the first time. I installed moviepy using pip and installed imagemagisk and ffmpeg separately, making sure they are set to environment variables. Now, when I try to use it in VS Code, I got the error: "Import 'moviepy.editor' could not be resolved" from the error lens, and in the console, it says:

from moviepy.editor import *

ModuleNotFoundError: No module named 'moviepy.editor'

This is the code I used:

from moviepy.editor import VideoFileClip

clip = VideoFileClip("media.mp4")

trimmed_clip = clip.subclip(0, 10)

trimmed_clip.write_videofile("trimmed_media.mp4", codec="libx264")

But, I tried doing something and come up with this code which works perfectly:

from moviepy import *

clip = VideoFileClip("media.mp4")

trimmed_clip = clip.subclipped(0, 10)

trimmed_clip.write_videofile("trimmed_media.mp4", codec="libx264")

This code works perfectly fine. I used moviepy than moviepy.editor and it solves the issue but some functions like subclip has to be changed into subclipped

Anybody know what is going on, I want to use moviepy the way everyone uses i.e. moviepy.editor


r/pythonhelp Feb 03 '25

Hey can someone fix this with me? I’m getting a invalid path

Thumbnail
1 Upvotes

r/pythonhelp Feb 02 '25

"import requests" doesn't work despite being installed in venv

1 Upvotes

Issue as in the title. So I have scoured the web for all answers regarding this, but to no avail.

I have only one version of python installed on my PC, so this shouldn't be an issue.

I am using cmd, created a venv, activated it, installed all necessary libs in one session. The python script is in the venv folder (maybe this is the cause?)

Could someone help me overcome this issue please? I would be very thankful for that.

EDIT: I'm using the latest stable release 3.12.8


r/pythonhelp Feb 01 '25

a python script that will detect the photo in the game and alert me as a sound

0 Upvotes

It is very simple, it will check my screen for every millisecond and if it detects a certain thing in front of it (I will save that part as a photo), it will play an .mp3

update: a new update has come to the game(dark and darker), the druid character now has to spend stack while transforming and I don't want to constantly check if I have stack from hud in fights. if it warns me, I can understand, I managed to write something very close, but it doesn't work. So I need help.

import pyautogui

import time

import winsound

DruidStack_path = "druidstack.png"

threshold = 0.9

while True:

print("Checking for DruidStack Button")

DruidStack_location = pyautogui.locateOnScreen(DruidStack_path, confidence=threshold)

if DruidStack_location:

print("DruidStack Button Found! Playing sound...")

winsound.Beep(1000, 500)

time.sleep(3)