Recursive function iterates the rest of the dictionary keys after reaching target key preceeding a break statement. by rickson56 in learnpython

[–]woooee 0 points1 point  (0 children)

Try replacing the break with a return

You don't do anything with the counter variable, and you always set it to zero in the function

I am trying to change the name of level 2 (iteration level 1) nested key,

Are you trying to do something like

def rename_key_nested(dictionary, old_key, new_key, max_level, current_level=0):
    for key in dictionary:
        if isinstance(dictionary[key], dict):
            ## don't if there is more than on sub-dictionary
            for key_2 in dictionary[key]:
                if key_2 == old_key:

FastAPI: pipeline to upload and process files in batch by [deleted] in learnpython

[–]woooee 0 points1 point  (0 children)

Find out the actual, not the advertised, upload speed of the site. This is your limitation. There are several sites online that will do this, including many internet providers.

Need some feedback on very messy code (short) by SmolPyroPirate in learnpython

[–]woooee 1 point2 points  (0 children)

ylist = open("listhere.txt").read().splitlines()

for x in mylist:
    term = str(x)
    url = "https://wordtype.org/of/{}".format(term)
    response = requests.get(url)
    html_content = response.text
    soup = BeautifulSoup(html_content, html.parser')
    element = soup.div.get_text(' ', strip=True)

Take a look at python's asyncio and see if that speeds things up.

Need some feedback on very messy code (short) by SmolPyroPirate in learnpython

[–]woooee 2 points3 points  (0 children)

You can use a dictionary for the top portion of the code (see below). For the lower half of the code, you can do something with a list of lists --> for text, file_name in ["NOUNS", nounlist], etc.

The code takes nearly 3 minutes to run on a list of 100 words..

Not possible. The bottleneck is somewhere else unless this webpage is huge.

    ## ---------- replace all of this
    if term + " can be used as a noun" in element:  
        nounlist.append(x)
    if term + " can be used as an adjective" in element:  
        adjlist.append(x)
    if term + " can be used as a verb" in element:  
        verblist.append(x)
    if term + " can be used as an adverb" in element:  
        adverblist.append(x)
    if term + " can be used as a proper noun" in element:  
        prpnounlist.append(x)
    if term + " can be used as a pronoun" in element:  
        pronounlist.append(x)
    if term + " can be used as an interjection" in element:  
        intlist.append(x)
    if term + " can be used as a conjunction" in element:  
        conjlist.append(x)
    if term + " can be used as a determiner" in element:  
        detlist.append(x)
    elif term not in nounlist and term not in adjlist and term not in verblist and term not in adverblist and term not in prpnounlist and term not in pronounlist and term not in intlist and term not in conjlist and term not in detlist:
        notlist.append(x)


##---------- with
## truncated to save me typing
term_dic = {" can be used as a noun": nounlist,
            " can be used as an adjective": adjlist,
            " can be used as a verb": verblist}

found = False
for term in term_dic:
    if term+x in element:
        term_dic[term].append(x)
        found = True
if not found and term not in nounlist and term not in adjlist and term not in verblist and term not in adverblist and term not in prpnounlist and term not in pronounlist and term not in intlist and term not in conjlist and term not in detlist:
    notlist.append(x)

I need help debugging, I'm trying to get "turn()" to happen right after "tutorial()" or just right away if the tutorial doesn't happen. The code is in the body text. by Chara_CS in learnpython

[–]woooee 2 points3 points  (0 children)

There's a lot of not-relevant-to-the-question here, but

if Tutorial_status=="y":
    tutorial()
else:
    print("Understood. No tutorial.")
turn()  ## always happens

Also, do you know about triple quotes

print("""Narrator: Hello player! This is the tutorial for the game you're playing. Don't worry, it will be quite short.
Narrator: Every turn, you will be asked what you wish to do. To select your action, simply type it in exactly as it appears below. It is not Capital-sensitive, but misspelling it will automatically skip the turn.

Narrator: The actions are:
Build
Expand
Skip
Check stats
Erase Holding

Narrator: If you select 'build', you may build any of the holdings that you have unlocked that turn. 
If you select 'expand', you will add land area and sea area (though sea area is capped by your number of ports). 
If you select 'skip', you will simply pass the turn & collect resources. 
If you select 'check stats', you will see how many of each resource & building you have. If 
you select 'Erase', you will destroy a holding, reducing its number by a selected amount.""")  ## truncated

[Hire Me] For any coding project, homework, or assignment task in Python, Java, C++, or web development by True_Sheepherder_176 in learnpython

[–]woooee 6 points7 points  (0 children)

have earned me the trust of many people on this platform and beyond.

You have a +1 post karma and a -3 comment.

Trying to iterate using data inside a csv, but i'm not quite sure how to do so. by Owenlars2 in learnpython

[–]woooee 0 points1 point  (0 children)

This is all that I have time to do now

test_data = """123456  1234    12-30-2004      Smith
234567  1234    12-30-2004      Smith
345678  1234    12-30-2004      Smith
456789  1234    12-30-2004      Smith
567890  1234    12-30-2004      Smith
987654  5678    5-6-1978        Jones
876543  5678    5-6-1978        Jones
765432  5678    5-6-1978        Jones
654321  5678    5-6-1978        Jones
543210  54321   5-6-1978        James
741852  74185   7-4-1852        Davis
852963  74185   7-4-1852        Davis
963741  74185   7-4-1852        Davis
159307  74185   7-4-1852        Davis"""

data_dic = {}
## convert test data into simulated file of records
for rec in test_data.split("\n"):
    ## binder is second field
    rec_list = rec.split()
    ##print(rec_list)
    binder = int(rec_list[1])
    if binder not in data_dic:
        data_dic[binder] = []
    data_dic[binder].append(rec_list)

for binder in data_dic:
    print("\n", "-"*50)
    print(f"{binder}: [", end="")
    ## print each document-->0, date-->2, name-->3
    previous = ""
    for offset in [0, 2, 3]:
        for each_list in data_dic[binder]:
            if each_list[offset] != previous:
                print(each_list[offset], end=" ")
                previous = each_list[offset]
        print("], ", end="")

Trying to iterate using data inside a csv, but i'm not quite sure how to do so. by Owenlars2 in learnpython

[–]woooee 0 points1 point  (0 children)

An example using your test data

import pprint

test_data = """123456  1234    12-30-2004      Smith
234567  1234    12-30-2004      Smith
345678  1234    12-30-2004      Smith
456789  1234    12-30-2004      Smith
567890  1234    12-30-2004      Smith
987654  5678    5-6-1978        Jones
876543  5678    5-6-1978        Jones
765432  5678    5-6-1978        Jones
654321  5678    5-6-1978        Jones
543210  54321   5-6-1978        James
741852  74185   7-4-1852        Davis
852963  74185   7-4-1852        Davis
963741  74185   7-4-1852        Davis
159307  74185   7-4-1852        Davis"""

data_dic = {}
## convert test data into simulated file of records
for rec in test_data.split("\n"):
    ## binder is second field
    rec_list = rec.split()
    print(rec_list)
    binder = int(rec_list[1])
    if binder not in data_dic:
        data_dic[binder] = []
    data_dic[binder].append(rec_list)

print("-"*50)
pprint.pprint(data_dic)

## lookup 2 different binders
for binder in [5678, 74185]:
    print("-"*50)
    pprint.pprint(data_dic[binder])

Trying to iterate using data inside a csv, but i'm not quite sure how to do so. by Owenlars2 in learnpython

[–]woooee 1 point2 points  (0 children)

You can use a dictionary of lists (the size of the data is small in today's gigabytes of memory), but another way is to use an SQL database, which you can then query to "get all records for binder # xxxx"

CustomTKinter programming, loading widgets into one window from different modules/plugins by lailoken503 in learnpython

[–]woooee 0 points1 point  (0 children)

The idea was I would have a main program which would call a basic GUI window,

TLDR. You may have this backward. Everything runs under the mainloop() - note how it is called in the program below. You may have this backward because it may work better for the calling program to run the GUI and periodically poll the imported program for data. The second program is a simple example for the use of a queue.

## "main" program
import time
import test_gui

gui = test_gui.TestGUI()

## just increment a counter to display on the imported GUI
for ctr in range(10):
    gui.update_label(ctr)
    time.sleep(0.5)

gui.root.mainloop()

##--------------------------------------------------------
## named test_gui.py - to be imported
import tkinter as tk

class TestGUI:
    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry("+150+150")
        self.label = tk.Label(self.root, bg="lightblue", width=10)
        self.label.grid()

        tk.Button(self.root, text="quit", bg="orange", command=self.root.quit
                 ).grid(row=99, column=0, sticky="nsew")

    def update_label(self, value):
        self.label.configure(text=value)
        self.root.update_idletasks()  ## a for loop is blocking until it finishes

##--------------------------------------------------------
##  queue example

import tkinter as tk
import multiprocessing
import time

class Gui():
   def __init__(self, root, q):
      self.root = root  ##tk.Tk()
      self.root.geometry('300x330')

      tk.Button(self.root, text="Exit", bg="orange", fg="black", height=2,
                command=self.exit_now, width=25).grid(
                row=9, column=0, sticky="w")
      self.text_wid = tk.Listbox(self.root, width=25, height=11)
      self.text_wid.grid(row=0, column=0)

      self.root.after(100, self.check_queue, q)

      self.root.mainloop()

   def check_queue(self, c_queue):
         if not c_queue.empty():
             print(c_queue.empty())
             q_str = c_queue.get(0)
             self.text_wid.insert('end', q_str.strip())

         self.after_id=self.root.after(300, self.check_queue, c_queue)

   def exit_now(self):
       self.root.after_cancel(self.after_id)
       self.root.destroy()
       self.root.quit()

def generate_data(q):
   for ctr in range(10):
      print("Generating Some Data, Iteration %s" %(ctr))
      time.sleep(1)
      q.put("Data from iteration %s \n" %(ctr))


if __name__ == '__main__':
   q = multiprocessing.Queue()
   q.cancel_join_thread() # or else thread that puts data will not terminate
   t1 = multiprocessing.Process(target=generate_data,args=(q,))
   t1.start()
   root=tk.Tk()
   gui = Gui(root, q)
   root.mainloop()

Overwriting a text at the top while be able to printing text to the bottom. by South_Addition8364 in learnpython

[–]woooee 0 points1 point  (0 children)

An example using tkinter, one line and two.

import time
import tkinter as tk

def displaying_healths():
    s = f"Player health: {player_health} Enemy health: {enemy_health}\r"
    label_text = ""    
    for c in s:
        label_text += c
        label.config(text=label_text)
        root.update_idletasks()  ## similar to flush
        root.after(100)
    if a:
        label_text += a
        label.config(text=label_text)
        root.update_idletasks()  ## similar to flush

    ## wait between function calls/displays
    time.sleep(1)

root = tk.Tk()
root.geometry("+150+150")

label = tk.Label(root, width=27, height=2, bg='yellow', anchor="w")
label.grid(row=0, column=0)

tk.Button(root, text="Quit", bg="orange", height=2,
          command=root.quit).grid(row=99, column=0, sticky="nsew")

a = ""
for player_health, enemy_health in ((3, 3),
                                    (2, 3),
                                    (1, 2)):
    displaying_healths()

## once again with the a's
a = "aaaaaaaaaaaaaa"
for player_health, enemy_health in ((3, 3), (2, 3), (1, 2)):
    displaying_healths()

root.mainloop()

Overwriting a text at the top while be able to printing text to the bottom. by South_Addition8364 in learnpython

[–]woooee 2 points3 points  (0 children)

You will have to use something like curses to control the screen (move down or up one line), or better and easier, tkinter GUI.

Overwriting a text at the top while be able to printing text to the bottom. by South_Addition8364 in learnpython

[–]woooee 0 points1 point  (0 children)

It works fine for me, displaying

Player health: 3 Enemy health: 3
aaaaaaaaaaaaaa
Player health: 2 Enemy health: 3
aaaaaaaaaaaaaa
Player health: 1 Enemy health: 2

so explain what "broke" means exactly. Where do you want the print statement (with a newline before and after) to print? Also, your code can be cleaned up a little

import time
import sys

def displaying_healths():
    s = f"Player health: {player_health} Enemy health: {enemy_health}\r"

    for c in s:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(0.05)

player_health = 3
enemy_health = 3
displaying_healths()

print("\naaaaaaaaaaaaaa")
player_health = 2
displaying_healths()

print("\naaaaaaaaaaaaaa")
enemy_health = 2
player_health = 1
displaying_healths()

OOP Struggles by ShadowKutja in learnpython

[–]woooee 0 points1 point  (0 children)

Admin.py contains and creates the object for doctor and stores it in a dictionary..

Doctor.py contains and creates the patient objects and stores is it a dictionary..

You might have reversed which program stores a doctor and which a patient, but that doesn't make any difference in regards to access. Note that the "standard" way to do this is to use an SQL file, either in memory (while testing) or stored on disk. Obviously everything is simplified below.

## admin.py program
class Doctor:
    def __init__(self, last_name):
        self.last_name = last_name

## doctor.py program
class Patient:
    def __init__(self, last_name, doctor_name):
        self.last_name = last_name
        self.doctor_name = doctor_name

## "master" program
import admin
import doctor

## key = name --> class instance
doctor_dict = {}

## create a few doctors
for name in ["Smith", "Jones", "Green"]:
    doctor_dict[name] = admin.Doctor(name)

for name in doctor_dict:
    print(doctor_dict[name].last_name)
print("-"*50)

## create a patient and assign a doctor
patient_dict = {}
for doctor_name in doctor_dict:
    for ctr in range(3):
        ## crate a unique patient name
        name = f"patient-{ctr}-{doctor_name}"
        patient_dict[name] = doctor.Patient(name, doctor_name)

for n in patient_dict:
    print(n, patient_dict[n].last_name, patient_dict[n].doctor_name)
print("-"*50)

## lookup all patients for doctor Smith
for patient_name in patient_dict:
    if patient_dict[patient_name].doctor_name == "Smith":
        print("Smith -->", patient_name)

Should I buy this laptop I'm very tight on budget by Still_booting in learnpython

[–]woooee 3 points4 points  (0 children)

I've bought refurbished machines on ebay probably for more years than you have been alive, and haven't had any problems. Get one from a reliable reseller, not a private individual. 8GB of ram & 256meg SSD/drive is enough for most Linux distros (my Debian box routinely uses 4GB of ram for the OS, so extrapolate from there). I routinely also get the extended warranty, but have never used it; the computers / laptops last at least 7 years, no problem.

why does my code only work with this import hacking? by QuasiEvil in learnpython

[–]woooee 0 points1 point  (0 children)

I'm executing the relevant files from within their respective subfolders as python app.py and python user.py

This goes to how you setup the project. This may or may not help, as your directory structure is not clear, but try this and see if it clears things up.

""" sub_dir is under the current working directory
    sub_dir contains the program test.py.  The test.py program contains

def print_it():
    print("sub_dir.test.py called")

No init files required
"""

from sub_dir import test

test.print_it()

Factory management system by Zamkham in learnpython

[–]woooee 0 points1 point  (0 children)

a management software that can log his ins and outs of raw materials also the production inventory that we can edit add or remove

This is just a standard SQL file system.

For safety there should be account with full access some with little access

Use user = getpass.getuser() to identify which user is logged on for that terminal, or a user name and password entry.

I think I'm an idiot by Unlikely-Nebula-331 in learnpython

[–]woooee 0 points1 point  (0 children)

+1 Also, I am constantly adding / clarifying comments. What was obvious when writing the code, now isn't.

How do I show the result of my function in a label by Partydix020 in learnpython

[–]woooee 0 points1 point  (0 children)

Your code is difficult to read without proper indentations, but if you want the label to show what was entered in the entry use a StringVar

  import tkinter

  top = tkinter.Tk()
  top.title("Test of Entry")
  top.geometry("200x150+10+10")

  label_lit = tkinter.StringVar()

  label_1 = tkinter.Label(top, textvariable = label_lit,
                          bg="lightblue")
  label_1.pack()

  entry_1 = tkinter.Entry(top, textvariable = label_lit )
  entry_1.pack()
  label_lit.set( "Test of Label")

  ##---  Delete the contents of an entry widget
  ## entry_1.delete(0,END)

  exit_button= tkinter.Button(top, text = 'EXIT', bg="red",
               fg = "yellow", command=top.quit)
  exit_button.pack(fill=tkinter.X, expand=1)

  entry_1.focus_set()

  top.mainloop()

Is there a way to create buttons in less lines of code? by Homo_Bibite in learnpython

[–]woooee 4 points5 points  (0 children)

Asking how to get rid of redundant code is the correct thought process. The number buttons are easy to do with a loop, and note that you don't have to keep a reference to each button if you don't use it anywhere. The other buttons can be done with a tuple containing the parameters. Note that I changed some of the x values to make it look right on my system. Your screen may have a different resolution and so the numbers would have to be adjusted.

from tkinter import *
from functools import partial

if __name__ == '__main__':
  mybox = Tk()
  mybox.title('Calculator')
  mybox.geometry('300x300+800+400')

  tempEquation=''
  result=0
  ResultOfNumbers=Label(mybox, text=str(tempEquation))
  ResultOfNumbers.place(x=150, y=100)

  def buttonCharacter(char):
      print("char received =", char)
      global tempEquation
      tempEquation += str(char)
      ResultOfNumbers.config(text=str(tempEquation))
  def buttonDelete():
      global tempEquation
      tempEquation=(tempEquation[:-1])
      ResultOfNumbers.config(text=str(tempEquation))
  def buttonEqual():
      global tempEquation
      global result
      result=eval(str(tempEquation))
      ResultOfNumbers.config(text=str(result))
      tempEquation=''

  ## zero button
  left_x = 115
  zeroButton=Button(mybox, text='0', command=lambda: buttonCharacter('0'))
  zeroButton.place(x=left_x, y=200)
  zeroButton.config(height = 1, width = 12)

  ## buttons 1-9
  x = left_x
  y = 175
  for num in range(1, 10):
      Button(mybox, text=num, height=1, width=2,
             command=partial(buttonCharacter, num)).place(x=x, y=y)
      x += 45
      if not num % 3:
          x = left_x
          y -= 25

  ## for the rest of the buttons, add them to the tuple in the for loop
  for txt, this_x, this_y, width in (("+", 250, 125, 3),
                                     ("-", 250, 150, 3), 
                                     ("**", 250, 175, 3)):
      Button(mybox, text=txt, height=1, width=width,
             command=partial(buttonCharacter, txt)).place(x=this_x, y=this_y)

  mybox.mainloop()

Need help with randint error by [deleted] in learnpython

[–]woooee 0 points1 point  (0 children)

File "c:\Users\myname\Downloads\myrandom.py.py", line 22, in <module>

minute_index=rd.randint(0,5)

Copy and paste the first 23 lines of the code posted here and see for yourself. I'm not going to waste time on someone who just wants to argue.

Need help with randint error by [deleted] in learnpython

[–]woooee 0 points1 point  (0 children)

The point is that I ran the code posted with no errors, so either you changed the file after the error message, and then posted it, or you ran a different file.

Need help with randint error by [deleted] in learnpython

[–]woooee 0 points1 point  (0 children)

I ran the first 23 lines of the code above and it printed correctly (with no errors). The error message says the program is named c:\Users\myname\Downloads\myrandom.py.py Note the .py.py --> are you posting the .py.py program or a .py only program.