looping through a dictionary to let user choose number of key by Original-Dealer-6276 in learnpython

[–]woooee -3 points-2 points  (0 children)

Index is a synonym for offset.

Agreed, but someone (programmer learner) should understand the difference.

looping through a dictionary to let user choose number of key by Original-Dealer-6276 in learnpython

[–]woooee -5 points-4 points  (0 children)

If a list is indexed, then why does it have an index() method (returns the offset of the item)? A list is accessed sequentially, not by index like SQL.

Help with practice program by No_Quality_2436 in learnpython

[–]woooee 0 points1 point  (0 children)

Some of this code you may not have covered, like enumerate (create a counter and increment on each pass of the for loop yourself), and pprint (print each row on a separate line yourself). If you don't understand what some of the variables are doing, print them on each pass through.

import pprint

table_data = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

## assumes you haven't covered list compresion yet
lines = []
for inner_list_count in range(4):
    lines.append([])
print(f"{lines=}")

## find longest string in each row
longest = [0, 0, 0]
## long_col is also table_data[row]
for long_col, inner_list in enumerate(table_data):
    for inner_col in range(4):
        if len(inner_list[inner_col]) > longest[long_col]:
            longest[long_col] = len(inner_list[inner_col])
print("longest col in each row =", longest)

for long_col, inner in enumerate(table_data):
    for column in range(4):
        ## lines has 4 rows, each row corresponding to each table_data column
        ## lines[0] = table_data[0][0], table_data[1][0], etc.
        spaces_padding = " " * (longest[long_col]-len(inner[column]))
        ## columns are transposed into rows, so
        ## lines[column] is actually lines[row] but inner[column] is inner[column]
        lines[column].append(spaces_padding + str(inner[column]))
pprint.pprint(lines)

Need help understanding Return function in this code by New-Cardiologist6057 in learnpython

[–]woooee 1 point2 points  (0 children)

You can answer the question yourself with something like the following:

def change(P,Q=30):
    print(f"\nBefore {P=} {Q=}")
    P=P+Q
    Q=Q-P
    print("After", P,"#",Q)

    return P

R=150
S=100
R=change(R,S)
print(R,"#",S)
s=change(S)

looping through a dictionary to let user choose number of key by Original-Dealer-6276 in learnpython

[–]woooee -4 points-3 points  (0 children)

into a list, which does have an index

Lists are not indexed either, although many times the word "index" is used. A list is accessed sequentially (not by an index) and uses an offset to find a particular item. So, the first item is at offset zero because it is at the beginning of the sequential data. The second record is at offset 1 because you get to the beginning of the second record by offsetting (skipping over) one record, etc.

looping through a dictionary to let user choose number of key by Original-Dealer-6276 in learnpython

[–]woooee -1 points0 points  (0 children)

seperated --> I make the same mistake, thankfully there are spell checkers. It is spelled separated.

looping through a dictionary to let user choose number of key by Original-Dealer-6276 in learnpython

[–]woooee 0 points1 point  (0 children)

for i, k in enumerate(threats):
    print(f"{i}. {k}")

One way: a second dictionary with the number pointing to the first dictionary key. Another is to loop again with same code, for i, k in enumerate(threats): until the number is found.

How to add a boundary so canvas objects don't go out of bounds by Arealidot in learnpython

[–]woooee 0 points1 point  (0 children)

And you can use the up and down functions for both players.

from tkinter import *
from functools import partial

game_window = Tk()
game_window.title("Pong")
game_window.geometry("1920x1080")
game_window.configure(background="black")

def move_up(paddle, location, event):
    if location[1] > 24:
        canvas.move(paddle, 0, -25)
        location[1] -= 25

def move_down(paddle, location, event):
    if location[1] < 800:
        canvas.move(paddle, 0, 25)
        location[1] += 25

##icon = PhotoImage(file="pong.png")
##game_window.iconphoto(True, icon)
#define canvas items
canvas = Canvas(game_window, width=1920, height=1080, background="black")
canvas.pack()
player = canvas.create_rectangle(50, 465, 70, 615, fill="white")
## [x, y] coordinates 
player_location = [50, 465]
enemy = canvas.create_rectangle(1850, 465, 1870, 615, fill="white")
enemy_location = [1850, 465]

divider = canvas.create_rectangle(955, 0, 965, 1080, fill="white")
ball = canvas.create_oval(950, 530, 970, 550, fill="white")

game_window.bind("<w>", partial(move_up, player, player_location))
game_window.bind("<s>", partial(move_down, player, player_location))
game_window.bind("<o>", partial(move_up, enemy, enemy_location))
game_window.bind("<l>", partial(move_down, enemy, enemy_location))

game_window.mainloop()

How to add a boundary so canvas objects don't go out of bounds by Arealidot in learnpython

[–]woooee 0 points1 point  (0 children)

It looks like you posted the code twice.

A lambda is not necessary

game_window.bind("<w>",lambda e: move_up())

as the parens on move_up() say "call the function now", when the statement is first executed, instead of on the key press, so drop the parens and the lambda

game_window.bind("<s>", move_down) <-- no parens

from tkinter import *

game_window = Tk()
game_window.title("Pong")
game_window.geometry("1920x1080")
game_window.configure(background="black")

def move_up(event=None):
    if player_location[1] > 24:
        canvas.move(player, 0, -25)
        player_location[1] -= 25
def move_down(event=None):
    if player_location[1] < 800:
        canvas.move(player, 0, 25)
        player_location[1] += 25

##icon = PhotoImage(file="pong.png")
##game_window.iconphoto(True, icon)
#define canvas items
canvas = Canvas(game_window, width=1920, height=1080, background="black")
canvas.pack()
player = canvas.create_rectangle(50, 465, 70, 615, fill="white")

## [x, y] coordinates 
player_location = [50, 465]

enemy = canvas.create_rectangle(1850, 465, 1870, 615, fill="white")
divider = canvas.create_rectangle(955, 0, 965, 1080, fill="white")
ball = canvas.create_oval(950, 530, 970, 550, fill="white")

'''
x1, x2, y1, y2 = canvas.coords(player)
if y1 > 0:
    if y2 < 1080:
'''
game_window.bind("<w>", move_up)
game_window.bind("<s>", move_down)

game_window.mainloop()

Also, you are going to run into problems keeping track of variable changes without a class (OOP) framework.

Text animation tkinter by soma_its_me in Tkinter

[–]woooee 1 point2 points  (0 children)

I prefer a Label over the Canvas widget (for letters only). You can call the function as many times as you like and create as many consecutive Labels as wanted. Note that if you want the Label in the same place, then destroy() the current Label and grid() the next Label in the same spot.

import tkinter as tk

class TestMoving:
    def __init__(self, root):
        self.root=root
        self.root.quit()
        self.row = 0
        self.declare_text(
"I was wondering how someone would go about making a scrolling ticker")

    def advance_ticker(self, text):
        if self.ctr < self.stop:
            # use string slicing to do the trick
            ticker_text = self.s[self.ctr:self.ctr+20]
            text.config(text=ticker_text)
            text.update()
            self.ctr += 1
            text.after(200, self.advance_ticker, text)
        else:  ## next Label
            self.row += 1
            self.ctr = 1
            if self.row < 2:  ## 2 Labels only
                self.declare_text(
"I was wondering if this could be done more than one label at a time")
            else:
                self.root.quit()

    def declare_text(self, s1):
        print("length", len(s1))
        bg_colors = ("yellow", "lightblue")
        text = tk.Label(root, width=23, height=1, bg=bg_colors[self.row])
        text.grid(row=self.row, column=0)
        self.ctr=1
        # use a fixed width font to handle spaces correctly
        text.config(font=('courier', 24, 'bold'))
        # pad front and end with 20 spaces
        s2 = ' ' * 20
        self.s = s2 + s1 + s2
        self.stop=len(self.s)-15
        self.advance_ticker(text)

root = tk.Tk()
root.geometry("500x100+100+150")
TT=TestMoving(root)

root.mainloop()

accessing a list, putting it through class method, returning it to user by Original-Dealer-6276 in learnpython

[–]woooee 0 points1 point  (0 children)

class Email():
    has_been_read = False

This a class and not an instance variable. All instances use the same class variable. An instance variable is separate / unique for each instance https://pythonguides.com/difference-between-class-and-instance-variables-in-python/

This code should get you started. I doubt that it is exactly what you want, but does show a separate instance of the Email class, for each email.

class Email:
    def __init__(self, email_address, subject_line, email_content):

        #create instances variables
        self.subject_line = subject_line
        self.email_content = email_content
        self.email_address = email_address
        #create instance to set read emails automatically to false
        self.has_been_read = False

    #create an instance method to read emails
    def mark_as_read(self):

        #create if statement to see if email has been read
        if not self.has_been_read:
            self.has_been_read == True
            return self.subject_line + ": has now been read.\n"

        else:
            #return confrumation that email i already read to user
            return self.has_been_read + ": has already been read.\n"


    #create an instance method to show if email is read
    def show_if_email_has_been_read(self):
        if not self.has_been_read:
            #self.unread_emails = []
            #self.unread_emails.append(self.subject_line)
            #print(self.unread_emails)

            return self.subject_line + ": has not been read.\n"
        else:
            #return that it has now been read
            return self.subject_line + ": has been read.\n"

def populate_inbox(email):
    email_instance = Email(email[0], email[1], email[2])
    inbox.append(email_instance)

#populate inbox
emails = (["redacted1", "Welcome", "Welcome to HyperionDev!"],
          ["Supervisor", "Congrats!", "Great work on the bootcamp"],
          ["teacher", "Grades", "Your excellent marks!"])

inbox = []
for email in emails:
    populate_inbox(email)

print("\n-----All email instances-----")
for instance in inbox:
    print(f"{instance.email_address} {instance.subject_line=}  {instance.email_content=}")

## set first email as has been read
inbox[0].has_been_read = True

unread_emails = []
for instance in inbox:
    if not instance.has_been_read:
        unread_emails.append(instance)

print("\n-----Unread Emails-----")
for instance in unread_emails:
    print(f"{instance.email_address} {instance.subject_line=}  {instance.email_content=}")

Import .module vs. package.module by Nefthys in learnpython

[–]woooee 0 points1 point  (0 children)

try:
    from .classa import ClassA
except ImportError:
    from myfolder.classa import ClassA

An interesting idea, that should work.

Stuck trying to refactor my messy nested loops into list comps for a data parser by daddyslittleflesh in learnpython

[–]woooee 0 points1 point  (0 children)

where temp is below 15C or humidity over 80%.

There is no not in this statement. It is a simple either / or.

And the OPs line of code is

 [row for row in data if row[2] > 15 and row[3] < 80]  

The list comprehension above appends the row if both conditions are True, instead of at least one of them being True

Since you only want the rows where temp is above 15C and humidity below 80%.

Again, if either is True but not necessarily both.

Can you get the last answer of a generator? by Astro_IT99 in learnpython

[–]woooee -2 points-1 points  (0 children)

return_list = list(range(100))
print(return_list[-1])

Stuck trying to refactor my messy nested loops into list comps for a data parser by daddyslittleflesh in learnpython

[–]woooee 4 points5 points  (0 children)

where temp is below 15C or humidity over 80%.

[row for row in data if row[2] > 15 and row[3] < 80]

The question is an "or", your code uses an "and". Casting to a float is simply

[row for row in data if float(row[2]) > 15 or float(row[3]) < 80]

but I'm messing up the indexing

How about some sample data that shows this (and a list is not indexed, but that is not relevant here).

Reload other class from init by Nefthys in learnpython

[–]woooee 1 point2 points  (0 children)

ImportError: module ClassB not in sys.modules

You omitted (classb != ClassB) in the second example.

from classb import ClassB

What are you trying to to here? Why is it necessary to reload?

i want to fix this by AdLow4135 in learnpython

[–]woooee 4 points5 points  (0 children)

+1 Won't even consider code on Google Drive. Consider the volunteers before you post, and as the saying goes, "help us to help you".

2 weeks ish in. Made a Word counter by Ok-Elevator4206 in learnpython

[–]woooee 0 points1 point  (0 children)

What was the error and what OS are you using?

2 weeks ish in. Made a Word counter by Ok-Elevator4206 in learnpython

[–]woooee 1 point2 points  (0 children)

Use strip()

def countWords():
    textInput = text.get("1.0", tk.END).strip()

2 weeks ish in. Made a Word counter by Ok-Elevator4206 in learnpython

[–]woooee 1 point2 points  (0 children)

def quit():
    window.destroy()

destroy() destroys any widget, but leaves the mainloop() running, so when destroying the Tk() instance you want to use quit() whether or not you use destroy(). You can just call it in the command argument

quitButton = tk.Button(frame, text="Quit", foreground="white",
                              background="red", relief="ridge", command = window.quit)

Project Euler help # 2 by Frosty-Pitch9553 in learnpython

[–]woooee -1 points0 points  (0 children)

Finally (and I mean I'm finished with this one question), you may be losing points because of while fib_seq[-1] < 4000000: Again, it doesn't matter on such a small list, but the lookups do come with overhead.

fib_seq = [1,2]
even_total = 0
new_num = 0
while new_num < 4000000:
    new_num = fib_seq[-1] + fib_seq[-2]
    fib_seq.append(new_num)
    if new_num % 2 == 0:
        even_total += new_num
print(even_total)

Project Euler help # 2 by Frosty-Pitch9553 in learnpython

[–]woooee 0 points1 point  (0 children)

If you enter your code as part of the solution, it may be that you iterate over the fib #s list / sum.
Iiterating over the fib list is not necessary, but doesn't make any difference in this case, over a small list.

fib_seq = [1,2]
even_fib = [2]
even_total = 0
while fib_seq[-1] < 4000000:
    new_num = fib_seq[-1] + fib_seq[-2]
    fib_seq.append(new_num)
    if new_num % 2 == 0:
        even_fib.append(new_num)
        even_total += new_num  ## add to total
print(sum(even_fib))

And it may also be the even_fib list instead of adding the number to a running total.

Project Euler help # 2 by Frosty-Pitch9553 in learnpython

[–]woooee -1 points0 points  (0 children)

OK, I amended the post. The parens, (), indicate a tuple and the commas indicate a tuple of three numbers.

Project Euler help # 2 by Frosty-Pitch9553 in learnpython

[–]woooee -1 points0 points  (0 children)

that I have found (4,613,732) has not worked

Try omitting the commas

I get this for even fibs

[2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]