r/pythonhelp • u/JpBarnrad • Jun 27 '24
Please assist me with my problem.
code want a file that does not exist and every time is another file
r/pythonhelp • u/JpBarnrad • Jun 27 '24
code want a file that does not exist and every time is another file
r/pythonhelp • u/MaleficentTurn558 • Jun 26 '24
Give me 10 python coding question which gemin AI can't solve or it's response is wrong
r/pythonhelp • u/Faizan_shafi10 • Jun 26 '24
Hi
I have started working on Python 6 months ago. I am working on a project where I got 40000 DICOM files from different clinics in Germany. I have sorted them using the metadata inside the dicom files. and converted them in to different formats like nifti, tiff etc.
Now my next task was to create a nodes of different functions inside my main script. My main script has few functions like
a- for reading Dicom files.
b- for sorting dicom files
c- for convert dicom files to different formats. etc
Now i want to convert each function in to a executable command and convert it into node. Then I can import that node in to my workflow editor and create a workflow. I hope it made sense.
workflow-nodes is a collection of various tools written in Python 3, which are also usable inside a workflow as nodes. Each node is an executable command line tool providing the --xmlhelp interface, which can be used to obtain a machine readable representation of any command line tool and its parameters (see also xmlhelpy). There are nodes for many different tasks, including data conversion, transport and visualization tools.
For installation and usage instructions, please see the documentation:
I dont want to be spoon fed but please If somone has worked on this before can you please make a simple function which takes two numbers and adds them. Make it a command using xmlhelpy library and make it a node.
I just want to understand the logic behind it and then I will implement in for my own script.
I will wait for some helpful replies. Thank you
r/pythonhelp • u/JpBarnrad • Jun 26 '24
So the moment I run my code it gives me a black box which is fine but then it closes after that and i can not do anything.
Tracebook (most recent call last):
File “bubbles.py”, line 13, in <module>
File “<frozen importlib._bootstrap>”, line 1360, in _find_and_load
File “<frozen importlib._bootstrap>”, line 1331, in _fina_and_load_unlock
File “<frozen importlib._bootstrap>”, line 935, in _load_unlock
File “Pyinstaller\loader\pyimod02_importers.py”, line 419, in exec_module
file “pvporcupine__init__.py”, line 12 in <module>
File “<frozen importlib._bootstrap>”, line 1360, in _find_and_load
File “<frozen importlib._bootstrap>”, line 1331, in _fina_and_load_unlock
File “<frozen importlib._bootstrap>”, line 935, in _load_unlock
File “pyinstaller\loader\pyimod02_importers.py”, line 419, in exec_module
File “pvporcupine\factory.py”, line 17, in <module>
File pvporcupine_until.py”, line 148, in pv_keyword_paths
FilenotFounError: [WinError 3] The system cannot find the path specified: (my path)
[15164] Failed to execute script ‘bubbles’ due to unhandled exception!
r/pythonhelp • u/Public_Ad_4430 • Jun 25 '24
hey guys! I really need help right now, I'm in the processing of editing a video and I want to add deepface recognition. Basically, the code to read faces that appear in a video and add a squear around the face, with details as well. I tried watching videos but i keep having problems with deepface downloading (in PyCharm) ect. Any advise would be helpful. Thank you!!
r/pythonhelp • u/noisycartographer93 • Jun 21 '24
I'm trying to write a script to read the federal register column in the table at this site: ECOS: USFWS Threatened & Endangered Species Active Critical Habitat Report
I've got this so far, but I can't see an obvious way or guide to read the table. Coud anyone point me in the right direction?
from urllib.request import urlopen
usfws_site = r"https://ecos.fws.gov/ecp/report/table/critical-habitat.html"
page = urlopen(usfws_site)
html_bytes = page.read()
html = html_bytes.decode("utf-8")
r/pythonhelp • u/QuietRing5299 • Jun 20 '24
If you've been using Python for a while, you might have missed a significant recent addition to the language: the "Match Case" statement, which serves as Python's answer to the much-anticipated "Switch Statement." This feature, introduced in Python 3.10, has sparked considerable discussion among developers, especially those familiar with similar constructs in other programming languages.
The "Match" statement enables you to compare a value against various patterns and execute the corresponding block of code for the first matching pattern. This improvement eliminates the need for cumbersome nested if-else statements, greatly enhancing the readability of your code. I highly recommend getting acquainted with this new feature, as it is expected to become more prevalent in Python codebases.
For a detailed explanation of how to use the "Match Case" statement, along with other Python tips, check out my YouTube video. Don’t forget to like, comment, and subscribe to support the channel. I hope you find it informative!
r/pythonhelp • u/3_Thumbs_Up • Jun 20 '24
I'm trying to get the following python program working:
https://github.com/owdevel/ytdl-nfo
I'm running the latest version of Arch linux and on their github page there's someone with the exact same issue as me. The problem seems to be related to my python environment. I believe I need to run the program in a python 3.8 environment with the package setuptools installed. However, I can't get it working.
Here's a summary of what I've done.
I've installed python (3.12), python-pip, python-pipx and pyenv through my distros package manager (Arch).
I've downloaded python 3.8 through pyenv and set it to global:
[arch@archlinux ~]$ pyenv version
3.8.19 (set by /home/arch/.pyenv/version)
[arch@archlinux ~]$ python --version
Python 3.8.19I've installed setuptools through pip:
[arch@archlinux ~]$ pip list
Package Version
------------------ --------
argcomplete 3.4.0
Brotli 1.1.0
certifi 2024.6.2
charset-normalizer 3.3.2
click 8.1.7
idna 3.7
mutagen 1.47.0
packaging 24.1
pip 23.0.1
platformdirs 4.2.2
pycryptodomex 3.20.0
PyYAML 6.0.1
requests 2.32.3
setuptools 56.0.0
tomli 2.0.1
urllib3 2.2.1
userpath 1.9.2
websockets 12.0I've installed ytdl-nfo through the following command:
pipx install ytdl-nfo --python python3.8But when I try to run the program it gives me the following error message. The module pkg_resources is supposedly in the setuptools package.
Traceback (most recent call last):
File "/home/arch/.local/bin/ytdl-nfo", line 5, in <module>
from ytdl_nfo import main
File "/home/arch/.local/share/pipx/venvs/ytdl-nfo/lib/python3.8/site-packages/ytdl_nfo/__init__.py", line 4, in <module>
from .Ytdl_nfo import Ytdl_nfo
File "/home/arch/.local/share/pipx/venvs/ytdl-nfo/lib/python3.8/site-packages/ytdl_nfo/Ytdl_nfo.py", line 3, in <module>
from .nfo import get_config
File "/home/arch/.local/share/pipx/venvs/ytdl-nfo/lib/python3.8/site-packages/ytdl_nfo/nfo.py", line 5, in <module>
import pkg_resources
ModuleNotFoundError: No module named 'pkg_resourcesr/pythonhelp • u/Just-Ad4940 • Jun 19 '24
class Room:
def __init__(self, name, description=""):
= name
self.description = description
self.items = []
self.exits = {}
def add_exit(self, direction, room):
self.exits[direction] = room
def add_item(self, item):
self.items.append(item)
class Item:
def __init__(self, name, description=""):
= name
self.description = description
def setup_rooms():
rooms = {
'Bedroom': {'south': 'Kitchen', 'east': 'Bathroom'},
'Kitchen': {'north': 'Bedroom', 'east': 'Living Room', 'south': 'Laundry Room', 'item': 'Sack of feathers'},
'Bathroom': {'west': 'Bedroom', 'south': 'Living Room', 'item': 'Master Key'},
'Closet': {'south': 'Master Bedroom', 'west': 'Bathroom'},
'Living Room': {'north': 'Bathroom', 'east': 'Master Bedroom', 'west': 'Kitchen', 'item': 'Bucket'},
'Laundry Room': {'north': 'Kitchen', 'east': 'Garage', 'item': 'Washing Machine'},
'Master Bedroom': {'north': 'Closet', 'west': 'Living Room'},
'Garage': {'west': 'Laundry Room', 'north': 'Living Room', 'item': 'Rope'},
}
room_objects = {}
for room_name in rooms:
room_objects[room_name] = Room(room_name, description=f"This is the {room_name}.")
for room_name, details in rooms.items():
current_room = room_objects[room_name]
for direction, connected_room in details.items():
if direction != 'item':
current_room.add_exit(direction.lower(), room_objects[connected_room])
else:
item = Item(details['item'])
current_room.add_item(item)
return room_objects
def show_instructions():
print("Revenge on Step Mom")
print("Collect all the items to progress through the locked Master Bedroom")
print("Move Commands: South, North, East, West")
print("Add to Inventory: get 'item name'")
def show_status(current_room, inventory):
print(f"You are in the {current_room.name}")
print(f"Inventory: {inventory}")
if current_room.items:
for item in current_room.items:
print(f"- {item.name}")
print("-------------------")
def check_win_condition(current_room, inventory):
if current_room.name == 'Master Bedroom' and 'Master Key' in inventory:
print("Congratulations! You've unlocked the Master Bedroom!")
print("You tie Sandra up, pour hot tar and feathers all over her! Her screams are like music to your ears.")
print("You have earned that Capri Sun.")
return True
return False
def main():
show_instructions()
rooms = setup_rooms()
current_room = rooms['Bedroom']
inventory = []
while True:
show_status(current_room, inventory)
command = input("Enter a command: ").lower().strip()
if command in ['north', 'south', 'east', 'west']:
if command in current_room.exits:
current_room = current_room.exits[command]
else:
print("I can't go that way.")
elif command.startswith("get "):
item_name = command[4:].strip()
item_found = False
for item in current_room.items:
if item.name.lower() == item_name:
inventory.append(item.name)
current_room.items.remove(item)
item_found = True
print(f"{item_name} added to inventory.")
break
if not item_found:
print(f"No {item_name} found here.")
elif command == 'exit':
print("Goodbye!")
break
else:
print("Invalid direction")
if __name__ == "__main__":
main()self.nameself.name
#Ouput
You are in the Bedroom
Enter a command (North, South, East, West, or exit): east
You can't go that way!
You are in the Bedroom
Enter a command (North, South, East, West, or exit): EastA simple text based game for a class. There may be other issues but I can't even leave the bedroom to continue to debug lol
r/pythonhelp • u/thisnigerianmomma • Jun 15 '24
can you guys help me figure out which lines have errors?
names = \[\]4 names.append (input(“Enter your name with a capital letter.”))
5. print(names)
6.
7 number = int(input(“How many names need to be entered? ”))
8. names = make_list(number)
9. for name in names:
10. if name [1] ==“A”:
11. print(“Name”, name, “starts with A”)
r/pythonhelp • u/Lazy_Sky_8967 • Jun 14 '24
ok so im trying to install stable baselines 3 everthing goes fine when i enter: !pip install stable-baselines3[extra] everything is able to install just fine exept "wheel" i get the error:
error: subprocess-exited-with-error
Getting requirements to build wheel did not run successfully. exit code: 1
[1 lines of output] error in gym setup command: 'extras_require' must be a dictionary whose values are strings or lists of strings containing valid project/version requirement specifiers. [end of output]
note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error Getting requirements to build wheel did not run successfully. exit code: 1 See above for output. note: This error originates from a subprocess, and is likely not a problem with pip.
Please help
r/pythonhelp • u/PK_Fund • Jun 14 '24
Anyone knows how to bubble sort the odds of this array and do the same thing to the evens but like put in a new array?? (new arrays should be 1D) No need for codes just the algorithms.
array = [[128, 2], [32, 4], [75, 6]]
r/pythonhelp • u/This-Breakfast6206 • Jun 13 '24
Hi everyone,
I'm looking for a tool or formula in Python that can recognize a graph from an image and convert it into corresponding Python code with the exact values. For example, if I have an image of a graph, I would like to get the Python code that reproduces the graph, including all the data points and details.
Has anyone come across a library or a method that can achieve this? Any guidance or suggestions would be greatly appreciated!
Thanks in advance!
r/pythonhelp • u/SCM456 • Jun 12 '24
I'm an amateur with matplotlib who is writing a program and getting these issues, so I've written a smaller version that demonstrates the same issues with less code. I have a window with matplotlib charts integrated into a PySimpleGUI canvas, and whenever I update the charts there is an annoying white flash. I have no idea how to prevent this, or if it is even possible to prevent it. I have looked around on google and I saw recommendations saying to use
figure_canvas_agg.draw_idle()instead of
figure_canvas_agg.draw()In the draw_figure function. However, this made no difference whatsoever when I tried it. Also, when I try to save or open the charts, it doesn't work properly with how I've coded it. I know that problems specifically with matplotlib AND pysimplegui together is a bit specific to ask help for, but I might as well post this just in case and any help would be much appreciated.
Example code:
import PySimpleGUI as sg
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
sg.theme("DarkGrey11")
#Value input section
frame1 = [sg.Frame("Change values to update the pie chart",(
[
[sg.Input(5, key="input1",size=(3,1),justification="center",enable_events=True)]
+[sg.Input(2, key="input2",size=(3,1),justification="center",enable_events=True)]
+[sg.Input(8, key="input3",size=(3,1),justification="center",enable_events=True)]
+[sg.Input(3, key="input4",size=(3,1),justification="center",enable_events=True)],
[sg.Button("Open charts in new window", key="opencharts", pad=20)],
[sg.Button("Save charts", key="savecharts")]
]
), border_width=1, element_justification="center")
]
#Pie chart display section
frame2 = [sg.Frame("",(
[
[sg.Canvas(size=(200,500), key="graph")]
]
),size=(700,700), element_justification="center")
]
layout = [frame1 + frame2]
window = sg.Window("Example of the issue",
layout,
size=("1000","700"),
finalize=True,
element_justification="center")
#Setting up GUI matplotlib integration
matplotlib.use("TkAgg")
def draw_figure(canvas, figure, loc=(0, 0)):
figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
figure_canvas_agg.draw()
figure_canvas_agg.get_tk_widget().pack(side="top", fill="both", expand=True)
return figure_canvas_agg
def delete_fig_agg(fig_agg):
fig_agg.get_tk_widget().forget()
plt.close("all")
#Setting chart colors to match the window's theme
textcolour = (0.8,0.8,0.8)
matplotlib.rcParams['text.color'] = textcolour
matplotlib.rcParams['axes.labelcolor'] = textcolour
matplotlib.rcParams['xtick.color'] = textcolour
matplotlib.rcParams['ytick.color'] = textcolour
# Main loop
while True:
#Waiting for input
event, values = window.read()
#Creating a list from the input values, 'try' prevents non-numerical input error
try:
graph_values = [ float(values["input1"]), float(values["input2"]), float(values["input3"]), float(values["input4"]) ]
except:
continue
#Creating the figure
fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(8,8))
ax1.pie(x=graph_values, labels=["Input 1", "Input 2", "Input 3", "Input 4"])
ax2.plot(graph_values, marker='.')
#Setting the figure and line graph background to match the GUI
fig.patch.set_facecolor( (0.11,0.12,0.137) )
ax2.patch.set_facecolor( (0.11,0.12,0.137) )
#Delete the figure (the try/except prevents an error if there is no figure)
try:
delete_fig_agg(fig_canvas_agg)
except:
pass
#Draw the charts onscreen
fig_canvas_agg = draw_figure(window["graph"].TKCanvas, fig)
#Show charts in new window
if event == "opencharts":
plt.gcf()
plt.show()
#Save the charts
if event == "savecharts":
plt.savefig("graphs_example.png") #Saves in same location as this .py file r/pythonhelp • u/mach0-nach0 • Jun 12 '24
Amateur Python tinkerer here expanding my knowledge and building my skills.
Essentially, I'm creating a small procedural-generated text-based game. The only 'graphical representation' is a small ASCII map that will mark the location of the player and surrounding towns, land-features, etc.
I'm having issues with my town generation as I would like there to be 'padding' between my towns to keep them from stacking on the same row/column in my 2D matrix. Each town generates a random X and Y value within a While Loop and 'scan' nearby locations within a certain range (padding) to check if a town_symbol is already there. If so, it passes and assigns new random values to X and Y and reruns the 'check'. Else, it inserts the town_symbol and breaks from the while loop, repeating for each town.
I can't seem to get towns to NOT stack on either the X or Y axis. Help is greatly appreciated!
If further info is needed I'm happy to oblige.
Any and all feedback on code quality is HIGHLY appreciated as I'm considering a career change into Python development in the future. Thanks!!
Code:
r/pythonhelp • • Jun 11 '24
I created productivity reports for several departments in a hospital. I utilize a dashboard and do it manually once a month for like 30 employees. I am now beong asked to do it for close to 100 and desperately need to automate this process. I can create and export 3 or 4 excel reports that would contain this assortment of data in an unsummarized form. Pretty much the raw data. What would be my best approach for creating or updating these 100+ seperate employee excel productivity reports? Like am I just creating using my already formatted files and coding it to fill specific cells correlating with the month or metric or are there better ways to do this?
r/pythonhelp • u/AdvitaOne • Jun 10 '24
Hi everyone,
I'm working on a Python script designed to monitor and correct the access control configuration for Apache and LiteSpeed web servers. The script detects changes in configuration files on Plesk Panel Server and updates /var/www/vhosts/system/{domain}/conf/vhost_ssl.conf accordingly after performing necessary checks. However, it seems that the script fails to proceed with writing and updating the vhost_ssl.conf file upon detecting changes.
Here is a brief overview of my script's functionality and logic:
Initialization and Configuration:
Web Server Detection:
ps and netstat commands.File Monitoring and Handling:
watchdog to monitor changes in the specified configuration directory.vhost_ssl.conf file.Functions:
compute_file_hash(filepath): Computes the MD5 hash of a file to detect changes.is_acl_location_block(lines): Identifies if a block of lines contains ACL directives.contains_ip_addresses(lines): Checks if a block of lines contains IP addresses.add_modification_comments(lines, indentation): Adds comments indicating modifications to a block of lines.convert_to_modern_syntax(lines, indentation): Converts ACL directives to a modern syntax.create_or_update_vhost_ssl_config(vhost_ssl_path, ipv4, ipv6, location_block): Creates or updates the vhost_ssl.conf file with modified ACL directives.The Issue:
The script doesn't proceed to handle the logic for writing and updating /var/www/vhosts/system/{domain}/conf/vhost_ssl.conf after detecting file changes or performing the necessary checks. Specifically, the correct_syntax(config_path, domain_to_paths) function is not fully executing its intended logic.
Here's the relevant part of my script:
# Main monitoring logic
=
=
# Initial check for existing files
# Reset force_overwrite_once after the initial run
global
= False
What I've Tried:
Request for Help:
vhost_ssl.conf file after detecting changes?Here is the full script for reference: [Paste full script code here]
Thanks in advance for your help!
#!/usr/bin/env python3
# Initialize debugpy
# Configurations
=
= 50 * 1024 * 1024 # 50MB
=
# Command-line arguments
=
=
# Set up logging
=
=
=
=
=
=
= None
=
= ==
global
= 5 # Retry interval in seconds
return
return
return
return
=
=
=
=
=
in or :
=
== :
=
= :
return
=
return
=
return
=
=
return
=
=
continue
in :
=
return
= None
= None
= None
=
=
=
=
=
return , ,
=
# debugpy.breakpoint() # Break here to inspect
=
=
= f
= f
=
return
# def create_or_update_vhost_ssl_config(vhost_ssl_path, ipv4, ipv6, location_block):
# logger.debug(f"Writing to vhost_ssl_path: {vhost_ssl_path} with location_block: {location_block}")
# if not os.path.exists(vhost_ssl_path) or args.force_overwrite == 'always' or force_overwrite_once:
# os.makedirs(os.path.dirname(vhost_ssl_path), exist_ok=True)
# with open(vhost_ssl_path, 'w') as f:
# f.write(f'<IfModule mod_ssl.c>\n <VirtualHost {ipv4}:443>\n')
# f.write(''.join(location_block))
# f.write(f' </VirtualHost>\n <VirtualHost [{ipv6}]:443>\n')
# f.write(''.join(location_block))
# f.write(' </VirtualHost>\n</IfModule>\n')
# logger.info(f'{"Overwritten" if args.force_overwrite else "Created new"} vhost_ssl.conf at {vhost_ssl_path}')
# else:
# with open(vhost_ssl_path, 'r') as file:
# existing_lines = file.readlines()
# # Update existing vhost_ssl.conf with modified ACL lines
# with open(vhost_ssl_path, 'w') as file:
# in_vhost_block = False
# updated_lines = []
# for line in existing_lines:
# stripped_line = line.strip()
# if f'<VirtualHost {ipv4}:443>' in stripped_line or f'<VirtualHost [{ipv6}]:443>' in stripped_line:
# in_vhost_block = True
# updated_lines.append(line)
# updated_lines.extend(location_block)
# elif '</VirtualHost>' in stripped_line and in_vhost_block:
# in_vhost_block = False
# updated_lines.append(line)
# elif not in_vhost_block:
# updated_lines.append(line)
# file.writelines(updated_lines)
# logger.info(f'Updated existing vhost_ssl.conf at {vhost_ssl_path}')
# # Record the modification for counting
# domain = vhost_ssl_path.split('/')[5]
# if domain not in modification_stats:
# modification_stats[domain] = 0
# modification_stats[domain] += 1
=
return
return
=
return
, , =
return
return
=
= False
=
= None
= 0
=
=
= True
=
=
in and :
= False
=
+= 1
=
=
= None
:
return
=
return
, =
# Ensure location_block is not empty
= f
= f
# Atomic write
# Ensure only location_block is used
# Test the configuration
=
=
= + 1
return
=
# Update existing vhost_ssl.conf with modified ACL lines
= False
=
=
= True
in and :
= False
not :
# Record the modification for counting
=
= 0
+= 1
# debugpy.breakpoint() # Break here to inspect
=
# Break here to inspect
=
return
=
return
return
# Break here to inspect
=
=
# Initial check for existing files
# Reset force_overwrite_once after the initial run
global
= False
r/pythonhelp • • Jun 10 '24
Trying to follow this guide for flask: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
I am on chapter 1, for some reason the code he supplied does not seem to work, it gives me an error that app was not found. My file structure looks ok?
r/pythonhelp • u/Ill-Construction5495 • Jun 09 '24
Hi! Currently the programming course I'm in is doing projects with Pandas, where we have to pick a hypothesis regarding a data base chosen by us and then present it as if it was a pitch to a company. (in my case, an ad (or a warning against, if my hypothesis will be wrong!) for preparation courses for school exams)
Except, I'm going on a week trip and will miss the class where we'd clear up last mistakes and finish our projects, so I thought I'd finish it today and make a small presentation about it ahead of time as to not waste time presenting it an entire week after, except.... a str/int type error appeared and I am now lost on how I could fix it.
Any help would be much appreciated. :)
(Note: I've tried replacing all instances of 70 as "70" but it would bring up problems in lines like.. 740? or 330? and alike, which made me even more confused, which is why I kept the 70s without the ""s. If I should bring them back, do tell.)
(Note 2: The space before .csv is intentional because that's how the file is actually named there.)
import pandas as pd
df = pd.read_csv('StudentsPerformance .csv')
no_prep = df[df['test preparation course'] == 'none']
prep = df[df['test preparation course'] == 'completed']
results1 = df[no_prep & df[df['math score' >= 70]] & df[df['reading score' >= 70]] & df[df['writing score' >= 70]]]
results2 = df[prep & df[df['math score' >= 70]] & df[df['reading score' >= 70]] & df[df['writing score' >= 70]]]
no_prep_results = df.count(results1)
prep_results = df.count(results2)
def hypotester():
if prep_results > no_prep_results:
print('hipoteza dobra / hypothesis correct! :)')
else:
print('hipoteza zła / incorrect hypothesis :(')
hypotester()r/pythonhelp • u/solastrify • Jun 09 '24
def play():
global selection1, selection2
gameLoop = True
while gameLoop:
SCREEN.blit(BG, BGrect)
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameLoop = False
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if PLAY_BACK.checkForInput(PLAY_MOUSE_POS):
main_menu()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
for item in memPicsRect:
if item.collidepoint(event.pos):
if selection1 != None:
selection2 = memPicsRect.index(item)
hiddenImages[selection2] = True
else:
selection1 = memPicsRect.index(item)
hiddenImages[selection1] = True
for i in range(len(pictures)):
if hiddenImages[i] == True:
SCREEN.blit(memPics[i], memPicsRect[i])
else:
pygame.draw.rect(SCREEN, WHITE, (memPicsRect[i][0], memPicsRect[i][1], picSize, picSize))
pygame.display.update()
if selection1 != None and selection2 != None:
if pictures[selection1] == pictures[selection2]:
selection1, selection2 = None #THIS IS CAUSING THE ERROR
else:
pygame.time.wait(1000)
hiddenImages[selection1] = False
hiddenImages[selection2] = False
selection1, selection2 = None, NoneHello! I keep getting TypeError: cannot unpack non-iterable NoneType object at the section that i've marked with #. Above all of this code (I just haven't put it in this post), I've set both selection 1 and 2 to = None. I'm very new to python and don't really know what I should change the None to in order to get my results, or if I can still use it and something else needs to be change. I do have to keep the def function though. I'm trying to make a memory tile game. If you're willing to help and need more information, please let me know because that would mean a lot to me. Thank you!
r/pythonhelp • u/BasketballShoes85 • Jun 09 '24
I am taking a class right now and they are asking to parse data but I feel like they jumped me into this and I missed a way to use regex to break it down. Might just be that I don't have faith in my approach. Can someone explain how to handle this problem and how regex (or whatever works) is used? I actually want to learn this and not get some AI quick fix, so I am sorry if it is some basic level question. Thanks!
Create a second Python program to parse the following unstructured data:
Center/Daycare
825 23rd Street South
Arlington, VA 22202
703-979-BABY (2229)
22.
Maria Teresa Desaba, Owner/Director; Tony Saba, Org. Director.
Web site: www.mariateresasbabies.com
Serving children 6 wks to 5yrs full-time.
National Science Foundation Child Development Center
23.
4201 Wilson Blvd., Suite 180 22203
703-292-4794
Web site: www.brighthorizons.com 112 children, ages 6 wks–5 yrs.
7:00 a.m. – 6:00 p.m. Summer Camp for children 5–9 years.
r/pythonhelp • u/oakdiamondYT • Jun 08 '24
Does anyone know python libraries that simulate mouse movement and dont make my player camera forcefully look down and rotate counterclockwise in every game i try? I already tried using pyautogui and pynput with the same result.
r/pythonhelp • u/Ok-Track2269 • Jun 08 '24
Sorry im new to reddit and python. im trying to make a simple thing that will track player stats in a MLB/NBA game and present it to me as they get updated kinda like a parlay. I can't seem to get it to actually show when a player has a hit or any stat. it just says they have 0 even if that have one.
r/pythonhelp • u/akaBrotherNature • Jun 07 '24
Hi everyone.
This feels like it should be super simple, but I just cannot figure it out.
I've downloaded the ebay openapi spec for their fulfilment api...
https://developer.ebay.com/api-docs/master/sell/fulfillment/openapi/3/sell_fulfillment_v1_oas3.json
...and I've generated the client using openapi-python-client, and imported and instantiated the client like so:
from fulfillment_api_client import AuthenticatedClient
client = AuthenticatedClient(
base_url="https://api.ebay.com", token="XXX"
)But then I get stuck.#
The openapi spec describes an endpoint path (e.g. /order/{orderId}) like so:
"paths": {
"/order/{orderId}": {
"get": {
"tags": [
"order"
],
"description": ...",
"operationId": "getOrder",
"parameters": [
{
"name": "fieldGroups",
"in": "query",
"description": ...",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "orderId",
"in": "path",
"description": "...",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Order"
}
}
}
},
"400": {
"description": "Bad Request",
"x-response-codes": {
"errors": {
"32100": {
"domain": "API_FULFILLMENT",
"category": "REQUEST",
"description": "Invalid order ID: {orderId}"
},
"32800": {
"domain": "API_FULFILLMENT",
"category": "REQUEST",
"description": "Invalid field group: {fieldGroup}"
}
}
}
},
"404": {
"description": "Not Found"
},
"500": {
"description": "Internal Server Error",
"x-response-codes": {
"errors": {
"30500": {
"domain": "API_FULFILLMENT",
"category": "APPLICATION",
"description": "System error"
}
}
}
}
},
"security": [
{
"api_auth": [
"https://api.ebay.com/oauth/api_scope/sell.fulfillment",
"https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly"
]
}
]
}
}But I have no idea how to access that using the client in python.
Can anyone help. Thank you in advance! 😊