Skip to main content

Get the Reddit app

Scan this QR code to download the app now
Or check it out in the app stores
r/learnpython icon
r/learnpython icon

r/learnpython

members
online
Rising
Open sort options
Change post view



homework assignment homework assignment

For this step, implement menu selections "b" and "d.

    1. Make a copy of step1.py to use as a starting point for this step.

  • 2. For menu selection "b",

  • Query the user for an attribute name, using the input() command.

  • Query the user for an attribute value using the input() command.

  • Store the attribute and value in the dictionary using the attribute as the item key and the value as the item value.

~NOTE:~ Since attribute values could be plain text, e.g. background-color: BLUE, ~store attribute values as strings.~

This is where Im having trouble .

I thought my code is supposed to start like this to implement selection b:

Window_Administration_Application = """
a: Enter a to exit application
b: Enter b to enter an attribute
c: Enter C to calculate and display the aspect ratio
d: Enter d to display the window attributes and values
"""
done = False

while not done:
    print(Window_Administration_Application)
    
    selection = input("Please select a menu option: ")
    if selection == "a":
        done = True
        print("Done!")
    elif selection == "b":
        print("Entering an attribute selected.")
    elif selection == "c":
        print("Calculate aspect ratio selected.")
    elif selection == "d":
        print("Display the attributes and values selected.")
    else:
        print("{} is not a valid entry Try a, b, c, or d.") 
# 
#Beginning of Section 2
#       
 selection(b) == attribute_name:

    attribut_name = input("Please enter the attribute name: ")
print(f"You entered: {attribute_name}")   

attribute_value = input("Please enter a value for the attribute name: ")
print(f"You entered: {attribute_value}")

Looking to make a system to help store gage pins at work, Please help Looking to make a system to help store gage pins at work, Please help

Looking to make a storage system that helps me locate what gage pins we currently have in stock. I would use a lista cabinet and store things using drawer # and have a xy grid of bins that they can be stored in. Then a person can use a 7in screen to type in the gage pin size and from there locate and remove it from the system. Same for adding pins. I'm really unsure where to start, I tried playing around with a CSV file but then I heard about SQL databases. If yall could give some help on where to start that would be wonderful.




No module named 'pytube' even though it is installed No module named 'pytube' even though it is installed

I installed pytube successfully but it is not importing, and even after it's installed i don't know where is it.. when i do pip list in my terminal (I'm working in VSCode) it shows pytube but it does not get imported, I think i also should mention that the same problem is happening for me with pygame, it is installed and in the pip list but still ModuleNotFoundError, What do i do??

I'm also sure there is no spelling mistakes


Looking for some kind of a "Python Bible" Looking for some kind of a "Python Bible"

Hello everyone, I want to improve and expand my knowledge in Python coding. Is there a kind of “Python Bible” for this purpose? Even simple keywords would be enough for me to look up and read about.

Background: First off, I’m not an IT guy. I studied finance, never had any courses in proper programming, and no one ever taught me Python coding. I first used Python for my master’s thesis, where I had to conduct a sentiment analysis. I had to teach myself, which I managed to do quite well with the help of YouTube tutorials, the very helpful people on Stack Overflow, and code templates from other developers (back then, there was no ChatGPT). But since I’m the type who prefers to learn autodidactically and learns best in the process of solving real problems, it wasn’t a big deal. Since then, I have grown to love Python and have been coding a lot as a hobby. For fun, I’ve done many projects, including:

•	Simple data encryption (AES, RSA)
•	Resource and general data management algorithms for online strategy games
•	Trading strategies
•	A lot of other stuff remotely related to data

Since the release of ChatGPT, my coding skills have improved significantly, especially since I’ve learned to ask the right questions.

What do I want to learn? Given this background, I now want to learn the basics, ideally through a book that I can work through. This includes:

•	Meaningful naming of variables, parameters, functions
•	When to use functions
•	How to write code that is easy to read, edit, and as modular as possible
•	How to properly structure things (codes, files, folder structures)
•	How to make functions modular and versatile (especially regarding parameters)
•	What to use when? (Lists, tuples, dictionaries, data frames, SQL, etc., especially for storing and handling large amounts of data)

I know I could find all this through research and ChatGPT, but I think it would be cool to have a book that guides me through it all in a structured way. It doesn’t have to be too in-depth :)

TL;DR: Looking for a book to help someone like me, a beginner/intermediate coder without an IT background, learn the basics.

Thanking you in advance!


How to dynamically add columns? (SQLAlchemy | Database | SQLite) How to dynamically add columns? (SQLAlchemy | Database | SQLite)

I'm working on a program that lets the user create their own column in a database table. The program asks the column name and the program adds it using the "ALTER" SQL command. But the problem is that the SQLAlchemy data model is already hardcoded in the source code and can't be altered to correspond to the new table. I think it could be done using raw SQL commands, but I"m not sure how to achieve what I need using the ORM.
One thing that I could think of was to create a large table with many generic columns, and assign user-defined names to these columns in a config file. But it doesn't feel like the best practice.


Can't get my loop to break. Brand Affiliate Can't get my loop to break.
import random, sys

print('ROCK, PAPER, SCISSORS')

#These variables keep track of the number of wins, losses, and ties. 
wins = 0
losses = 0
ties = 0

while True: #The main game loop.
    print('%s Wins, %s Losses, %s Ties' % (wins,losses,ties))
    while True: # The player input loop.
        print('Enter your move: (r)ock (p)aper (s)issors or (q)uit')
        playerMove = input()
        if playerMove == 'q':
            sys.exit()
        if playerMove == 'r' or playerMove == 'p' or playerMove == 's':
            break
        print('Type one of r, p , s, or q.')

#Display what the player chose:
if playerMove =='r':
    print('Rock versus...')
elif playerMove == 'p':
    print('Paper versus...')
elif playerMove == 's':
    print('Scissors versus...')

Tkinter Interface Scaling Help Tkinter Interface Scaling Help

I would appreciate any help as I have been unable to resolve this issue. I have a simple tkinter user interface that displays information. I want the display sections to expand their width with the window size. I can't get any of the output fields to scale with the window size. Can anyone see what's preventing scaling here?

import pandas as pd
import tkinter as tk
from tkinter import ttk

# Load the Excel file
excel_file_path = 'complaints_data.xlsx'
materials_df = pd.read_excel(excel_file_path, sheet_name='Materials Information')
patients_df = pd.read_excel(excel_file_path, sheet_name='Patients Information')
samples_df = pd.read_excel(excel_file_path, sheet_name='Sample Information')
query_export_df = pd.read_excel(excel_file_path, sheet_name='query_export_results')

# Strip leading/trailing spaces from column names
materials_df.columns = materials_df.columns.str.strip()
patients_df.columns = patients_df.columns.str.strip()
samples_df.columns = samples_df.columns.str.strip()
query_export_df.columns = query_export_df.columns.str.strip()

# Ensure PR ID is treated as string
materials_df['PR ID'] = materials_df['PR ID'].astype(str).str.strip()
patients_df['PR ID'] = patients_df['PR ID'].astype(str).str.strip()
samples_df['PR ID'] = samples_df['PR ID'].astype(str).str.strip()
query_export_df['PR ID'] = query_export_df['PR ID'].astype(str).str.strip()

# Merge the dataframes on PR ID and Grid Unique ID
merged_df = pd.merge(materials_df, patients_df, on=['PR ID', 'Grid Unique ID'], suffixes=('_materials', '_patients'))
merged_df = pd.merge(merged_df, samples_df, on=['PR ID', 'Grid Unique ID'], suffixes=('', '_samples'))
merged_df = pd.merge(merged_df, query_export_df, on='PR ID', suffixes=('', '_query'))

def get_complaint_info(pr_id):
    complaint_data = merged_df[merged_df['PR ID'] == pr_id]
    if complaint_data.empty:
        return f"No data found for PR ID: {pr_id}"

    sections = [
        ("MDR Ownership", [("Plant Description", "Plant Description")]),
        ("Patient Information (A)", [
            ("Age at Time of the Event", "Age at Time of the Event"),
            ("Age_Unit", "Age Unit"),
            ("Patient Date of Birth", "Patient Date of Birth"),
            ("Patient Sex", "Patient Sex"),
            ("Patient Weight", "Patient Weight"),
            ("Patient Weight Unit", "Patient Weight Unit"),
            ("Ethnicity", "Ethnicity"),
            ("Race", "Race")
        ]),
        ("Adverse Event or Prod Prob (B)", [
            ("Event Occurrence Date", "Event Occurrence Date"),
            ("Patient Impacted?", "Patient Impacted?"),
            ("Patient Impact (Desc.)", "Patient Impact (Desc.)")
        ]),
        ("Suspect Medical Device (D)", [
            ("Pro Codes", "Pro Codes"),
            ("Plant Description", "Plant Description"),
            ("Material #", "Material #"),
            ("Batch Expiration Date", "Batch Expiration Date"),
            ("Batch #", "Batch #"),
            ("Material GTIN Number", "Material GTIN Number"),
            ("Serial #", "Serial #"),
            ("Initial Reporter Occupation", "Initial Reporter Occupation")
        ]),
        ("Med Device Reprocess Info (D)", [("Sample Available", "Sample Available")]),
        ("Initial Reporter (E)", [
            ("Initial Reporter First Name", "Initial Reporter First Name"),
            ("Initial Reporter Last Name", "Initial Reporter Last Name"),
            ("Initial Reporter Phone #", "Initial Reporter Phone #"),
            ("Initial Reporter Fax #", "Initial Reporter Fax #"),
            ("Initial Reporter E-mail", "Initial Reporter E-mail"),
            ("Initial Reporter Addr 1", "Initial Reporter Addr 1"),
            ("Initial Reporter Addr 2", "Initial Reporter Addr 2"),
            ("Initial Reporter City", "Initial Reporter City"),
            ("Initial Reporter State", "Initial Reporter State"),
            ("Initial Reporter Zip", "Initial Reporter Zip"),
            ("Initial Reporter Country Code", "Initial Reporter Country Code"),
            ("Customer Name:", "Customer Name"),
            ("Initial Reporter Occupation", "Initial Reporter Occupation")
        ]),
        ("All Manufacturers (G)", [
            ("Plant Description", "Plant Description"),
            ("510k Number", "510k Number")
        ]),
        ("Device Manufacturers Only (H)", [
            ("Inv Summary Status", "Inv Summary Status"),
            ("Batch Creation Date", "Batch Creation Date"),
            ("Serial Creation Date", "Serial Creation Date"),
            ("Annex E Code & Term 1", "Annex E Code & Term 1"),
            ("Annex F Code & Term 1", "Annex F Code & Term 1"),
            ("Manually Entered Annex A Code", "Manually Entered Annex A Code")
        ])
    ]

    output = {}
    for section_title, fields in sections:
        section_info = {}
        for field_name, field_desc in fields:
            value = complaint_data[field_name].iloc[0] if field_name in complaint_data else ""
            if pd.isna(value):
                value = ""
            section_info[field_desc] = value
        output[section_title] = section_info
    
    return output

def display_complaint_info(info):
    for widget in result_frame.winfo_children():
        widget.destroy()
    
    if isinstance(info, str):
        label = tk.Label(result_frame, text=info, fg="red")
        label.grid(row=0, column=0, padx=10, pady=10, sticky="ew")
        return
    
    section_colors = ["#FFCCCC", "#FFCC99", "#FFFFCC", "#CCFFCC", "#CCCCFF", "#FFCCFF", "#CCFFFF"]

    color_index = 0
    row = 0
    for section, fields in info.items():
        section_frame = tk.Frame(result_frame, padx=10, pady=10, bg=section_colors[color_index])
        section_frame.grid(row=row, column=0, sticky="ew", padx=10, pady=5)
        section_frame.grid_columnconfigure(0, weight=1)
        section_frame.grid_columnconfigure(1, weight=1)

        section_label = tk.Label(section_frame, text=section, font=("Helvetica", 16, "bold"), bg=section_colors[color_index])
        section_label.grid(row=0, column=0, sticky="w", columnspan=2)

        field_row = 1
        for field, value in fields.items():
            field_label = tk.Label(section_frame, text=f"{field}:", anchor="w", bg=section_colors[color_index])
            field_value = tk.Entry(section_frame)
            field_value.insert(0, value)
            field_value.config(state="readonly")
            field_label.grid(row=field_row, column=0, sticky="ew", padx=(10, 5), pady=2)
            field_value.grid(row=field_row, column=1, sticky="ew", padx=5, pady=2)
            field_row += 1

        row += 1
        color_index = (color_index + 1) % len(section_colors)

def on_search_click(event=None):
    pr_id = pr_id_entry.get().strip()
    info = get_complaint_info(pr_id)
    display_complaint_info(info)

root = tk.Tk()
root.title("Complaint Information Tool")

# Create the input frame
input_frame = tk.Frame(root, padx=10, pady=10)
input_frame.pack(fill="x")

pr_id_label = tk.Label(input_frame, text="Enter PR ID:")
pr_id_label.pack(side="left")

pr_id_entry = tk.Entry(input_frame, width=30)
pr_id_entry.pack(side="left", padx=5, fill="x", expand=True)
pr_id_entry.bind("<Return>", on_search_click)

search_button = tk.Button(input_frame, text="Search", command=on_search_click)
search_button.pack(side="left", padx=5)

# Create the result frame with a scrollbar
result_canvas = tk.Canvas(root)
result_frame = tk.Frame(result_canvas)
scrollbar = ttk.Scrollbar(root, orient="vertical", command=result_canvas.yview)
result_canvas.configure(yscrollcommand=scrollbar.set)

scrollbar.pack(side="right", fill="y")
result_canvas.pack(side="left", fill="both", expand=True)
result_canvas.create_window((0, 0), window=result_frame, anchor="nw", tags="result_frame")

def on_frame_configure(event):
    result_canvas.configure(scrollregion=result_canvas.bbox("all"))

result_frame.bind("<Configure>", on_frame_configure)

# Enable scrolling with the mouse wheel or trackpad
def on_mouse_wheel(event):
    result_canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")

result_canvas.bind_all("<MouseWheel>", on_mouse_wheel)

# Make the UI scale with window size
root.grid_columnconfigure(0, weight=1)
input_frame.grid_columnconfigure(1, weight=1)
result_canvas.grid_columnconfigure(0, weight=1)
result_frame.grid_columnconfigure(0, weight=1)

root.mainloop()

"No such file or directory" What is this happening?? "No such file or directory" What is this happening??

So I desided to brush off my python knowledge now that I'm used to my new Linux daily driver. I fired up VS codium, added the python extension, typed print ("Hello") and clicked the run button. but I just got this.

/bin/python: can't open file '/home/stereo/Desktop/Programing/print (Hello).py': [Errno 2] No such file or directory

What the heck is causing this? The file is clearly there as I see it in the file explorer. And I saw 2 videos trying to solve this very error and neither of them worked.


Pandas df transformation where meta data is row 0 and headers are row 1 Pandas df transformation where meta data is row 0 and headers are row 1

I have an excel file where the date and other data is in row 0 and the actual col headers are in row 1. Is there a way to read the excel file with all the data, do transformations such as df[col a] = x and then write it back to an excel file with the meta data and headers in the same spot?

I’ve tried reading with header=1 and then inserting the meta data but it always gets stuck right under the headers


[VideoHelperSuite] - ERROR - No valid ffmpeg found [VideoHelperSuite] - ERROR - No valid ffmpeg found

I'm brand new to this world. I'm trying to learn ComfyUI on a mac computer using Terminal. I've been using this tutorial to learn a comfyUI Workflow, and after it gets done with KSampler it gave me a red text error within ComfyUI saying:

Error occurred when executing VHS_VideoCombine: ffmpeg is required for video outputs and could not be found.
In order to use video outputs, you must either:
- Install imageio-ffmpeg with pip,
- Place a ffmpeg executable in /Users/rachel/ComfyUI, or
- Install ffmpeg and add it to the system path.

https://imgur.com/a/StVYDgy

When I try booting up ComfyUI in terminal it warns me:

[VideoHelperSuite] - WARNING - Failed to import imageio_ffmpeg

[VideoHelperSuite] - ERROR - No valid ffmpeg found.

on this github page, i herad those guys mention they had success by reinstalling the extension. I tried to go to this website and I performed: git clone https://git.ffmpeg.org/ffmpeg.git ffmpeg (within terminal and even though terminal said the install worked), I'm still getting that warning/error about VideoHelperSuite in terminal when I try to boot up comfyUI. How do I fix this?

update: u/socal_nerdtastic had me downloaded the static version of FFmpeg and put it in the root ComfyUI folder. That got rid of the red “error” in terminal but the yellow “warning - failed to import imageio_ffmpeg” remained. 

Austin Mroz on github said "Since you've manually downloaded ffmpeg and the error message is no longer being shown, the warning for imageio-ffmpeg can be safely ignored. I've not been able to track down why imageio-ffmpeg isn't automatically installed for a small subset of people, but the manual intervention you've done to download ffmpeg should be enough to make things work."

So I'm trying the process again in comfyUI to see if it works. I'm trying to queue the prompt again. I got all the way to "video combine" in comfyUI, then a got a pop up on the desktop of my mac that says ffmpeg cannot be opened because the developer cannot be verified. macOs cannot verify this app is free from malware. Only after comfy cancelled the process and gave me red text errors was I able to grant security permissions in the apple settings under security and privacy. lets try again, take 3.... Only this time I'm using "proRes" instead of h264 under the "vimeo combine" box in ComfyUI. Yes I know ProRes will be a much bigger file.


ThreadPoolExecutor memory footprint ThreadPoolExecutor memory footprint

Hello all!

I have an issue, where I want to get reddits opinion before taking the suggested fixes on the numerous GitHub issues related to this.

With concurrent.futures.ThreadPoolExecutor if you pass a large iterable to map, the memory footprint can explode and cause crashes, even if the underlying operations aren’t too memory intensive.

Some suggestions I’ve seen to handle this is basically switch to a chunked submit/map operation so the executor doesn’t spawn all tasks before one has even completed.

Currently when working with a 17k length iterable (pagination for an API) the memory footprint causes a 32GB ram container to crash.


pytesseract troubleshooting pytesseract troubleshooting

I was trying to use pytesseract for text recognition. image_to_string returned TesseractNotFoundError as it was not in path or not installed. I installed tesseract from GitHub and put path to the exe in path, restarted IDE, restarted PC, nothing really changes. Path is: "C:\Program Files\Tesseract-OCR\tesseract.exe".

Is there any other library/AI to turn text in the image into string? It has to be fast enough to track real-time stream.

Thank you!


Trying to get a key with python, would this work? Trying to get a key with python, would this work?

import logging from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time # Configure logging logging.basicConfig(filename='C:\\Users\\bling\\PythonScripts\\bot_error.log', level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s') def check_for_key(): driver = None # Initialize driver variable try: # Configure WebDriver options chrome_options = Options() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--ignore-certificate-errors") chrome_options.add_argument("--ignore-ssl-errors") # Set the path to the ChromeDriver executable service = Service("C:\\Users\\bling\\PythonScripts\\chromedriver.exe") # Update this path driver = webdriver.Chrome(service=service, options=chrome_options) driver.get("https://www.marvelrivals.com/twitch/#/index") # Correct URL while True: try: # Wait until the redeem button is clickable redeem_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, ".btn_key")) ) redeem_button.click() print("Key claimed successfully!") break except EC.NoSuchElementException: print("Key not available yet.") time.sleep(60) # Check every minute except Exception as e: logging.error(f"An error occurred: {e}") finally: if driver: driver.quit() # Ensure the browser is closed properly if __name__ == "__main__": check_for_key() input("Press Enter to exit...")


Should I store this in-memory or in DB? Should I store this in-memory or in DB?

So I am building an application that needs to do a lot of reads and quite a few writes. I am using Docker and deploying it to an AWS ec2 instance. My app will run for events which usually takes around an hour and then it will wait for the next event. Within these events, it will need to do a lot of reading and writing of some data about the people in the event. The question is whether this data should just be stored in memory or if I should store it in my DB.

To give some numbers at max load I would expect around 200 people and for each of those we need to store a few simple things like an ID and and some other info. This data however will need to be read around 200 times pr. person over the 1 hour of the events. And probably write to it around 100 times. This comes out to around 40.000 reads and 20.000 writes in one hour.

I am using Supabase for the DB, and I am worried that it won't be able to handle it or that the response will be too slow, as we really need it to be super fast reads. I should note that this data will only need to be read and written to within the event, after that we would just save it for the long term in the DB and the instance would close down.

So should I store it in the database or in-memory?


Combat Phishing with Python? Combat Phishing with Python?

My mom keeps almost getting tricked by these phishing emails and I'm getting really fed up with them. I know there was a post a few weeks back on r/python about a package someone made to combat fake shopping sites (fed fake credit card info into it and overloaded it so they got charged a few cents every fake purchase, essentially bankrupting the site).

Is there an equivalent if all I have is an email address? Is there any way to counter these phishers with this single data point?

Any ideas appreciated! I would love to make a package to do this but my networking knowledge is limited.


I need help with a web scraping script I’m using for automated Shopify product updating from a catalogue on a different website I need help with a web scraping script I’m using for automated Shopify product updating from a catalogue on a different website

My main challenge is getting it to log in to endlessaisles (my website containing the data) and then getting it to find the correct elements on the page in order to grab the image url and product description. I can get it to remote it just fine but it won’t grab the stuff. Is there a simpler approach I can use for this? Or does anyone have advice on scraping a website that must be logged in to every time

Using selenium to do the web stuff


Keep getting a socket.error when I try to scan for ports. Keep getting a socket.error when I try to scan for ports.

I made sure that the syntax for the Python script that I wrote is correct. I would execute the script in the cmd and it executed fine. I would enter in my ip address, but instead of showing a list of open / closed ports, it just gives me the socket error. I’m trying to figure out what might be causing this. Could it be something with the firewall?

Here’s the code:

https://imgur.com/a/Z1GkdBC

Note: I’m using Windows os.

Note: what I mean by error is that I got the message that I put in the socket.error in the except. When I put my ip in the port scanner it says “Host not responding”.


Best way to number a string in alphabetical order Best way to number a string in alphabetical order

I’m trying to write a function that takes a word as input and returns a list where each letter is numbered according to alphabetical order.

Example:

INPUT = “bear”
OUTPUT = [2, 3, 1, 4]

If there are duplicate letters, number them sequentially from left to right.

Example:

INPUT = “reef”
OUTPUT = [4, 1, 2, 3]

My code:

input = “reef”
sorted_in = sorted(input)
out = []

for letter in input:
    indx = sorted_in.index(letter)
    out.append(indx)
    sorted_in[indx] = 0

Excuse any syntax errors, I’m typing on my phone at work. Setting sorted_in[indx] = 0 is my plan for handling duplicate letters. Is there a more efficient way to do this? I know it’s more Pythonic to use a list comprehension but I can’t figure out how to do that last bit with a list comprehension.


Want to start over again and do it the right way Want to start over again and do it the right way

1,5 years ago i decided to start learning python because i wanted to do something else career wise. So i started watching a lot of turorials, downloaded a lot of ebooks and couldn't actually move forward. I think they call it tutorial hell.

The whole "learning" python phase lasted a month. I was already kinda familiar with python from high school so i knew some basic things. But i managed to learn more in a month than 2 years in school. I made a rock paper scissors game, a calculator and a small game that's like a treasure hunt with questions. I know that it's not much, but i was really proud of the things that i made.

I wasn't taking it seriously and was farting around and following every day a new tutorial cause the old one was a little bit difficult and i wanted to be inside my comfort zone.

Now i know that learning programming needs discipline and hard work. So i want to start again and this time do it right. I will follow only one course/book and when i finish it I'll make small projects to learn even better.

The thing is that I don't know Which course to take. Started the 100 days of angela but didn't like it that much. I was thinking of automate the boring stuff(it even has videos on YouTube) or the cs50 course which seems pretty legit.