#off-topic-lounge-text

1 messages ยท Page 28 of 1

late agate
#

print(a2)

#

print(a[2])

carmine current
#

!e ```py
a = ["a", "b", "c"]
index = 2

w = a[index]
print(w)

timid fjordBOT
#

@carmine current :white_check_mark: Your eval job has completed with return code 0.

c
hybrid spoke
#

list_positions[ to_index] = char1

#

list_positions[ from_index] = char2

carmine current
#

!voice

timid fjordBOT
#

Voice verification

Canโ€™t talk in voice chat? Check out #voice-verification to get access. The criteria for verifying are specified there.

carmine current
#

@pine gull

#

!e ```py
thing = ['b', 'a']

thing = str(thing)
print(thing)

timid fjordBOT
#

@carmine current :white_check_mark: Your eval job has completed with return code 0.

['b', 'a']
mystic lynx
#

!e

#

!e

timid fjordBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*

mystic lynx
#

e

#

!E

timid fjordBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*

mystic lynx
#

!e4

#

!e

timid fjordBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*

analog sparrow
#

here?

hallow owl
#

i need help with objects and classes, can someone help me?

wide belfry
#

who knows graph?

wide belfry
#

O(n)

tepid cove
#

wan dรฉ

wide belfry
#

I found it!

bold sky
#

def func1(num1, num2):
while True:
try:
num1 = float(input("Insert your first number >>"))
except(ValueError):
print("Err... numbers only!\n")
continue
else:
break
while True:
try:
num2 = float(input("Insert your second number >>"))
except(ValueError):
print("Hey! Didn't i tell you numbers only!\n")
else:
break

#
def func1(num1, num2):
    while True:
        try:
            num1 = float(input("Insert your first number >>"))
        except(ValueError):
            print("Err... numbers only!\n")
            continue
        else:
            break
    while True:
        try:
            num2 = float(input("Insert your second number >>"))
        except(ValueError):
            print("Hey! Didn't i tell you numbers only!\n")
        else:
            break```
wide belfry
#

NaN

rigid stag
#

math.isnan(x)\

wide belfry
#

Bsf

timid fjordBOT
#

@primal bison :white_check_mark: Your eval job has completed with return code 0.

c
pastel fable
#

i can't stream

gleaming torrent
#

!eval code

timid fjordBOT
#

@gleaming torrent :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'code' is not defined
lunar skiff
#

@versed gust what's up?

#

what kinda help you lookin for?

versed gust
#

hi

#

How can i Implement this model into Microsoft Excel using the =IF() formula.?

lunar skiff
#

oh, no

versed gust
#

?

#

whyy

lunar skiff
#

VBA

versed gust
#

thats not good news!!

lunar skiff
#

but on the note, it's not Python

versed gust
#

yeah not yet at least for me

#

lol

#

just a last assignment question

#

thats need to be done

lunar skiff
#

sorry about that, don't know Excel

versed gust
#

๐Ÿ˜ฉ

#

no worries

pine pawn
#

@tepid cove what library?

tepid cove
#

joblib

pine pawn
#

is it for like stream processing

#

and parallel processing

#

big data pipelines and stuff

#

@tepid cove

#

could someone give me voice access ?

#

im tryna help someone

wind breach
#

can anyone help me

#

please

#

can i make my jarvis that it may auto recognize my language

warm hedge
#

!e

def something(name, *args, **kwargs):
    print(name)
    print(args)
    print(kwargs)


something("Iceman", "youname", "esdfdsf")
print()
something("Iceman", x=10, y=20)
print()
something("iceman", "sadndjks", a=20)```
timid fjordBOT
#

@warm hedge :white_check_mark: Your eval job has completed with return code 0.

001 | Iceman
002 | ('youname', 'esdfdsf')
003 | {}
004 | 
005 | Iceman
006 | ()
007 | {'x': 10, 'y': 20}
008 | 
009 | iceman
010 | ('sadndjks',)
011 | {'a': 20}
warm hedge
#

!e

my_list = [1, 2, 3]
print(my_list)
print(*my_list)```
timid fjordBOT
#

@warm hedge :white_check_mark: Your eval job has completed with return code 0.

001 | [1, 2, 3]
002 | 1 2 3
warm hedge
#

pirnt(1, 2, 3)

echo aurora
#

def computePayment(self):
# compute the total payment.
monthlyPayment = self.getMonthlyPayment(float(self.loanAmountVar.get()),
float(self.annualInterestRateVar.get()) / 1200,
int(self.numberOfYearsVar.get()))

self.monthlyPaymentVar.set(format(monthlyPayment, '10.2f'))
totalPayment = float(self.monthlyPaymentVar.get()) * 12 \
                       * int(self.numberOfYearsVar.get())
self.totalPaymentVar.set(format(totalPayment, '10.2f'))

compute the monthly payment.

def getMonthlyPayment(self, loanAmount, monthlyInterestRate, numberOfYears):
monthlyPayment = loanAmount * monthlyInterestRate /
(1- 1 / (1 + monthlyInterestRate) **
(numberOfYears * 12))

return monthlyPayment;
warm hedge
warm hedge
#

In this Python Beginner Tutorial, we will begin learning how to import modules in Python. We will learn how to import modules we have written, as well as modules from the Standard Library. We will also explore sys.path and how imported modules are found. Let's get started.

The code from this video can be found at:
https://github.com/CoreyMSchaf...

โ–ถ Play video
quaint saffron
wide aurora
#

im lagging out

#

i could hear you when you was deafened

#

brb

cold lintel
#

I can hear you Griff

#

Erm, I wasn't looking

#

But I could hear him I think

wide aurora
quaint saffron
wide aurora
#

!code

timid fjordBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

quaint saffron
#
class Enemy:
    def __init__(self):
        enemy_spaceship_height, enemy_spaceship_width = 200, 400
        game_enemy_image = pygame.image.load(os.path.join('Game_assets', 'enemy.png'))
        game_enemy_1 = pygame.transform.scale(game_enemy_image, (enemy_spaceship_width, enemy_spaceship_height))
        game_enemy_image_2 = pygame.image.load(os.path.join('Game_assets', 'enemy2.png'))
        game_enemy_2 = pygame.transform.scale(game_enemy_image_2, (enemy_spaceship_height, enemy_spaceship_width))
        enemy1 = pygame.Rect(319, 310, enemy_spaceship_width, enemy_spaceship_height)
        enemy2 = pygame.Rect(219, 210, enemy_spaceship_width, enemy_spaceship_height)
wide aurora
cold lintel
#

Soo... ๐Ÿ˜„

#

Heading back up...

wide aurora
#

ye

candid hearth
#

!code

timid fjordBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

candid hearth
#

error?!

#

def

#

def (makePicture)

#

ek

#

i hate all girls

strong meteor
#

why

#

would you print that

#

and also its wronh

timid fjordBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

misty topaz
#

๐Ÿ’ป ๐Ÿ–ฅ๏ธโ˜•

brittle gale
#

hiiii

tranquil temple
#

hello

dim sundial
#

I need a little help with a code issue (but the thing is too big to past), anyone got a few minutes fee time?

#

Basically it's skipping if/else and not understanding why

buoyant kestrel
hollow canopy
#
most_common = df_rem_corrupt[col].mode()[0]
df_rem_corrupt.loc[df_rem_corrupt.index.tolist(), df_rem_corrupt.select_dtypes(exclude=['int64','float64']).columns.tolist()] = df_rem_corrupt.select_dtypes(exclude=['int64','float64']).fillna(most_common)
primal bison
#

thats what i do

primal bison
#
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 902, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 864, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.0.value: This field is required``` @sturdy geyser  

```py
  embed1.add_field(name=f"{args}", value="")```
sturdy geyser
#

join code help voice 0

primal bison
#

-bug <bug>

sturdy geyser
#

embed1.add_field(name="Bug:", value=f"{args}")

primal bison
#
@client.command()
async def bug(ctx, args):
  channel = client.get_channel(824000991358746715)
  embed = discord.Embed(description="โœ… Your bug has been sent to the developer")
  await ctx.send(embed=embed)
  embed1 = discord.Embed(title="New Bug Report", timestamp=ctx.message.created_at)
  embed1.add_field(name="Bug:", value=f"{args}")
  embed1.set_footer(icon_url=ctx.author.avatar_url)
  await channel.send(embed=embed1)
#
  embed1.set_footer(icon_url=ctx.author.avatar_url)```
#

gotta get off @sturdy geyser

sturdy geyser
#

alright

#

cya

primal bison
#

thanks bye

toxic marsh
#

!e

timid fjordBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*

toxic marsh
#

!e ```python

#x = int(input())
from sympy.core.cache import cacheit

from sympy import binomial

@cacheit

def a(n): return 1 if n==0 else 2**binomial(n, 2) - sum(a(k)*binomial(n, k) for k in range(n))

print(a(4))

timid fjordBOT
#

@toxic marsh :white_check_mark: Your eval job has completed with return code 0.

41
toxic marsh
#

!e ```python
#from sympy.core.cache import cacheit

from sympy import binomial

#@cacheit

def a(n): return 1 if n==0 else 2**binomial(n, 2) - sum(a(k)*binomial(n, k) for k in range(n))

print(a(4))

timid fjordBOT
#

@toxic marsh :white_check_mark: Your eval job has completed with return code 0.

41
brittle gale
#

e8p[]

#

hiii

safe root
azure pagoda
#

ohhh

#

ok here

#

so I cannot screen share

#

yea I can send ss

#

so this is the program I am writing right now

#

ill send my code

#

right now when converting my quiz grades into intergers I get an error

#

im not quite sure why though

#

yes

buoyant kestrel
#

@azure pagoda Also, quick thing. If you change channels or leave and rejoin the call, you'll be remuted by the system.

carmine current
#
if 63 < thing <= 97:
#

!f-strings

timid fjordBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

hexed nexus
#

!e

ans=["a","c","c"]
print(str(ans) + "\n")
ans[1]="b"
print(ans)
timid fjordBOT
#

@hexed nexus :white_check_mark: Your eval job has completed with return code 0.

001 | ['a', 'c', 'c']
002 | 
003 | ['a', 'b', 'c']
young imp
#

Hasn't python 3.10 got match case?

dawn creek
#

selectedbutton = getattr(Button, 'BasicButton')
selectedbutton(parameter="Some Stuff")
naive thunder
#

Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters.

#

this is the exercise

maiden wind
#

@naive thunder

s = "adtyausavavmas"
print(s[1:-1])
naive thunder
#
def remove_char(s):
    for characters in s:
        return(s[1:-1])
maiden wind
#

there ya go ^

naive thunder
#

yeah , it worked now

#

didnt know about the slicing method so i tried to replace first and last char with "" but didnt work

#
s.replace(el1 , el2) 
#

i tried to index [0,-1]

#

apparently it doesnt work like that ๐Ÿ˜›

carmine current
#

@hazy gate seems to be on my end

hazy gate
#

its discord i think

carmine current
hazy gate
#

huh, thats kinda cool

#

hopping off, later!

carmine current
sweet snow
#

so in order to participate in the voice chat conversation i have to be active in the chat ?

azure pagoda
#

something like that

sweet snow
#

yert thank you

timid fjordBOT
#

Voice verification

Canโ€™t talk in voice chat? Check out #voice-verification to get access. The criteria for verifying are specified there.

sweet snow
#

I did the verification and I got told that I can't VC since I've been ''chatlly'' unnactive XD

azure pagoda
sweet snow
#

yes pweaaaaase

#

i have to get a reason to send 50 messages

#

not zootopia wth

graceful elk
#

what is zootopia?

sweet snow
#

the secret life of pets

graceful elk
#

\๐Ÿ‘

sweet snow
#

its like beastars

frail citrus
#

can someone help me

#

about coding I couldn't understand

livid root
#

Hey

#

What you guys doing?

sweet snow
#

beatbox sound yayy

#

omg ๐Ÿ˜‚

#

is there a spam channel XD

azure pagoda
livid root
#

I just moved to Florida, You guys know when the last hurricane happen?

sweet snow
#

bye bye

#

can u play ayayaya

#

oh oh and sponge bob song

#

bye bye meganight

livid root
#

That's Dubai

#

And Abu Dabi

#

Commercial Aircrafts how for like 36,000 Ft.

wide mesa
#

which module is being used
for the zombie
in the livestream
can anyone tell me plz

subtle edge
#

hi

shrewd pilot
#

Bilal and Mohamed are debating who won the card game they played 10 years ago. Unsurprisingly, with their unnatural memory abilities, they could remember what sequence of cards was played. Can you figure out who won and end this debate?

The game consists only of one round

In this round, they both throw a card, and whoever throws the card with the highest number wins the turn and earns the sum of numbers in both cards.

As they are sure that one of them won, it is guaranteed that there was no tie in their game.

Input
The first line will contain B (1โ€‰โ‰คโ€‰Bโ€‰โ‰คโ€‰20) representing the number in the card played by Bilal.

The second line will contain M (1โ€‰โ‰คโ€‰Mโ€‰โ‰คโ€‰20) representing the number in the card played by Mohamed.

Output
One line containing the name (Mohamed or Bilal) of the player who won the game.

Examples
inputCopy
1
5
outputCopy
Mohamed
inputCopy
14
13
outputCopy
Bilal

#

sm1 can solve uit

mighty cedar
#

pycharm?

static turtle
#

always

primal bison
#

@sweet snow i also have to get 50 msgs bro, we r together dont worry XD

#

but did you not read everything

#

its 3 days minimum, 50 messages and chat more than 30 mins block @sweet snow

sweet snow
#

Ohhhhh

sweet snow
primal bison
tender tangle
sweet snow
#

Ohh Oki I see thank you so much I'll just try to find an interesting topic related to coding and talk about it

#

PS : I'm an absolute beginner when it comes to programming and since I need at least to master one program I had to chose between R program and python so I've chosen the later

shrewd umbra
#
    if episodenum is None:
        print('Please Check ' + epath + ' Manual Inervention Needed')

    else:

        seriesfolder = urllib.parse.quote(seriestitle, safe='')
        seasonfolder = urllib.parse.quote(
            'Season ' + str(seasonenum), safe='')
        episodefinal = urllib.parse.quote(seriestitle +
                                          ' - ' + str(episodenum) + ext, safe='')
        firstpath = os.path.join(destination, seriesfolder)
        os.mkdir(firstpath)
        dest = urllib.parse.quote(destination + seriesfolder + sep + seasonfolder +
                                  sep + episodefinal, safe='')
        # shutil.move(files, dest)
        print(firstpath)
        print(dest)```
#

this was terrible 2 am coding

carmine current
#

!d pathlib

timid fjordBOT
#

New in version 3.4.

Source code: Lib/pathlib.py

This module offers classes representing filesystem paths with semantics appropriate for different operating systems. Path classes are divided between pure paths, which provide purely computational operations without I/O, and concrete paths, which inherit from pure paths but also provide I/O operations.

../_images/pathlib-inheritance.png If youโ€™ve never used this module before or just arenโ€™t sure which class is right for your task, Path is most likely what you need. It instantiates a concrete path for the platform the code is running on.

Pure paths are useful in some special cases; for example:... read more

broken talon
#

?

safe mesa
icy sky
#

i have to finish my implementation of dijkstra before joining you

#

๐Ÿ˜ญ

primal bison
#
@client.event
async def on_command_error(ctx,error):
  if isinstance(error, commands.MissingPermissions):
    embed = discord.Embed(description=f"โŒ You do not have permissions to do this")
    await ctx.message.delete()
    await ctx.send(embed=embed)
  elif isinstance(error, commands.MissingRequiredArgument):
    embed1 = discord.Embed(description=f"โŒ You did not enter all the required arguments", color=ctx.author.color)
    await ctx.message.delete()
    await ctx.send(embed=embed1)
  elif isinstance(error, commands.CommandNotFound):
    embed2 = discord.Embed(description=f"โŒ Command {CommandNotFound} is not found")
    await ctx.message.delete()
    await ctx.send(embed=embed2``` why doesnt 
```py
  elif isinstance(error, commands.CommandNotFound):
    embed2 = discord.Embed(description=f"โŒ Command {CommandNotFound} is not found")``` not work
#

o shoot worng channel

warm hedge
#

need help @frail quarry ?

frail quarry
#

yes with some user validation

warm hedge
#

any framework or just python?

#

django, flask, ?

frail quarry
#

just python data input

warm hedge
#

okay

#

shoot the question

#

u ther?

frail quarry
#

yes

warm hedge
#
def _validate(value, _type):
    try:
        if _type(value) > 0:
            print("here")
        else:
            print("nop")
    except ValueError:
        print("ERROR")


_validate("dsds", int)```
#

_validate("10.5", float)

#

!e
print(int)

timid fjordBOT
#

@warm hedge :white_check_mark: Your eval job has completed with return code 0.

<class 'int'>
fierce thunder
#

A function should do one thing and one thing only

warm hedge
#

all(list)

fresh relic
#

i made around 400

#

why ?

#

@buoyant kestrel its done
anti aliased clock in pygame

timid fjordBOT
#

Hey @fresh relic!

It looks like you tried to attach file type(s) that we do not allow (.mkv). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.

Feel free to ask in #community-meta if you think this is a mistake.

fresh relic
#

ahhh

#

ok

#

yooo i made a new wallpaper for my wallpaper engine

buoyant kestrel
#

Ooooooo

fresh relic
#

and i also made a new PS shell theme

sonic vapor
#

looks good

cold lintel
#

๐Ÿ‘€

proud lichen
#

how do these voice channels work?

primal bison
#

h

#

hi

wide aurora
#

@primal bison

#

!voice

timid fjordBOT
#

Voice verification

Canโ€™t talk in voice chat? Check out #voice-verification to get access. The criteria for verifying are specified there.

primal bison
#

!voice

#

i see

#

i wanted to ask a question

#

im making a basic guessing game and im using a looping method but i also wanna make it store how many times you retried guessing ;-;

#

well lemme show u one option i tried

#
import random


myList = ["Apple", "Crab", "Money"]



def main():
    #Input and Variables.
    tries = 0
    guess = str(input('Please guess the items, your choices are Apple, Crab and Money: ')).capitalize()
    guesser = random.choice(myList)
    '''-----'''

    #Main core of the code!
    if guesser == 'Money'  and guess == 'Money':
        print(f'\nYou have got it correct!')

    elif guesser == 'Crab' and guess == 'Crab':
        print(f'\nYou have got it correct!')

    elif guesser == 'Apple' and guess == 'Apple':
        print(f'\nYou have got it correct!')

    else:
        if guesser != guess:
            print(f'\nYou have got it wrong!!!, the correct answer was {guesser}')

    #loop script to make the game repeatable.
    repeat = input('Would you like the play again? y/n: ').capitalize()
    if repeat == "Y":
        tries + 1
        print(tries)
        main()
    else:
        print('Have a good day!!')
        exit()
main()```
#

lemme try smth no pun intended and yes please.

wide aurora
#

!e

def t():
  for _ in range(10):
    yield False
  yield True

T = t()

def test():
  if next(T):
    return 1
  else:
    return test() + 1

print(test())
timid fjordBOT
#

@wide aurora :white_check_mark: Your eval job has completed with return code 0.

11
primal bison
#

not rlly im about 2 weeks in

#

a little

wide aurora
#

!e

import random

def main():
  tries = 0
  guess = random.randint(1, 20)
  while True:
    if random.randint(1, 20) == guess:
      return tries
    else:
      tries += 1

print("It took", main(), "Attempts")
timid fjordBOT
#

@wide aurora :white_check_mark: Your eval job has completed with return code 0.

It took 7 Attempts
primal bison
#

hm.

primal bison
#

@wide aurora

#

i got it to work but

#

the bottom main() is that needed?

#

when i remove it, none of the script launches

#

i shorted some of the code :3

#
import random


myList = ["Apple", "Crab", "Money"]



def main(tries = 0):
    #Input and Variables.
    guess = str(input('Please guess the items, your choices are Apple, Crab and Money: ')).capitalize()
    guesser = random.choice(myList)

    #Main core of the code!
    print(guesser == guess and f'\nYou have got it correct! It took you {tries} tries!' or f'\nYou have got it wrong!!!, the correct answer was {guesser}')

    #loop script to make the game repeatable.
    while True:
        repeat = input('Would you like the play again? y/n: ').capitalize()
        if repeat == "Y":
            return main(tries + 1)
        else:
            print(f'\nHave a good day!! You lasted {tries} tries!')
            exit()
main()  ```
cold lintel
#

I can hear you too @shadow mauve

#

Erm, you could make your own ๐Ÿ˜„

wide aurora
cold lintel
#
import re

with open('pride-and-prejudice.txt') as file:
    words = set(re.findall(r'[a-zA-Z]+', file.read()))
#

You might get a few false-matches.

#

Doctest might work.

#
def canonical(word):
    """Return the sorted letters of the word.

    >>> canonical('word')
    'dorw'
    >>> canonical('')
    ''
    """
    ...

import doctest
doctest.testmod()
#

Standard library

#

It's useful.

#

And I think it works with pytest?

#

Sorry, it's like you and 'lit'

#

My overuse of ๐Ÿ˜„

shadow mauve
#

"""Return the sorted letters of the word.

canonical('word')
'dorw'
>>> canonical('')
''
"""

wide aurora
cold lintel
#

No indents yep

#

Yeah, when you run your file, it will run these tests.

#

So, it will try doing canonical('word') and check that the output is 'dorw'

#

If all the tests pass, it will not print anything out.

#

At the bottom.

#

You can force it to print out all the test by doing:

#
doctest.testmod(verbose=True)
#

Yep, instead of doctest.testmod()

wide aurora
#

verbose=Oof

cold lintel
#

Ah, because that comes after your main code, sorry.

#

That's why it's not being reached.

#

You might want to put the main part of your code in a main() function.

#

Sorry if this is throwing a lot at you at once.

#

That's a common way to structure python files.

#

Then you put ```py
main()

#

Yeah, so wrap the while true loop in a def main(): function.

shadow mauve
#
# Import the modules required
import json
from difflib import get_close_matches

# Loading data from json file
# in python dictionary
data = json.load(open("myfile.json"))

def canonical(word):
    """Return the sorted letters of the word.

    >>> canonical('word')
    'dorw'
    >>> canonical('')
    ''
    """
    return ''.join(sorted(word))

def anagrams(word):
    try:
        return data[canonical(word)]
    except KeyError:
        print('The items you are looking for are not within the file')
def main():
    while True:

        found = False
        letters_list = []

        letters = input('Please enter your letters: ')
            
        if not all(char.isalpha() for char in letters):
            print("Illegal Character. Re-enter your letters")
            break
            
        else:
            letters_list.append(letters)

                #Longest word checker
        
        for anagram in anagrams(letters_list):
            print(anagram)

import doctest
doctest.testmod(verbose=True)
cold lintel
#

Yep

#

Maybe also wrap the two lines to run the tests in a test() funtion.

#
def test():
    import doctest
    doctest.testmod(verbose=True)
#

Erm, it's frozen.

#

Nah, can't connect.

#

Yeah, it's tough when you're starting out ๐Ÿ˜“

#

Erm, so right now, it's just not finding any anagrams for common words?

#

yep

#

Yep

#

Alright.

#

Ah right.

#

Erm, the canonical thing should work fine.

#

Have you got the other code?

#

The code that generates the table?

#

Nah, can you paste that here?

#

Please

shadow mauve
#
import json
from collections import defaultdict

file = open('myfile.json', 'w')



def canonical(word):
    return ''.join(sorted(word))

table = defaultdict(list)
data = json.load(open("words_dictionary.json"))

for word in data:
    table[canonical(word)].append(word)
json.dump(table, file)
file.close()
#
# Import the modules required
import json
from difflib import get_close_matches

# Loading data from json file
# in python dictionary
data = json.load(open("myfile.json"))

def canonical(word):
    return ''.join(sorted(word))

def anagrams(word):
    try:
        return data[canonical(word)]
    except KeyError:
        print('The items you are looking for are not within the file')


while True:

    found = False
    letters_list = []

    letters = input('Please enter your letters: ')
        
    if not all(char.isalpha() for char in letters):
        print("Illegal Character. Re-enter your letters")
        break
        
    else:
        letters_list.append(letters)

            #Longest word checker
    
    for anagram in anagrams(letters_list):
        print(anagram)
cold lintel
#

Alright. Can I just check that this isn't for school or something?

#

Alright, I feel like you've worked pretty hard on this and had some good ideas but it's just not coming together.

#

If you like, I can provide a full solution, and you can look at that and see if you can understand how it works.

#

It will work, with a few modifications.

#

But it's hard for me to dictate that through discord ๐Ÿ˜„

#

Mind if I fix it for you?

#

Alright, one sec...

#

Btw, I'll combine together the two files into one. I'm not sure why Hemlock wanted you to write the table back to a json file.

#

Also, do you want to use this word list I found instead of the json?

#

It's the words you're allowed to use in Scrabble.

#

Yeah, Scrabble has some crazy words ๐Ÿ˜„

#

One sec...

#

Alright

#

Try this out: ```py
from collections import defaultdict

def canonical(word):
return ''.join(sorted(word))

file = open('Collins_Scrabble_Words_2019.txt')
table = defaultdict(list)
for word in file:
word = word.strip().lower()
table[canonical(word)].append(word)
file.close()

def anagrams(word):
try:
return table[canonical(word)]
except KeyError:
return []

def main():
while True:
letters = input('Please enter your letters: ')
if not all(char.isalpha() for char in letters):
print("Illegal Character. Re-enter your letters")
continue
for anagram in anagrams(letters):
print(anagram)

main()

#

You'll need that list of scrabble words.

#

I'm not sure that 'hello' was in the original wordlist you were using? ๐Ÿค”

#

Ah

#

ONOMATOPOEIA is in the list of words. Sure you spelled it right?

#

Yep

#

Ah right. This is a slightly trickier problem

#

You need to try every possible combination of fewer letters.

#

I think so

#

I have an idea.

#

The way I would do it might go over your head.

#

One sec while I think ๐Ÿค”

#

Alright, if you want to do this efficiently, the code will be quite complicated. I'd have to figure it out myself.

#

Mine is like 70WPM, and that is after a lot of practice.

#

I just don't seem to be able to get faster.

#

There are people here who type at like 120 WPM ๐Ÿ˜…

#

It's crazy

#

You sure?

#

I feel like you mean one word per second?

#

Ah right.

#

I was worried then for a second.

#

I'm actually struggling to think of how to do this tbh.

#

Finding the anagrams of a word is not that hard. But finding all the words (possibly shorter) that can be made with letters it fairly tricky.

#

Here's one way you could do it:

#

(don't worry if this doesn't make too much sense)

#

British actually ๐Ÿ˜„

#

London

#

I\ve got a fairly generic accent yep

#

Erm, 30 ๐Ÿ˜„

#

Not particularly

#

Yep

#

Like 16?

#

Ah right ok.

#

Yep

#
from itertools import combination

def subletters(letters):
    return (
        combination
        for n in reversed(range(len(letters)+1))
        for combination in combinations(letters, n)
    )
#

So, you need this this

#

Alright ๐Ÿ˜„

#

I could make it more complex if you like ๐Ÿ˜„

#

Oh ok

#

Then you can change ```py
for anagram in anagrams(letters):
print(anagram)

#

to ```py
for subletter in subletters(letters):
for anagram in anagrams(subletter):
print(anagram)

#

Alright.

#

Yep

#

Ah, should be combinations

#

Ah right ok ๐Ÿ˜„

#

Hmm, one sec.

#

Oh, I think I see what happened.

#

Might be an issue of indentation...

#

Yep

#
from collections import defaultdict
from itertools import combinations

def canonical(word):
    return ''.join(sorted(word))

file = open('Collins_Scrabble_Words_2019.txt')
table = defaultdict(list)
for word in file:
    word = word.strip().lower()
    table[canonical(word)].append(word)
file.close()

def anagrams(word):
    try:
        return table[canonical(word)]
    except KeyError:
        return []

def subletters(letters):
    return (
        combination
        for n in reversed(range(len(letters)+1))
        for combination in combinations(letters, n)
    )

def main():
    while True:
        letters = input('Please enter your letters: ')
        if not all(char.isalpha() for char in letters):
            print("Illegal Character. Re-enter your letters")
            continue
        for subletter in subletters(letters):
            for anagram in anagrams(subletter):
                print(anagram)

main()
shadow mauve
#
from collections import defaultdict
from itertools import combinations

def canonical(word):
    return ''.join(sorted(word))

def subletters(letters):
    return (
        combination
        for n in range(len(letters)+1)
        for combination in combinations(letters, n)
    )

file = open('Collins_Scrabble_Words_2019.txt')
table = defaultdict(list)
for word in file:
    word = word.strip().lower()
    table[canonical(word)].append(word)
file.close()

def anagrams(word):
    try:
        return table[canonical(word)]
    except KeyError:
        return []

def main():
    while True:
        letters = input('Please enter your letters: ')
        if not all(char.isalpha() for char in letters):
            print("Illegal Character. Re-enter your letters")
            continue
        for subletter in subletters(letters):
            for anagram in anagrams(letters):
                print(anagram)

main()
cold lintel
#

Ah, sorry

#

I made a mistake when I first typed out the code, then I changed it.

#
            for anagram in anagrams(letters):
#

should be ```py
for anagram in anagrams(subletters):

#

I know ๐Ÿ˜„

shadow mauve
#

Please enter your letters: youinmber
Traceback (most recent call last):
File "c:\Users\User\OneDrive\Documents\Python code\Longest possible word.py", line 37, in <module>
main()
File "c:\Users\User\OneDrive\Documents\Python code\Longest possible word.py", line 34, in main
for anagram in anagrams(subletters):
File "c:\Users\User\OneDrive\Documents\Python code\Longest possible word.py", line 23, in anagrams
return table[canonical(word)]
File "c:\Users\User\OneDrive\Documents\Python code\Longest possible word.py", line 5, in canonical
return ''.join(sorted(word))
TypeError: 'function' object is not iterable
PS C:\Users\User\OneDrive\Documents\Python code>

cold lintel
#

hmm

#

Oh, my mistake again

#
            for anagram in anagrams(subletter):
#

Sorry, badly named variable.

#

Nice

#

Ah, I did that deliberately

#

If you want it to go in the opposite direction, remove reversed from the subletters function.

#

Ah, wait, you want the words to get shorter as they go down or longer?

#

Ahh, right

#

Then you do want reversed.

#

You copied an earlier version of the code, before I edited reversed into it.

#
def subletters(letters):
    return (
        combination
        for n in reversed(range(len(letters)+1))
        for combination in combinations(letters, n)
    )
#

n is the length of the combination of letters.

#

Nice

#

Alright, see if you can look closely at the code and understand how it works.

#

Do you want me to show you that breakpoint() thing?

#

Alright

#

Yeah, no problem

#

Mine too tbh ๐Ÿ˜„

#

I'm experiencing caffeine withdrawal lemon_pensive

#

It's not fun

#

Anwyay, heading up to the other channel...

#

Cya ๐Ÿ‘‹

fresh relic
#

!pastebin

timid fjordBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

fresh relic
#

@gray yew

timid fjordBOT
#

Hey @gray yew!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

โ€ข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

โ€ข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

fresh relic
#

!pastebin

timid fjordBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

fresh relic
#

use this

gray yew
fresh relic
#
                elif event.type == pygame.K_RIGHT:
                    d = 'd'
#

ur doing this

                elif event.type == pygame.K_Right:
                    d = 'd'
gray yew
proud lichen
#

this error looks like a hot mess

night lily
#

!e

class MyClass:
    def return_self(self):
        return self

my_instance = MyClass()
print(my_instance is my_instance.return_self())โ€Šโ€Š
timid fjordBOT
#

@night lily :white_check_mark: Your eval job has completed with return code 0.

True
night lily
#
#The following is True
MyClass is not my_instance```
honest sun
#

@night lily i have to do some work, ill tell you when i need help with my maths hw

#

hello?

night lily
#

This function, as written, will return a reference to the class Person's method, get_friend.

night lily
#
str(person.get_friend())```
#

!e

class MyFirstClass:
    pass

class MySecondClass:
    def __str__(self):
        return 'Hello, world'
my_first_instance = MyFirstClass()
my_second_instance = MySecondClass()

print(str(my_first_instance))
print(str(my_second_instance))```
timid fjordBOT
#

@night lily :white_check_mark: Your eval job has completed with return code 0.

001 | <__main__.MyFirstClass object at 0x7fe54a06dfd0>
002 | Hello, world
night lily
#

@honest sun I'm available at the moment unless I move on to the next person. Are you around?

#

Alright. Haven't heard back, so I'll move on.

#

@wide helm

#

Were you able to sort out your turtle question?

#

@primal bison Try googling for something like plain language software license examples or a given preexisting licence name e.g. MIT licence plain language explanation.

#

@wide helm Haven't heard from you either, so I'm taking a break for now. I'll be around later.

#

@primal bison Either you weren't talking or my phone crapped the call.

#

So if you were talking, I wasn't ignoring you.

primal bison
#

the second option

night lily
#

kk

primal bison
#

!e

for i in range(10000):
  print(i)
primal bison
#

guys i need help with a code pls

#

python

night lily
#

@primal bison Avoid using list as a variable name, for starters. If that's your instructors code, I would like to frown disapprovingly at them.

#

list, being a builtin, shouldn't be overwritten.

primal bison
#

well its a quiz where i need to fill the blanks

night lily
#

I see.

primal bison
#

i filled the last 2 blanks

#

but stuck at the first one

#

u got any idea?

night lily
#

Yes.

primal bison
#

hmm

night lily
#

If I look at it for long enough I will. I know how to do the problem from nothing, but with existing stuff, I have to work out what the hell they're up to, first. Which isn't very helpful.

primal bison
#

i must fill the blanks so that the code prints out the first element of the list if it is a even number

night lily
#

Are there existing other functions that have been created previous to this?

#

I suppose min would work, but it's stupid.

primal bison
#

it didin't work

#

:C

night lily
#

Because if the list changes so the lowest value in the list is not also the first, it breaks.

night lily
#

Well it would work, but they seem to be asking for not that answer, as well they ought.

primal bison
#

exactly !

night lily
#

Whoever wrote this has a contempt for its target audience.

primal bison
#

hhaha yea

#

i found it

#

it supossed to be len

night lily
#

In terms of builtin functions, the only one which does give the first is min.

#

But that's 4.

#

Oh.

#

I didn't read the question properly.

#

I'm a grade A idiot.

#

No wonder I thought they were doing something idiotic.

#

For some reason, I was thinking it was after the parity of the first element.

primal bison
#

yeah bro it happens i just guessed it anyway and still doesnt understand how

night lily
#

len returns the number of elements within the object you feed it.

#

Usually.

primal bison
#

hmm

#

dam now

#

nvm i got it

night lily
#
for i in range(10):
    print(i)```
In turn, per line, print 10 values, 0 to 9.
primal bison
#

yeah thx

wet minnow
#

@primal bison need help?

craggy pasture
#

hi

candid hearth
#

i

#

need help with lamda function

#

please ๐Ÿ˜ฆ

bleak summit
#

what is the problem

distant root
#

Pls Send ur Doubt , I will try to help

brittle gale
#

code\

craggy pasture
#

hi

azure pagoda
#

@primal bison

#

if someone joins talk in this channel

#

and someone will give you voice role

#

this guy is helpful idk if he will join though

#

he can help you if you do not understand

carmine current
#

i would appreciate not being pinged randomly

azure pagoda
#

np

#

well I would still recommend you post your code here and maybe someone will ping you to join @primal bison

#

stay here for a while if you want

mystic whale
#

a= float( input("vvedite pervoe chislo\n") )
b= float( input("vvedite vtoroe chislo\n") )
what = input ("vyberite deistvie (+ - * /) \n")
if what == "+":
c = a + b
print("result" + str(c) )
elif what == "-":
c = a - b
print("result" + str(c) )
elif what == "*":
c = a * b
print("result" + str(c) )
elif what == "/":
c = a / b
print("result" + str(c) )
else:
print("neverno")

primal bison
#

hi

vapid pivot
#

can I share my screen in help 2?

#

help 1

#

where can I share my screen?

buoyant kestrel
#

py -3.8 -m pip install colorama

#

py -3.8 -m pip install -U discord.py

buoyant kestrel
#

DISM.exe /Online /Cleanup-image /Restorehealth

#

sfc /scannow

pastel gazelle
#

I'm back!

#

oh everyone left

halcyon kayak
#

Can anyone solve this?

night lily
#

@halcyon kayak I believe I may be able to offer some guidance in this matter.

#

If you so require.

#

I haven't heard back from you, so I'll give an overview of the sorts of things I think you might need to know.

#

Python is what is known as an object oriented language. Programming in Python involves the creation and instruction of these objects.

#

Each object you create will be an embodied instance of a blueprint, a class.

#

Class is to blueprint as class instance is to house.

#

Strings, text, are of type/class str.

#

Whole numbers without a decimal point are of type int.

#

With a decimal point are type float.

#

These are what are known as builtins.

#

There are also several builtin functions, which themselves are of one type or another. builtin function or method/bultin function.

#

There are a few "keywords" in python which are reserved, such as for,and, return etc. If it's not a keyword or syntax, everything in your code will be part of an object of one sort or another.

#

Functions are like a box of code that is run every time you say "Hey, box. Run your code."

#

So all you have to do to run it several times is to just talk to the box. You don't have to write the whole thing out.

#

Functions can take parameters as input and they can return data as output.

#

They can do both, either, or neither. Though functions, if not explicitly told to return information will return None.

#

You can have functions as part of classes, too. A function that is a child attribute of a class is called a method.

#
def my_function():
    pass # Pass does nothing except provide syntax completeness. You can't have a blank indentation in Python.

class MyClass:
    def my_method(self):
        pass```
#

In this way we have created my_function and MyClass.my_method.

#

The dot indicates a traversal of the structure. In the same way your computer has a file system with folders and files, Python has a similar system with objects.

#

"Everything" in python being an object...like classes.

#

my_method can thus be said to be an attribute of MyClass.

#

You may have noticed self.

#

I'll get to that.

#

In functions, I've mentioned parameters as input. (as distinct from the function, input)

#
print('Hello, world.')```
#

This code, when executed, will cause the text Hello, world to appear on the screen.

#

print is a builtin function, so we don't need to first create it with def, the keyword used to define a function or method.

#

To call/invoke/execute a function, you will typically add parentheses to the end (). Depending on what context you are using parentheses, this is not always indicative of the calling of a function.

#

Sometimes parentheses are involved in function defining. Sometimes they're used as a structured data object, called a tuple.

#
a = (1,2,3)
def func():
    pass```
#

So in the print example, we have fed the invocation of the function a string, 'Hello, world'.

#

While print prints text to the screen, print returns None.

#

Returning/evaluation is where a given object or invocation of an object can be thought of as undergoing a transmutation into the returned value/object, itself.

#

!e

a = 1
print(a ==1)```
timid fjordBOT
#

@night lily :white_check_mark: Your eval job has completed with return code 0.

True
night lily
#

a in this context can be thought of as nearly the literal same thing as a number 1.

#

a is thus of type int

#

!e py def my_func(): return 5 print(my_func() == 5)

timid fjordBOT
#

@night lily :white_check_mark: Your eval job has completed with return code 0.

True
night lily
#

my_func() is, itself, 5, because that's what the function returned when called.

#

!e

def my_func():
    return 5
print(my_func == 5)```
timid fjordBOT
#

@night lily :white_check_mark: Your eval job has completed with return code 0.

False
night lily
#

This is what happens when we ask Python if the function, itself, is equal to the number 5. It is not.

#

!e

def my_func(v): 
    print(v) # I am not run until my_func is called...

my_func('Hello, world.') # ...here.```
timid fjordBOT
#

@night lily :white_check_mark: Your eval job has completed with return code 0.

Hello, world.
night lily
#

Here, we have fed a string, 'Hello, world', as a parameter to the invocation of my_func.

#

v, in the scope of the running of my_func and not outside of the function, is now equal to 'Hello, world.'.

#

It, in turn, is fed into print, resulting in that being printed to screen.

#

my_func, with no return keyword, will return None.

#

So were we to do print(my_func('Apple')) it would print

Apple
None```
#

You don't always need to assign the return value of a function to a variable or give it to a function as a parameter, but you can if you need to.

#

Strings, type str, have methods.

#

Remembering that methods are functions that are child attributes of a class.

#
'Hello, world.'.upper() == 'HELLO WORLD.'```
#

Were I to evaluate this statement, it would return True

#

Lets say, however, that I wanted to create my own class.

#

One that inherits from str.

#
class MyStr(str):
    pass``` Compare to previous class creation above.
#

class, here, is to classes as def is to functions and methods.

#
my_custom_string_class_instance = MyStr('Hello, world.')
my_custom_string_class_instance.upper() == 'HELLO, WORLD.'```
#

When a class is inserted into the parentheses as above, ie class MyStr(str):, it is said to be inheriting from that class.

#

All of the classe's attributes, including the attributes that are methods, are now also attributes of MyStr.

#

Here is a class and method call without inheritance.

#
class MyClass:
    def my_method(self):
        return 5
my_class_instance = MyClass()
my_class_instance.my_method() == 5 #This is True```
#

Calls the method from the instance, then compares it, now transmuted to its return value, to 5.

#

What is self?

#

You may have noticed that I didn't give a parameter to the method call.

#

Methods, by default, automatically pass the instance from which it is being called as the parameter, self.

#

Functions and methods can have multiple parameters.

#
def my_func(a, b):
    print(a+b)
my_func(1,1)``` This will print 2
#

!e

class MyClass:
    def my_method(self, v):
        return self is v
my_instance = MyClass()
print(my_instance.my_method(my_instance))```
timid fjordBOT
#

@night lily :white_check_mark: Your eval job has completed with return code 0.

True
night lily
#

is comparing identity, == comparing equality.

#

!e

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
print(a is b)
c = a
print(a is c)```
timid fjordBOT
#

@night lily :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | False
003 | True
night lily
#

a and c point to the same object...the same instance...in memory.

#

Look now again at return self is v above.

#

Instances, when created, automatically run a method named __init__.

#

!e class MyClass: def __init__(self): print('Hello, world.') a = MyClass()

timid fjordBOT
#

@night lily :white_check_mark: Your eval job has completed with return code 0.

Hello, world.
late agate
#

opal just ping me when you come back. i'm deafening myself

night lily
#

!e ```py
class MyClass:

def __init__(self, value_parameter):
    self.value = value_parameter

def get_value(self):
    return self.value

my_instance = MyClass('Apple')
print(my_instance.get_value())โ€Š```

timid fjordBOT
#

@night lily :white_check_mark: Your eval job has completed with return code 0.

Apple
night lily
#

@halcyon kayak I hope this all can help get you started.

#

If you need to, I suggest you look through Corey Schafer's Python tutorial series playlist on YouTube.

#

Also

#

!resources

timid fjordBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

halcyon kayak
#

@night lily Thank you so much. God bless you ๐Ÿ™‚

dense ether
#

hello

#

i need help in a program

#

i have created an elif ladder in python. but when i run it, it takes a lot of time to run... if the ladder has some inputs, i need to type my input two times for its execution. is there any way to aver come this problem?

pliant ginkgo
#

Ive just learned the very absolute basics of python (lists, print, loops, import, etc) I wanted to learn to make video games for fun. the, import pygame, command doesnt work. am I doing something wrong?

dense ether
#

first u must have pygame installed

#

type "pip install pygame" in your cmd

brittle gale
#

hi

buoyant kestrel
hard estuary
#

@buoyant kestrel may i get unmuted i would like to ask a question course related

crystal fjord
#

help-candy please

nimble blaze
#

wack

brittle gale
#

hiii

glass flame
#

Yo can you save values in a var and then use the var in a list ?

drowsy pebble
#

Morning! ... well it's morning for me anyway

sturdy sierra
#

yo can i get someones help?

#

im trying to build a gui to open apps with a push of a button but cant get the executable files

#

to pop up

delicate vessel
sturdy sierra
#

Fixed thanks!

#

@delicate vessel

delicate vessel
sturdy sierra
#

Getting the file directory to open with a button

royal mantle
#

for dict in list(d):
for k, v in d.items():
if k == "account_number"():
data.append(hashlib.md5(v.encode()).hexdigest())
return data

hazy forge
#

``

hexed nexus
#

!e
if name == "main":
print(name)

timid fjordBOT
#

@hexed nexus :white_check_mark: Your eval job has completed with return code 0.

__main__
fresh sail
#

Karlsruhe, Germany

frozen sail
#

the who

#

my favorite

earnest cloak
#

!e
input = cat
print ("I im learning how to code on python", cat)

timid fjordBOT
#

@earnest cloak :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'cat' is not defined
earnest cloak
#

!e
print ("I im learning how to code on python", cat)

timid fjordBOT
#

@earnest cloak :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'cat' is not defined
hazy pebble
#

!e

def sum1(n):
   x = n * (n + 1) /2
   print(x)
sum1(5)
timid fjordBOT
#

@hazy pebble :white_check_mark: Your eval job has completed with return code 0.

15.0
hazy pebble
#

!e

set_range = int(input('Enter a valid range from 1 - 100: '))
if set_range > 100 or set_range < 1:
  return print('Please enter a valid range and try again.')
else:
  for i in range(set_range):
     n = set_range * 300000 / 100
     print(n,'%')
#

!e

def x(n):
   y = n * 2000 / 100
   print(y)
x(100)
timid fjordBOT
#

@hazy pebble :white_check_mark: Your eval job has completed with return code 0.

2000.0
sharp coral
#
@client.command()
async def bug(ctx, *,bug1):
    print('1')
    #user = (762511000897323068)
    channel = await client.get_user_info(762511000897323068)
    print(channel)
    await ctx.id.send(f"Sir this is a **Bug** report \nuserinfo -- name - {ctx.author.name}  id- {ctx.author.id} from srver - {ctx.guild.name} server id - {ctx.guild.id} \n\n--REPORT-- \n**{bug1}**")
    print('2')
    #await user.send(f"Sir this is a **Bug** report \nuserinfo -- name - {ctx.author.name}  id- {ctx.author.id} from srver - {ctx.guild.name} server id - {ctx.guild.id} \n\n--REPORT-- \n**{bug1}**")
    print(3)
    await ctx.send('Thank you for reporting your report will be reviewed by the owner ')```
night lily
#
print('1')
raise Exception```
sharp coral
# night lily ```py print('1') raise Exception```
@client.command()
async def bug(ctx, *,bug1):
    print('1')
    raise Exception
    #user = (762511000897323068)
    channel = await client.get_user_info(762511000897323068)
    print(channel)
    await ctx.id.send(f"Sir this is a **Bug** report \nuserinfo -- name - {ctx.author.name}  id- {ctx.author.id} from srver - {ctx.guild.name} server id - {ctx.guild.id} \n\n--REPORT-- \n**{bug1}**")
    print('2')
    #await user.send(f"Sir this is a **Bug** report \nuserinfo -- name - {ctx.author.name}  id- {ctx.author.id} from srver - {ctx.guild.name} server id - {ctx.guild.id} \n\n--REPORT-- \n**{bug1}**")
    print(3)
    await ctx.send('Thank you for reporting your report will be reviewed by the owner ')```
night lily
#
try:
    ...
except Exception as e:
    print(e.__repr__())```
sharp coral
# night lily ```py try: ... except Exception as e: print(e.__repr__())```
@client.command()
async def bug(ctx, *,bug1):
    print('1')
    try:
        #user = (762511000897323068)
        channel = await client.get_user_info(762511000897323068)
        print(channel)
        await ctx.id.send(f"Sir this is a **Bug** report \nuserinfo -- name - {ctx.author.name}  id- {ctx.author.id} from srver - {ctx.guild.name} server id - {ctx.guild.id} \n\n--REPORT-- \n**{bug1}**")
        print('2')
        #await user.send(f"Sir this is a **Bug** report \nuserinfo -- name - {ctx.author.name}  id- {ctx.author.id} from srver - {ctx.guild.name} server id - {ctx.guild.id} \n\n--REPORT-- \n**{bug1}**")
        print(3)
        await ctx.send('Thank you for reporting your report will be reviewed by the owner ')
    except Exception as e:
        print(e.__repr__())
#
1
AttributeError("'Bot' object has no attribute 'get_user_info'")```
#
TypeError("'ClientUser' object is not callable")```
young imp
#

client.fetch_user(id)

sharp coral
# young imp `client.fetch_user(id)`
@client.command()
async def bug(ctx, *,bug1):
    print('1')
    try:
        #user = (762511000897323068)
        channel = await client.fetch_user(762511000897323068)
        print(channel)
        await ctx.id.send(f"Sir this is a **Bug** report \nuserinfo -- name - {ctx.author.name}  id- {ctx.author.id} from srver - {ctx.guild.name} server id - {ctx.guild.id} \n\n--REPORT-- \n**{bug1}**")
        print('2')
        #await user.send(f"Sir this is a **Bug** report \nuserinfo -- name - {ctx.author.name}  id- {ctx.author.id} from srver - {ctx.guild.name} server id - {ctx.guild.id} \n\n--REPORT-- \n**{bug1}**")
        print(3)
        await ctx.send('Thank you for reporting your report will be reviewed by the owner ')
    except Exception as e:
        print(e.__repr__())```
sharp coral
late agate
#
class Rectangle:
    
    def __init__(self, top_left, width_height)
        self.top_left = top_left
        self.width_height = width_height
    
    def get_bottom_right(): 
    
    def move(): 
    
    def resize(): 
    
    def __str__(): ```
pastel gazelle
#

(1, 2)

#
    self.top_left = new_top_left```
late agate
#

can't hear you @pastel gazelle

pastel gazelle
#

self.bottom_right = ((self.top_left[0]+self.width_height[0]),(self.top_left[1]+self.width_height[1]))

late agate
#
def resize(width_height): 
        self.width_height = (width, height)```
pastel gazelle
#

self.width_height = (width, height)

late agate
#

you DC'd again

pastel gazelle
#

Computers going weird

#
    return f"{self.top_left}, {self.bottom}"```
late agate
pastel gazelle
#

Rectangle((0, 0), (1, 1)).get_bottom_right()

#

Rectangle( (0, 0), (1, 1) )

late agate
#
class Rectangle((0,0), (1,1)):```
pastel gazelle
#

A = Rectangle( (0, 0), (1, 1) )

late agate
#

self.bottom_right = ((self.top_left[0] + self.width)),(self.top_left[1]+self.height)

pastel gazelle
#

self.bottom_right = ((self.top_left[0]+self.width),(self.top_left[1]+self.height))

#

Very good

late agate
#

nice. you dc'd again

pastel gazelle
#

Discord is being weird

late agate
#

error 502?

pastel gazelle
#

Nah its just staying on that screen

late agate
#

weird

#
 def get_bottom_right(self):
        return self.bottom_right
    ```
primal bison
#

how do you code a bot to send a dm to a person when they first join a server?

late agate
#

@primal bison try claiming one of the help channels in the server. Lua is helping me right now

primal bison
#

how do I do that

late agate
#

go to available help channels

pastel gazelle
#

I have no idea what that is wanting....

#

OH we implemented move() wrong

late agate
#

we also forgot to return something?

pastel gazelle
#

I dont think so

#

Try

#

In move put self.top_left = ((self.top_left[0]+self.new_top_left[0]),(self.top_left[1]+self.new_top_left[1]))

#

Thats adding to self.top_left instead of just setting it

#

Damn dude thats just too strict :-(

late agate
#

i knoww

#

also the last test failed says rectangle has not attribute bottom

pastel gazelle
#

self.bottom_right = ((self.top_left[0]+width),(self.top_left[1]+height))

pastel gazelle
#
     pointx = _Point._x
     pointy= _Point._y
     dist_x = self._x - _Point._x
     dist_y = self._y - _Point._y
     distance = math.sqrt((dist_x**2)+(dist_y**2))
     return distance```
#

Something similar to

    self._x = self._x + _Point._x
    self._y = self._y + _Point._y```
late agate
#

ooo weeee

#

you coming back to vc?

pastel gazelle
#

idk discord just got killed by housekeeping for not responding for a minute

late agate
#

oof

pastel gazelle
#
  if self.dist_to_point(_Point) < epsilon:
    return True
  else:
    return False```
#
  if _Point1.dist_to_point(_Point2) < epsilon:
    return True
  else:
    return False```
#
  if self.dist_to_point(_Point) < epsilon:
    return True
  else:
    return False```
young imp
#
def is_close_to(self, _Point):
  return self.dist_to_point(_Point) < epsilon

Just saying randomly, maybe you can do it like this?

hearty bison
#

hey guys

hearty bison
#

hi no reply ;-;

remote arrow
#

is there a way i can learn python?

undone yoke
abstract tiger
hearty bison
#

hey yaal

undone yoke
#

HI

#

whats up

untold rain
#

gays can you see my app

fast sandal
#

!voiceverify

night lily
#

unit testing

#

@leaden yarrow Are you in need of assistance? ๐Ÿ™‚

leaden yarrow
#

yes

#

@night lily yes

#

@night lily can i speak

#

actually i am not able to speak

night lily
#

@buoyant kestrel May we have a temp unmute, prettiest of pleases?

buoyant kestrel
#

On who?

#

Oh sup, right yeah

leaden yarrow
#

okay

buoyant kestrel
#

Done

leaden yarrow
#

I need help

night lily
#

Thanking you. ๐Ÿ˜Š

young imp
#

no clue about django either :(

#

um, can you pardon @night lily

still trail
#

k

restive thorn
#

hi

#

The source code will be available in someplace?

frail quarry
#

im here

#

code help 1

#

go to code help 0

#

yes

#

ok

#

it doesnt let me join

#

Invalid metting id

severe sequoia
#

http://www.py4e.com/code3/mbox-short.txt
9.4 Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer.

#

name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)

names = []
namecounts = {}

for line in handle:
  storage = line.rstrip()
  if 'from' not in storage:
    continue 
  else: storage1 = storage.split()
        names.append(storage1[1:2])




for name in names:
    namecounts[name] = namecounts.get(name,0) + 1
    
maxvalue = 0
maxkey = 0
    
for key, value in namecounts.items():
    if maxvalue < value:
        maxvalue = value
        maxkey = key
print(maxkey, maxvalue)
dusty mirage
#

oh here, lol

#

Ok, so you are creating a dict of names and the numbers of mail messages

severe sequoia
#

also with the split, should it really look more like


name.append(storage.split()[1])
dusty mirage
#

well if youre getting just the max value, there is probably a function for that

#

built in

severe sequoia
#

my current error is a syntax error, bad input on line 13

dusty mirage
severe sequoia
#

AttributeError: 'str' object has no attribute 'append' on line 12

dusty mirage
#

whats the file look like? the one you are trying to read?

#

where?

#

Your for loop on the bottom look like it should work

queen hatch
dusty mirage
#

i got it, i'm looking at it

#

Did you do this code yourself from scratch?

#

Well, the top 3 lines don't really need to be like they are. Line 2 just says if the input is less than 1, which could be 0, then make the file name be 'mbox-short.txt'

#
name = "mbox-short.txt"
handle = open(name)

names = []
namecounts = {}

for line in handle:
  storage = line.rstrip()
  if 'from' not in storage:
    continue 
  else: storage1 = storage.split()
        names.append(storage1[1:2])




for name in names:
    namecounts[name] = namecounts.get(name,0) + 1
    
maxvalue = 0
maxkey = 0
    
for key, value in namecounts.items():
    if maxvalue < value:
        maxvalue = value
        maxkey = key
print(maxkey, maxvalue)
#

That should work.

#

instead

#

The original lines let you type in whatever you want for a file name

#

is all that was and it defaults to mbox-short.txt if you enter nothing

#

well, it may be above that, actually. Your error is on line 12, but on line 8 it only does a right strip but what you may need is a regular expression

#

to search for the email

#

specifically

#

lol, i didn't for a long time either

#

it's a way to parse text and extract specific text patterns

#

so strip() or rstrip() in actuallity is a regular expression that's built into a function

#

or method to be proper

#

so, what we need to do is see what rstrip() does for each line.

#

let me whip this up real quick

#

just about there

#

are you using any imported libraries?

#

ok

#

right, well rstrip I though strips the whitespace to the right of the line instead of all whitespace

#

So yes, that is where your problem is because you are not extracting the email by itself, you are extracting the entire line, so the names.append porting might be picking up other items from the file

#

portion*

#

give me a sec, I might be able to voice chat now

severe sequoia
#

name.append(storage.split()[1])

dusty mirage
#
for line in handle:
  storage = line.split()
  if storage[0] == 'From':
      names.append(storage[1])
#
import os

name = "mbox-short.txt"
with open(name) as handle:

    names = []
    namecounts = {}

    for line in handle:
        storage = line.split()


    if storage[0] == 'From':
        names.append(storage[1])

    print(names)```
severe sequoia
#

give me a sec, I might be able to voice chat now

#

give
me
a
sec
,
I
might
be
able
to
voice
chat

now

#

word[2] = r

dusty mirage
#

['give', 'me', 'a', etc...]

severe sequoia
#

if storage.startswith("from")

dusty mirage
severe sequoia
#
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)

names = []
namecounts = {}

for line in handle:
    storage = line.split():
        if len(storage) > 0 and storage[0] == 'From':
            continue
        else: storage = names.append(storage[1])
        




for name in names:
    namecounts[name] = namecounts.get(name,0) + 1
    
maxvalue = 0
maxkey = 0
    
for key, value in namecounts.items():
    if maxvalue < value:
        maxvalue = value
        maxkey = key
print(maxkey, maxvalue)
dusty mirage
#
import os

name = "mbox-short.txt"
with open(name) as handle:

    namecounts = {}

    for line in handle:
        storage = line.split()
        if len(storage) > 0 and storage[0] == 'From':
            if storage[1] in namecounts.keys():
                namecounts[storage[1]] += 1
            else:
                namecounts[storage[1]] = 1
        
maxvalue = 0
maxkey = 0
    
for key, value in namecounts.items():
    if maxvalue < value:
        maxvalue = value
        maxkey = key
print(maxkey, maxvalue)
#
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)

namecounts = {}

for line in handle:
    storage = line.split()
    if len(storage) > 0 and storage[0] == 'From':
        if storage[1] in namecounts.keys():
            namecounts[storage[1]] += 1
        else:
            namecounts[storage[1]] = 1
    
maxvalue = 0
maxkey = 0
    
for key, value in namecounts.items():
    if maxvalue < value:
        maxvalue = value
        maxkey = key
print(maxkey, maxvalue)
warm hedge
#

need help @hybrid gust ?

hybrid gust
warm hedge
#

huh, I saw you in code-help 1 vc, hence asked

hybrid gust
#

oh no that was just me changing the room because it was noisy

lofty tulip
#
@CLIENT#1526.event
async def on_member_update(before, after):
  print("ass")
target_roles = set([829460771704143902, 829460773566414919, 829460775634075698, 829460777303277608, 829475555443081256, 829710267905867786])

  num_target_roles = sum(role in target_roles for role in after.roles)
  print("ass1")
  num_roles = len(set(target_roles) & set(before.roles))
  print(num_roles)
  if num_target_roles >= 4:
    print("ass2")
    role =  get(after.guild.roles, name= ":trophy:")
    after.add_roles(role)```
warm hedge
#
 num_target_roles = sum(role.id in target_roles for role in after.roles)```
#
print([role.id for role in after.roles])```
#
target_roles = set([829460771704143902, 829460773566414919, 829460775634075698, 829460777303277608, 829475555443081256, 829710267905867786])```
could be 
```python
target_roles = (829460771704143902, 829460773566414919, 829460775634075698, 829460777303277608, 829475555443081256, 829710267905867786)```
warm hedge
#
class Roles:
    member_role = 243253
    dev_roel = 23423904
cold barn
#

Hi, I need assistance in this prompt of a question please:

night lily
#

@mild shoal Do you require assistance at this time? ๐Ÿ™‚

primal bison
#

im trying to make a line tool function in batch but i am wondering what the math would be like to connect these two points by a line

night lily
#

subtract point a from point b, divide by math.dist(a,b), that should be your unit vector along a to b

primal bison
#

X Y

night lily
#

Thus, a + (unit vector * distance ) == b

young imp
#

So what are you trying to do here?

#

You want to get the coordinates of every single point that lies on the line segment between those two points?

primal bison
#

!e

# point a \/
point_a_x = 17
point_a_y = 7

# point b \/
point_b_x = 35
point_b_y = 19

# minus point a from point b
x_subtracted = point_a_x-point_b_x
y_subtracted = point_a_y-point_b_y

print(x_subtracted)
print (y_subtracted)
timid fjordBOT
#

@primal bison :white_check_mark: Your eval job has completed with return code 0.

001 | -18
002 | -12
young imp
#

woops, should be x2 - x1

primal bison
#

!e

# point a \/
point_a_x = 17
point_a_y = 7

# point b \/
point_b_x = 35
point_b_y = 19

# minus point a from point b
x_subtracted = point_a_x-point_b_x
y_subtracted = point_a_y-point_b_y

print(x_subtracted)
print (y_subtracted)

math.dist(point_a_x point_a-y,point_b_x point_b_y)
timid fjordBOT
#

@primal bison :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 16
002 |     math.dist(point_a_x point_a-y,point_b_x point_b_y)
003 |                         ^
004 | SyntaxError: invalid syntax
primal bison
#

FUCK

night lily
#

I may have been wrong about the easy formula. You probably do need to be using math.atan2.

#

I know.

#

Batch.

primal bison
#

can i just get a script with input varriables so i canconvert it

young imp
#

so is inverse tan same thing as arc tan?

#

what is that atan2 then?

night lily
#

Okay. I believe I have it.

primal bison
#

yes

night lily
#
import math
def get_heading(xy_a, xy_b):
    x,y = xy_b[0]-xy_a[0], xy_b[1]-xy_a[1]
    return (math.atan2(x,y) * 180 / math.pi) % 360
def get_unit_vector(heading):
    r = math.radians(heading)
    return math.sin(r), math.cos(r)```
primal bison
#

Stupid voice verification...

undone yoke
#

@ OpalMist are you waiting/looking to help somebody in voice right now? Or do you currently need help?

primal bison
#

was helping me untill i gave up

night lily
#
import math, turtle

def get_heading(xy_a,xy_b):
    x,y = xy_b[0]-xy_a[0], xy_b[1]-xy_a[1]
    return (math.atan2(x,y)*180/math.pi) % 360

def get_unit_vector(heading):
    r = math.radians(heading)
    return math.sin(r), math.cos(r)

start = (0,0)
end = (50,70)
unit_vector = get_unit_vector(get_heading(start,end))
dist = math.dist(start, end)
points = []
for i in range(int(dist)):
    new_point = int(start[0]+(unit_vector[0]*i)), int(start[1]+(unit_vector[1]*i))
    if new_point not in points:
        points.append(new_point)
points.append(end)

for point in points:
    turtle.goto(point)```
#

Pardon the trash code.

#

...

#

and the formatting

#

Damn.

#

Right. That was...unexpected.

#

@primal bison

primal bison
#

thanks but i gave up

night lily
#

@jolly crown Do you require assistance at this time? ๐Ÿ™‚

jolly crown
#

here

#

i need help

night lily
#

Are you able to hear me?

jolly crown
#

can you repeat

#

yes

#

i can

#

yup in hd

#

guidance in vsc

#

ohh ok

#

alright

#

ok

terse forum
#

will it be okay for me to join the code/help1

jolly crown
#

i think so

night lily
#

I am at your disposal should you require assistance at this time, @terse forum

mild shoal
terse forum
night lily
#

@mild shoal I would suggest you go over Corey Schafer's YouTube tutorial series playlist for Python.

#

Also

terse forum
night lily
#

!resources

timid fjordBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

night lily
#

!e py fields = ('Apples', 'Pears', 'Grapes') lines = [(1,3,2), (5,1,7), (8,2,50)] file_lines = [','.join(fields)] for line in lines: line = ','.join([str(v) for v in line]) file_lines.append(line) file_text = '\n'.join(file_lines) print(file_text)

timid fjordBOT
#

@night lily :white_check_mark: Your eval job has completed with return code 0.

001 | Apples,Pears,Grapes
002 | 1,3,2
003 | 5,1,7
004 | 8,2,50
primal bison
#

hello

#

i was wondering how to make a script to grab a file and send it to myself through discord webhook

#

from a computer

#

yes

#

file system

#

pardon

#

no python 3.9

#

what is a module

#

all i really want to know is how to grab a file

#

i allready have a script to send to my self via discord

#

ahhh

#

ok but what script do i need to grab a file from a path

#

i want the text in the file

#

okay

night lily
#
with open('file_path_and_or_name', 'r') as file:
    text = file.read()```
primal bison
#

okay

#

so how do i copy the text

#

yeaaaa

#

i basically want it to open a file and send the file to me

night lily
primal bison
#

hmm

#

wait

#

how to send a script

night lily
#

!code

timid fjordBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

primal bison
#

i want to send a script

#

how to send

#

ok

#

see this

#

it is to grab discord tokens

#

i want to make it grab files

#

pardon

night lily
#

Take another look at the backtick example.

primal bison
#

are you talking to me

#

ok

#

i basically want to take a file

trail jewel
#

!warn 824166436771069952 We won't help with token grabbers here, please don't ask about it anymore.

timid fjordBOT
#

:incoming_envelope: :ok_hand: applied warning to @primal bison.

primal bison
#

i was not talking about token grabbers

#

i was using that as a exmaple

trail jewel
#

Let's not post token grabber code either

primal bison
#

ok i wont post

trail jewel
#

Thank you

primal bison
#

but i just wanted to know how to take a file

#

no

#

nothing to do with token grabber

#

i only posted that as a example because it shows how to use discord webhook

#

ok

#

thank you

#

bye

sturdy token
#

hi, anyone down to help w my program? (shouldnt take too long)

primal bison
#
while run:

    screen.fill(())

    z = [0] * screen_size  # Donut. Fills donut space
    b = [' '] * screen_size  # Background. Fills empty space

    for j in range(0, 628, theta_spacing):  # from 0 to 2pi
        for i in range(0, 628, phi_spacing):  # from 0 to 2pi
            c = math.sin(i)```
#

how can i put grey in the screen fill_

#

?

primal bison
#

i need help

#

how can i make a python window? that typewrites something? with black background?

#

@sturdy geyser can you may help me pls?

primal bison
#

could someone help me pls?

primal bison
#
window - Tk()
window.title('look down below โ†“')
label = Label(window, text = 'Thats the wrong file you dumbass')
label.pack (padx - 500, pady - 300)
window.mainloop()```
#

how to i fix it

#

how do i fix this

#

@safe mesa

#

can someone help me pls/

#

?

#

@storm gust can you help me on this ?

safe mesa
#

!warn 637329410760114178 Please don't spam random members of this server asking for help.

timid fjordBOT
#

:incoming_envelope: :ok_hand: applied warning to @primal bison.

primal bison
#

why but yourre project leads

safe mesa
primal bison
#

sorry

#

but idk what project leads means

safe mesa
#

It means we are the leads of a python discord project

primal bison
#

i though it means like helping with problems

#

ohhh

#

sorry

urban sigil
#

the problem is window = Tk() not switch "-" with "="

hybrid gust
#

anyone here using the gnome 40 on linux? Too many changes for my taste.

brittle gale
#

ghj'

astral oasis
#

woo

drifting cave
#

can someone help me really quick?

vernal sierra
#

I need to sleep, can someone help me please? It shouldn't take long

#

Just need to read and write from a file, for some reason it won't, will send cookies

wispy lantern
#

@night lily Can you help me with me with something?

#

okay

#

I can't open my mic yet

#

I'm having trouble getting a value from a spin box