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)


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 20 '25

How do I do this; please I beg of u

0 Upvotes

(Keep in mind I cannot use slicing)

2. insertAtIndex (due by end of class for full credit)

Write a function insertAtIndex that takes 3 arguments in the following order: a string called triples, an integer called i and a string called substring. Remember, triples is a string of order, family, species separated by commas. This function will insert substring into triples at index i. The function returns this new string. You can assume that i is a valid index in triples, meaning that it won’t be longer than the length of triples.

Example Usage


r/pythonhelp • • Oct 05 '24

What am I doing wrong? (Beginner)

Thumbnail
reddit.com
0 Upvotes

r/pythonhelp • • Sep 30 '24

how do you get bs4 to find html in a different section of page but same link

0 Upvotes

bs4 appears to not show html if its not immediately visible but because its not a whole new link but rather just hidden behind a (..button?) im not sure how i would get it to see elements within that (..subpage?)

not really any point to this program im just trying to learn the basics of web scraping

i tried searching by a bunch of classes or even just the specific href link, and eventually just searched for every element but even there the html i was looking for was not there at all

code:

import requests
from bs4 import BeautifulSoup

class Products:
def __init__(self, productHtml):
namesList = []
soup = BeautifulSoup(productHtml, features="html.parser")
products = soup.find_all("div", {"class": "product"})
for product in products:
namesList.append(product.get_text().replace("\n", ""))
self.names = namesList
self.links = soup.find_all("a", {"href": "https://mywishlist.online/x/amazon.com/12822103"})
self.test = soup.find_all("a")

r = requests.get("https://mywishlist.online/w/dihkts/rubys-wishlist")
products = Products(r.text)
print(products.names)
print()
print(products.links)
print()
print(products.test)

output:

['Blue Snowball Microphone', 'Bluetooth Earbuds', 'DUALSHOCK®4 Wireless Controller for PS4™']

[]

[<a class="sidebar-toggle" data-action="sidebar-toggle" href="javascript:void(0)"><i class="fa-sharp fa-solid fa-bars"></i></a>, <a class="sidebar-heading text-nowrap" href="https://mywishlist.online"><span class="logo"></span> My Wishlist</a>, <a class="sidebar-user" href="https://mywishlist.online/login" title="Login"><i class="fa-sharp fa-solid fa-arrow-right-to-bracket"></i></a>, <a href="https://mywishlist.online"><i class="fa-sharp fa-solid fa-gift fa-fw"></i>  Create a wishlist</a>, <a href="https://mywishlist.online/secretsanta" title="Secret Santa Generator"><i class="fa-sharp fa-solid fa-hat-santa fa-fw"></i>  Secret Santa</a>, <a href="https://mywishlist.online/finder"><i class="fa-sharp fa-solid fa-sparkles fa-fw"></i>  Gift ideas</a>, <a href="https://mywishlist.online/login"><i class="fa-sharp fa-solid fa-arrow-right-to-bracket fa-fw"></i>  Login</a>, <a class="mb-auto" href="https://mywishlist.online/help"><i class="fa-sharp fa-solid fa-circle-question fa-fw"></i>  Help</a>, <a href="https://mywishlist.online/contact">Contact</a>, <a href="https://mywishlist.online/privacy">Privacy policy</a>]

what i am looking for:

<a href="https://mywishlist.online/x/amazon.com/12822103" target="_blank" rel="noopener" class="btn btn-primary btn-lg btn-block text-truncate">
  <i class="fa-sharp fa-solid fa-cart-shopping"></i>
  &nbsp; View on Amazon
</a>

r/pythonhelp • • Sep 05 '24

Running a python scripts on windows startup

0 Upvotes

I have very little knowledge of programming but I have this folder with many different .py files. And when I want to run it i just type "python mainsetup.py" in cmd. Is there any way to make this run when Windows starts? It's called "Twitch-Channel-Points-Miner-v2" on github.

Thanks for whatever help I can get.


r/pythonhelp • • Sep 22 '24

Repeating lines

0 Upvotes

Hi, I have a question.i have a text and I want to repeat every line or sentence of this text 3 times. Like this:

Input: today is saturday,tomorrow is Sunday

Output: today is saturday,today is saturday,today is saturday,tomorrow is Sunday,tomorrow is Sunday,tomorrow is Sunday.

i couldn,t do it by using ai language models.is there any command in python for that?

Thanks


r/pythonhelp • • Sep 26 '24

Looking for people to join my new python programming community

0 Upvotes

Definitely I am not yet a master but I am learning.I will do my best to help.And that will be the point of this community that everyone can help each other.Nobody has to ask a specific person but everyone is there to help each other as a growing yet Relatively new python community of friendly like minded individuals with unique invaluable skill sets! And colabs and buddies!


r/pythonhelp • • Mar 16 '20

How to convert str 2 list

0 Upvotes

Hello I had some troubles 2 convert a str response 2 a list. My str looks like this:

[[“date”,”color”,”model”], [“2018”,”red”,”6”], [“2019”,”blue”,”1”]]

Is there any easy way 2 convert this string 2 a numpy array or even json?


r/pythonhelp • • Jan 28 '20

For context, I’m practicing lists by recording docs I find in a video game. What did I do wrong?

Post image
0 Upvotes

r/pythonhelp • • May 11 '21

how to create randomness

0 Upvotes

Hello. I made a discord bot using python and i figured out how to use it to send files. My issue is, i have alot of images and i want to make it so that one command works for multiple images but it cycles through them ramdomly. Regular random or shuffle commands do not work for this. the command to send a file is:

@ client.command()
async def example(ctx):
await ctx.send(file=dsc.File('example.txt'))

the installer is:

pip install discord

and to import it do:

import discord as dsc

If anyone has any idea how i can do this that would be very helpfull!


r/pythonhelp • • May 19 '21

Writing code for a discord bot compiles but ignores one line.

0 Upvotes

I try to follow the following Tutorial.

Sadly, without giving errors the bot does not work as in the tutorial.

The line:

message.content.lower()

in the function is for some reason ignored and if I write "hallo" as input instead of "Hallo" there's no response.

I'd like an explanation why it is ignored, and a different line that would work.

My code:

import discord

client = discord.Client()

u/client.event

async def on_message(message):

message.content.lower()

if message.author == client.user:return

if message.content.startswith('Hallo'):await message.channel.send('Welcome to my working bot')

client.run('<token is working just fine>')


r/pythonhelp • • Jan 04 '23

How to display cv2 (yolov3) output video stream inside a tkinter window ??

0 Upvotes

Hello! I hope you are well.

I am working on a object detection desktop application and I am trying to stream the output video (after object detection ie: with boxes and labels) inside a tkinter window. I have tried to do it with a canvas and update the canvas image after every n milliseconds and even use a label image with updating but it doesn't seem to work. It has been a couple days that I am trying with it. The furthest I was able to accomplish was showing the first frame only. I think that I have a problem with the loop. I don't know which one to run first, the mainloop or the updating the canvas loop. Logically, I should run the mainloop first and the updating loop should keep running in the background nothing after the mainloop runs until the tkinter window is closed as I saw in a course (still a tkinter beginner)

Here is the code that enabled me to show the first frame alone (I have hiddent my ip webcam https adress):

import cv2
import numpy as np
from tkinter import *
import PIL
from PIL import ImageTk


# load the model
net = cv2.dnn.readNet('yolov3.weights', 'yolov3.cfg')
# classes list
classes = []
with open('coco.names', 'r') as f:
    classes = f.read().splitlines()


window = Tk()
window.geometry("1000x800")
window.title('opencv inside tkinter !!')

cap = cv2.VideoCapture(0)
adress = "https://ip_webcam_adress:port/video"
cap.open(adress)

# tuple of lines, cols and canals
_, img = cap.read()
height, width, no_channels = img.shape
print('width: ' + str(width) + ' height: ' + str(height))
# Cette fonction effectue :Soustraction moyenne  Mise à l'échelle  Permutation de canaux BR
blob = cv2.dnn.blobFromImage(img, 1 / 255, (416, 416), (0, 0, 0), swapRB=True, crop=False)


# nn input
net.setInput(blob)

# get output layers names
output_layers_names = net.getUnconnectedOutLayersNames()
layerOutputs = net.forward(output_layers_names)

boxes = []
confidences = []
class_ids = []

for output in layerOutputs:
    for detection in output:
        scores = detection[5:]
        class_id = np.argmax(scores)
        confidence = scores[class_id]
        if confidence > 0.5:
            # center to all cadre
            center_x = int(detection[0] * width)
            center_y = int(detection[1] * height)
            w = int(detection[2] * width)
            h = int(detection[3] * height)

            x = int(center_x - w / 2)
            y = int(center_y - h / 2)

            boxes.append([x, y, w, h])
            confidences.append((float(confidence)))
            class_ids.append(class_id)

# print(len(boxes))
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
print("HI  ", indexes)
# add text to the image
font = cv2.FONT_HERSHEY_PLAIN
colors = np.random.uniform(0, 255, size=(len(boxes), 3))
# for i in indexes.flatten()
for i in indexes:
    x, y, w, h = boxes[i]
    label = str(classes[class_ids[i]])
    confidence = str(round(confidences[i], 2))
    color = colors[i]
    print('label is: ' + label)
    cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
    cv2.putText(img, label + " " + confidence, (x, y + 20), font, 2, (255, 255, 255), 2)

    # show
new_size = (int(600), int(337.5))
img = cv2.resize(img, new_size, interpolation=cv2.INTER_LINEAR)
new_img = ImageTk.PhotoImage(image=PIL.Image.fromarray(img))

canvas = Canvas(window, width=600, height=337)
canvas.create_image(0, 0, anchor='nw', image=new_img)
canvas.pack()

window.mainloop()

Thank you in advance for your help. This project is a huge thing for me at school and I would really appreciate your guidance :)


r/pythonhelp • • Dec 21 '22

How to go from a full dataset to one of only one variable meeting a specific criteria given in one of the other variables?

0 Upvotes

I have a dataset that consists of multiple variables but essentially I want to bring this data set down to look at only the variable sensor_specific_error_statistics_bias. Another variable give in quality_level which consists of the values 0-5. I only want to look at sses_bias given a quality_level of 5.

I tried using numpy to get the locations where the value was 5 in quality_level but it didn’t work as I expected it too and I’m not really sure where to go from here


r/pythonhelp • • Jan 19 '23

how do i use a For loop in this code?

0 Upvotes

Hi there, I could use some help. I am trying to add a loop for a series of strike dates to get some historical data for multiple prices. But I can't figure out where to put the 'for loop'.

I want the code to run through a list of different strike prices near the bottom, where it says strike=419, # 385 - 406

I am trying to make the code run through the prices from 385 to 406.

I am not sure how to put the for loop within the method? Or outside of it. I can't figure it out. Any suggestions would be appreciated. thanks! A.

# Parameter initialization at program start.
self.sleeptime = "2S"
self.asset = asset
self.filepath = filepath
self.length = length
self.timestep = timestep
self.timeshift = timeshift
self.set_market("24/7")

self.start_realtime_bars(self.asset)
self.thesestrikes = [380, 381, 392]

def on_trading_iteration(self):
bars = self.get_symbol_bars(
self.asset, self.length, timestep=self.timestep, timeshift=self.timeshift
)
# last_price = self.get_realtime_bars(self.asset)["close"][-1]
# strike_price = self.get_strike_price(
# last_price, 2, self.asset, "20211008"
# )
# print(f"This si the last price from rtb....{last_price}")
# print(strike_price)
last_price = self.get_last_price(self.asset)
print(f"Price for {asset.symbol}, last price is: {last_price}")
# last_option_price_dq = self.get_realtime_bars(self.asset).iat[-1,3]
# self.log_message(f"History pull: {history} and stream: {last_option_price_dq}")
if bars is None:
self.log_message(f"{'*' * 40} Bars returned None.")
else:
self.log_message(f"{'*' * 40} Last price of {self.asset.symbol} is {bars}.")
bars.df.to_csv(self.filepath)
print(bars)

def get_strike_price(self, last_price, spread, asset, expiration_date):
# Returns target strike price.
target_strike = 0
option_asset = self.create_asset(
asset.symbol,
asset_type="option",
expiration=expiration_date,
right="CALL",
multiplier=100,
)

strikes = self.get_strikes(option_asset)
print(strikes)

for strike in strikes:

print(
f"strike: {strike}, last price: {last_price}, "
f"spread: {spread}, diff: {last_price - spread}, "
f"target strike: {target_strike}"
)

if strike < (last_price - spread):
target_strike = strike
else:
break
return target_strike

if __name__ == "__main__":
# Choose your budget and log file locations
budget = 50000
logfile = "logs/historical.log"
# Initialize all our classes
trader = Trader(logfile=logfile) # debug="debug")
broker = InteractiveBrokers(InteractiveBrokersConfig)

# ################################################################################################################
expiration = datetime.strptime("20230118", "%Y%m%d").date()
# #####################################9##########################################################################
asset = Asset(
symbol="spy",
asset_type="option", # \option`, `stock`, `future`, `forex`expiration=expiration,right="CALL", # CALL or PUT# ######################################################################################################strike=419, # 385 - 406######################################################################################################multiplier=100, # Must include for options.currency="USD")# asset = Asset(symbol="spy")`


r/pythonhelp • • Jan 07 '23

Need asistance using VarCover

0 Upvotes

https://github.com/erscott/varcover

I need to use the link above, but i cant get it to work, im a complete nooby... help please?

(Had trouble setting the path for the VCF argument also cant install Tabix and bgzip)

I need sample ID + results for the following:

rs1045642

rs429358

rs7412

rs4680

rs2069514

rs762551

rs12720461

rs3745274

rs28399499

rs4244285

rs4986893

rs28399504

rs41291556

rs12248560

rs1799853

rs1057910

rs28371686

rs9332131

rs7900194

rs28371685

rs9332239

rs72558187

rs16947

rs1135840

rs35742686

rs3892097

rs5030655

rs5030867

rs5030865

rs5030656

rs1065852

rs201377835

rs5030865

rs28371706

rs59421388

rs28371725

rs55785340

rs35599367

rs28365083

rs776746

rs10264272

rs41303343

rs1800497

rs1799963

rs6025

rs1042044

rs6923761

rs2300615

rs1801133

rs1801131

rs1799971

rs5764010

rs4149056

rs763120

rs9923231

rs56107638

rs72547513

rs56337013

rs72552267

rs72558186

rs56165452

rs72558190

rs1304490498

rs5030862

rs765776661

rs72549353

rs72549354

rs4987161


r/pythonhelp • • Jan 19 '23

New to python and got a few errors in this code. Any advice would be appreciated on how to fix these errors.

0 Upvotes

import random
MAX_LINES = 3
MAX_BET = 10
MIN_BET = 1
ROWS =  3
COLS = 3
symbol_count =  {
"A": 2,
"B": 4,
"C": 6,
"D": 8
}
symbol_value =  {
"A": 5,
"B": 4,
"C": 3,
"D": 2
}
def check_winnings(columns, lines, bet, values):
winnings = 0
winning_lines={}
for line in range (lines):
symbol = columns[0][line]
for column in columns:
symbol_to_check = column[line]
if symbol != symbol_to_check:
break
else:
winnings += values[symbol] * bet
winning_lines.append(line + 1)
return winnings, winning_lines
def get_slot_machine_spin(rows, cols, symbols):
all_symbols = []
for symbol, symbol_count in symbols.items():
for _ in range(symbol_count):
all_symbols.append(symbol)
columns = [[], [], []]
for col in range(cols):
column = []
current_symbols = all_symbols[:]
for _ in range(rows):
value= random.choice(current_symbols)
current_symbols.remove(value)
column.append(value)
columns.append(column)
return columns
def print_slot_machine(columns):
for row in range(len(columns[0])):
for i, column in enumerate(columns):
if i != len(columns) - 1:
print(column[row], end=" | ")
else:
print(column[row], end="")
print()

def deposit():
while True:
amount = input ("What would you like to deposit? $")
if amount.isdigit():
amount = int(amount)
if amount > 0:
break
else:
print("Amount must be greater than zero.")
else:
print("Please enter a number.")
return amount

def get_number_of_lines():
while True:
lines = input (
"Enter number of lines to bet on (1-" +str(MAX_LINES) + ")? ")
if lines.isdigit():
lines = int(lines)
if 1 <= lines <= MAX_LINES:
break
if lines < 1:
print("Amount must be greater than zero.")
else:
print("Lines must be less than three.")
else:
print("Please enter a number.")
return lines

def get_bet():
while True:
amount = input ("What would you like to bet on each line? $")
if amount.isdigit():
amount = int(amount)
if MIN_BET <= amount <= MAX_BET:
break
else:
print(f"Amount must be between ${MIN_BET} - {MAX_BET}.")
else:
print("Please enter a number.")
return amount
def spin(balance):
lines = get_number_of_lines
while True:
bet = get_bet()
total_bet = bet * lines
if total_bet > balance:
print(f"You do not have enough to bet that amount, your current balance is: ${balance}")
else:
break
print(
f"You are betting ${bet} on {lines} lines. Total bet is equal to: ${total_bet}")
slots = get_slot_machine_spin(ROWS, COLS, symbol_count)
print_slot_machine(slots)
winnings, winning_lines = check_winnings(slots, lines, bet, symbol_value)
print(f"You won {winnings}.")
print(f"You won on lines:", *winning_lines)
return winnings  - total_bet

def main():
balance = deposit()
while True:
print(f"Current balance is ${balance}")
answer = input("Press enter to play (q to quit).")
if answer == "q":
break
balance += spin(balance)
print(f"You left with ${balance}.")
main()

errors:

File "c:\Users\shuai\Documents\Coding\Slot Machine\main.py", line 149, in <module>

main()

File "c:\Users\shuai\Documents\Coding\Slot Machine\main.py", line 145, in main

balance += spin(balance)

File "c:\Users\shuai\Documents\Coding\Slot Machine\main.py", line 120, in spin

total_bet = bet * lines

TypeError: unsupported operand type(s) for *: 'int' and 'function'


r/pythonhelp • • Jan 03 '23

INACTIVE making an instagram bot but the code isnt running because of code is unreachable

0 Upvotes

okay. i want to auto login into accounts from accounts.json file that i have. then i want to send messages to usernames i have from usernames.txt file. then whenever i encounter "Timed out. Element not found with XPATH : //textarea[@placeholder]" in the terminal, i want it to log out of that existing account, log in to the next account in the accounts.json file and repeat the process.

but everytime i put

insta = InstaDM (username=account["username"], password=account["password"], headless=False)

in, it makes all of the code unreachable underneath it.

please help.

heres the code:

import json
import random
from src.instadm import InstaDM
from selenium.common.exceptions import NoSuchElementException
f = open('infos/accounts.json',)
accounts = json.load(f)
with open('infos/usernames.txt', 'r') as f:
usernames = [line.strip() for line in f]
with open('infos/messages.txt', 'r') as f:
messages = [line.strip() for line in f]

while True:
if not usernames:
print('Finished usernames.')
break

dm_num = int(input('How many DM you want to send in each account: '))

for account in accounts:
if not usernames:
break
# Auto login
insta = InstaDM (username=account["username"], password=account["password"], headless=False)

for i in range(dm_num):
username = usernames.pop()
# Send message
try:
success = insta.sendMessage(user=username, message=random.choice(messages))
if not success:
insta.teardown()
continue
except NoSuchElementException:
# User not found - move on to the next user
continue
except Exception as e:
if "Timed out. Element not found with XPATH : //textarea[@placeholder]" in str(e):
insta.teardown()
continue
# Other error occurred - move on to the next user
# Log out
insta.teardown()


r/pythonhelp • • Jan 25 '23

shutil.copy not replacing file with new version

0 Upvotes

I've been working on a program (converted to exe) and have wanted to releases updates on it, so in the newer versions I wanted to have something like updater.exe, where the user could select the directory of their old version and it would copy the new version and replace the old one.

However when testing this I found that while the exe does copy over, it does not change the exe at all, basically if it had never copied. The time on the file will change and all, but the file will not?

I know that the problem I not the source file directory as if I hard code it to what I want it still will somehow copy the old one.

Any help is appreciated!

#simplfied sample of issue

import  os, shutil

srcDir = os.path.dirname(os.path.realpath(__file__))
destDir = "C:\\Windows" #this is just I random directory I'm using for this sample, not actually using C:\Windows

os.remove(destDir + "\\file.exe") #tried removing the original version and then copy, did not work

shutil.copy(srcDir + '\\file.exe', destDir + "\\file.exe") #then using shutil.copy, i tired to copy the exe to the destination folder

r/pythonhelp • • Jan 26 '23

block of code reading imported .txt file for snowboarding program

0 Upvotes

beginner good with theory, extremely bad with practice.

I imported the following .txt file made up by my categories + the user input after the ": * + space*" in the code:

gender: f

bootsize: 38

brand: Burton

experience_level: beginner

riding_style: allmountain

height: 165

for category "riding_style" I would like the user to be able to give more than 1 answer, like "freestyle park" because with more than one answer the suggested snowboard profile will be different.

I am stuck because this block of code only gets the 1st word of the user input as a dictionary value because we wrote [1]

from typing import Dict, Any #review


def read_input():
    name = "input.txt"
    file = open(name, 'r')
    text_lines = file.readlines()
    for line in text_lines:
        word_list = line.split()
        key = word_list[0]
        value = word_list[1]
        dictionary_input = {key: value}
        print(dictionary_input[key])
    file.close()

    return dictionary_input

I thought maybe I could write a special case in the for loop that for that specific riding_style line would take more than just 1 word after the first one and create a list with them and put the list as a value in the dictionary, but have no idea how. I looked online but I could find no answers.

Plus I am not sure how it would work and what if the user writes a comma or "and" between the words like "park and freestyle" or "park, freestyle" D:

Does anyone know a method or has tips? I am really quite desperate :/

LG


r/pythonhelp • • Oct 23 '20

python help

0 Upvotes

I am trying to assign auto generated players I have coded to teams on python

here is wht I have coded so far

import random

offence_score = random.randint(50,99)-20

defence_score = offence_score - 10

overall = offence_score + defence_score

first_names =("bill", "lebron", "lucas", "luis","tommy", "jack", "sam", "toby", "richy", "devonte", "micheal", "blake", "JJ", "steph", "kevin","liam","Elijah","Benjamin","Mason",)

second_names=("chika", "gray", "durant", "james","Jordan", "paul", "marcus", "jason","andy","Jon","Bill","Maria","john',cain","oliver","Ethan","Henry","Logan","sebastain","wyatt")

def players(list1,list2):

players= random.choice(list1)+" "+random.choice(list2)

return(players)

for i in range(1,20):

print("the player overall is:",overall,"the player is name is :",players(first_names,second_names))

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

#---------------------------------------------------------------------------------------------------

teams= ("Atlanta hawks","Golden state","orlando magic","Denvier park")


r/pythonhelp • • Oct 01 '20

For a Project

0 Upvotes

I need to learn how to do some things and im new to python so id like some help:

How do you create a txt file on a specific folder

How do you copy files between folders

how do you make a GUI canvas background be an image, like for example a 300x300 canvas filled with a png from C:\Example\Image.png

is there any way to automatically dettect the letter of a removable flash drive? like for example in pcs with only the C drive it will be the D drive but for example my pc has 3 drives so the flash drive is the F drive, or can i just use the name of the usb drive in the path?

How do i make a text entry box with a title above it and after i write on it, the text written gets coppied to a txt file

And, although i know how to start an app from python idk how to start it minimized and i wonder if there is anyway to do that

I have searched all of this in google but i was wondering if who is answering me this could give me a more direct and compact answer, thanks in advance


r/pythonhelp • • Nov 06 '20

anyone tryna help me out, this stuff is tough

0 Upvotes

Objectives

In this program you will once again be developing a solution to solve a described problem. Many of the skills you called upon to finish previous work will be needed in addition to new skills such as

  • string manipulation

  • list structures and related commands

  • string formatting

  • string methods

Project Overview

This project will be an exercise to develop a similar but scaled-back solution as some of those mentioned in Historical Background above. You will be preparing code to process transactions that customers will be transmitting to The OneOh2 Company.

Information to be Provided

The OneOh2 company maintains a lot of information regarding their business. In this project, we will only be concerned about customer information and product information. This information will be provided to you in predefined lists that will be initialized as statements in the provided code for this program.

The following information will be provided for use in your program:

  • Customer Information:

    • Customer_Number

    • Customer_Name

    • Customer_Balance

    • Customer_Password

  • Product Information:

    • Item_Number

    • Item_Description

    • Item_Price

Note: All of the customer information and all of the product information lists are synchronized by index. As an example, the fifth item in each of the customer information lists pertains to the same customer.

Information to be Input

Your program will process input representing transactions from customers of The OneOh2 Company. Although there are different types of transactions you will need to process, your program will only need to process one transaction at a time. Through test cases in zyBooks, your program will be provided different transactions to process each time it is run.

The following types of transactions will be provided as input to your program:

  • Name change request

  • New password request

  • Customer order

A name change request and password change request will contain a single line of data. A customer order will contain an initial line of data followed by one or two item lines.

The format of the data input for each transaction type is discussed below. Note the column numbering and legend provided.

Name change request format

1 2 3 4 5 6 7

1234567890123456789012345678901234567890123456789012345678901234567890

NC#####NNNNNNNNNNNNNNNNNNNNNNNNN

where

  • "NC" is the two-digit code for this transaction type

  • ##### represents the customer number, and

  • NNNNNNNNNNNNNNNNNNNNNNNNN is the customer's new name in firstname middle lastname format

The following example:

NC03251Jimmy James Johnson

represents a name change for customer 03251 with the new name Jimmy James Johnson

Password change request format

1 2 3 4 5 6 7

1234567890123456789012345678901234567890123456789012345678901234567890

NP#####NNNNNNNNNN where

where

  • NP indicates the transaction type

  • ##### is the customer number

  • NNNNNNNNNN is the customer's new password

The following:

NP03251A%T^&j1

represents a password change for customer 03251 and a new requested password of A%T^&j1

Item order format

A customer item order will consist of data in two or three lines. The order will have one "header" record and one or two item records. The item order header format is

1 2 3 4 5 6 7

1234567890123456789012345678901234567890123456789012345678901234567890

CO#####NMMDDYYYY

where

  • CO indicates the transaction type

  • ##### is the customer number

  • N is the number of order lines (1 or 2, depending on whether order contains 1 or 2 item orders)

  • MMDDYYYY is the order date in monthdayyear format

The item order item detail data is in the following format:

quantity^item^MMDDYYYY

where

  • quantity is the quantity being ordered

  • item is the product/item number being ordered

  • MMDDYYYY is the requested date for the order

  • ^ is the separator character between data fields

The following example:

CO03251210182020

10^A2331^10232020

100^BDLS31234134^10252020

represents a complete customer order transaction for customer 03251 with 2 order lines, an order date of 10/18/2020 and one order line for quantity 10 of product A2331 on date 10/23/2020, and a second order line for quantity 100 of product BDLS31234134 on date 10/25/2020.

Processing / Output

General

Your program should be able to process any of the three transactions each time it runs. (You need to include appropriate input operations to get data from the user, however, due to the nature of this problem, you should not include any user prompt text as part of your input.) Because we have yet to do looping, your program does not need to process more than one transaction at a time. However, your program must recognize the transaction that is being requested and process accordingly.

Before doing any transaction processing, your program should do the following error checking on the provided data:

  • testing for valid customer number (does the customer number exist on the company's customer list?)

  • is the transaction type valid? This is the only error checking you need to do -- you may assume all other data provided will be valid

If the data is invalid, you should print one or both of the following messages:

  • Customer number ###### is invalid

  • Transaction type XXX is invalid After reporting one or both of these error messages, you should not do any further processing.

If both the customer number and transaction type are valid, you should continue processing based on the transaction type as described below:

Customer Name Change

From the customer name change transaction data provided,

  • construct a revised name in the format Last Name, First Name Middle (ex: Johnson, Jimmy James)

  • update the appropriate customer name

  • print the customer_name list (entire list, not individual item)

Customer Password Change

Evaluate the new password to see if it is secure according to the following rules:

  • At least 6 characters in length (not counting spaces)

  • Having the first four characters as follows:

    • first character an upper case letter

    • second character a lower case letter

    • third character a number

    • fourth character one of the following: !@#$%^&*()

    • (you do not need to check after the fourth character)

If the new password is not secure:

  • print the following message:

    • New password not secure. Request denied.

    • (No further processing is necessary)

If the new password is secure,

  • update the password in the customer data

  • print the customer_password list (entire list, not individual item)

Customer Item Order

As described above, you will have one or two order lines in a customer order. For each order line, you need to do the following:

  • look up the item number in the company product data (no "not found" error checking required)

  • use the price for that item to compute total cost for the item (quantity ordered x item price)

Once you have calculated the necessary information, then generate an invoice for the items. Your invoice should be in the format illustrated with the following example outputs. Note: the column numbering is to assist you with lining up output and should not be part of your actual output. Also, be sure your browser zoom is set to allow the entire window to be viewed or some text in the display may wrap.

1 2 3 4 5 6 7 8 9

1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890

Order Date: 10/21/2020

Customer: 29251 Costanza, George Louis

Ln# Item # Item Description Req Date Qty Price Total

1 BC571 Laser printer paper 11/21/2020 125 20.17 $ 2521.25

Total 2521.25

1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890

1 2 3 4 5 6 7 8 9

1 2 3 4 5 6 7 8 9

1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890

Order Date: 10/21/2020

Customer: 29251 Costanza, George Louis

Ln# Item # Item Description Req Date Qty Price Total

1 LO917 Pencils 11/21/2020 125 2.83 $ 353.75

2 IL993 Spiral notebooks 11/25/2020 235 23.08 $ 5423.80

Total 5777.55

1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890

1 2 3 4 5 6 7 8 9


r/pythonhelp • • Oct 18 '20

Need hep :(

0 Upvotes

Hi guys,

I'm new in the coding scene and I took a complementary class at my CEGEP because it looks fun. However the course is so hard and he want us to do a project a week without teaching us anything. We have to teach ourself everythings. Moreover, we use sage phyton not pure python so it's harder to find things online... So I'm beggeing your help on one of the question of the project that is:

Sierpinski triangle: The Sierpinski triangle is formed from a black equilateral triangle, by erasing an ”upside-down” triangle in the middle, and then by repeating this process to each remaining black triangle.

(a) Write a function white_triangles(), which takes as input a list of three points (tuples) [A,B,C], and an integer current_iter, and which returns a graphics object S which will contain many white triangles (so it will only be visible if we show it on top of a black background later). Hint: Create an empty graphics object at the beginning of the function with S=Graphics()). If current_iter is equal to 0, the function should stop and return the empty graphics object S. Otherwise, it should do the following: • Calculate the coordinates of the midpoints of all three sides (call them M1, M2, and M3).

• Add a white ”middle” triangle to S, which connects the three midpoints. Hint: Use the command polygon2d([M1,M2,M3], color=’white’, fill=True).

• If current_iter==1, stop here. Otherwise, ”deal” with each of the surrounding small triangles: For each of the three ”small” triangles surrounding the white triangle, assuming that its vertices are P1, P2 and P3, add to S the output of white_triangles([P1,P2,P3],current_iter-1): i.e. the function should recursively call ”itself” (but with the iteration counter decreased by 1!), to deal with each of the smaller triangles. Note that for example for the lower left triangle, its vertices will be A, M1, and M3 (assuming you labelled the bottom left vertex A and then went counter-clockwise.)

(b) Write a function sierpinski(), which takes as input a list L of three points (tuples) and an integer maxiter, and which creates the plot of a black filled triangle, and adds to it the output of white_triangles(L,maxiter).

(c) Show the output of sierpinski([(0,0),(1,0),(1/2, sqrt(2)/2)],7) (without axes, but with 1-to-1 aspect ratio).

(d) Show the output of sierpinski(regpolygon(3),7) (without axes, but with 1-to-1 aspect ratio).

I reaaly tried har but only came up with that

def white_triangle(points, current_iter):

S=Graphics()

if current_iter == 0:

return S

elif current_iter == 1:

return S

else:

AB= vector(points[0])

BC= vector(points[1])

AC= vector(points[3])

M1= (AB[0] / 2, AB[1] / 2)

M2= (BC[0] / 2, BC[1] / 2)

M3= (AC[0] / 2, AC[1] / 2)

polygon2d([M1,M2,M3], color="white", fill=True)

That probably sucks but that the best that I got...