r/pythonhelp • • Nov 12 '24

Pyenv, Tkinter and Python 3.11 Broken

3 Upvotes

I use pyenv to install and use multiple versions of python for my project testing.

Yesterday, it appears that the tcl-tk package was updated for version 9.0.0.1 on homebrew. Homebrew is required for the installation of the 'tcl-tk' package if using pyenv in combination with the use of tkinter in your code.

Ok, so my code broke, since the prior versions of python required tcl-tk v8.6. For python 3.12, I was able to upgrade to python 3.12.10 which has support for tcll-tk v9. But python 3.11 does not yet have such support.

I tried various alternatives: 'brew [email protected]', 'uv python install 3.11', along with various path and global env settings to force it to point to. tcl-tk 8.6...with no luck.

I consistently get 'can't find a usable init.tcl in the following directories...' or 'import _tkinter # If this fails your Python may not be configured for Tk'.

I have searched far and wide for various solutions to no avail (google, stack overflow, github, etc.).

So my project is dead in the water with python 3.11, while working ok with 3.12 when relying on pyenv or uv for installing/pointing-to multiple versions of python. I think my only recourse is to install 3.11 directly from python.org and make it my default python, while using pyenv for 3.12 and 3.13.

The problem occurs with: import tkinter as tk

Is anyone else seeing this problem?


r/pythonhelp • • Nov 09 '24

SOLVED Yo, can yall check this out pls?

3 Upvotes

ok so, i was trying to make a user loggin but it stops here:

*Select User:

lobster

Majestic Username!

Select Password:psw*

This is the code:

def
 UsernameSelect():

    username=input("Select User:")
    
    if username == " " or "":
        print("Invalid Username")
        UsernameSelect()
    else:
        print("Majestic Username!")
        password()

def
 password():
    
    psw=input("Select Password:")
    if  psw == " " or "":
        print("Are you sure you dont want to set any Password?")
        yn=input("[y/n]")
        if yn == "y":
            print("Cool")
        else:
            password()
             

    else:
        print("Majestic Password!")

UsernameSelect()

r/pythonhelp • • Oct 10 '24

FYI? Homebrew on MacOS is now actively preventing system-wide pip installs?

3 Upvotes

Virtual Environments are a best practice, but it was nice when learning python and doing simple scripts to just pip install anything.

A recent homebrew update on my system has broken all my projects...

import pandas as pd

ModuleNotFoundError: No module named 'pandas'

name@names-MacBook-Pro-2 app % python3 -m pip install pandas

error: externally-managed-environment

× This environment is externally managed

╰─> To install Python packages system-wide, try brew install

xyz, where xyz is the package you are trying to

install.

If you wish to install a Python library that isn't in Homebrew,

use a virtual environment:

python3 -m venv path/to/venv

source path/to/venv/bin/activate

python3 -m pip install xyz

If you wish to install a Python application that isn't in Homebrew,

it may be easiest to use 'pipx install xyz', which will manage a

virtual environment for you. You can install pipx with

brew install pipx

You may restore the old behavior of pip by passing

the '--break-system-packages' flag to pip, or by adding

'break-system-packages = true' to your pip.conf file. The latter

will permanently disable this error.

If you disable this error, we STRONGLY recommend that you additionally

pass the '--user' flag to pip, or set 'user = true' in your pip.conf

file. Failure to do this can result in a broken Homebrew installation.

Read more about this behavior here: <https://peps.python.org/pep-0668/>

note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.

hint: See PEP 668 for the detailed specification.


r/pythonhelp • • Jul 27 '24

Pycharm, Pytorch [WinError 126]

3 Upvotes

hello,

I am using pytorch again and when i have tried literally everything but pytorch doesnt want to be importeed into pycharm. The path that it gives me is completely fine to acess the files. I have no clue why it would be doing this (for refrence, i have used pytorch within the last month, so i dont know why it wouldnt work now,) Pytorch is the only module that doesnt work, every other one (pandas, scikit-learn, etc all work)

Can anyone please for the love of god explain what the hell is going on with this.

OSError: [WinError 126] The specified module could not be found. Error loading "C:\Users\clacy\PycharmProjects\Test2\.venv\Lib\site-packages\torch\lib\fbgemm.dll" or one of its dependencies.

EDIT:

I fixed the issue, i just needed to use an older version of pytorch


r/pythonhelp • • Jul 16 '24

NameError: name 'pyscreeze' is not defined

3 Upvotes

Since I was bored, I decided to write a bot that would keep my computer on. So I created a file named qwe.py. But when i try to run the code it gives this error:

PS C:\Users\xxxxx\OneDrive\Masaüstü\desktop2\VısualStudioCode\python\BOTS\computer-awake> python .\qwe.py
Traceback (most recent call last):
  File "C:\Users\xxxxx\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\pyautogui__init__.py", line 663, in _normalizeXYArgs
    location = locateOnScreen(firstArg)
               ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\xxxxx\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\pyautogui__init__.py", line 228, in _couldNotImportPyScreeze
    raise PyAutoGUIException(
pyautogui.PyAutoGUIException: PyAutoGUI was unable to import pyscreeze. (This is likely because you're running a version of Python that Pillow (which pyscreeze depends on) doesn't support currently.) Please install this module to enable the function you tried to call.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\xxxxx\OneDrive\Masaüstü\desktop2\VısualStudioCode\python\BOTS\computer-awake\qwe.py", line 6, in <module>
    pyautogui.moveTo(random.choice(random_coor_list), random.choice(random_coor_list))
  File "C:\Users\xxxxx\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\pyautogui__init__.py", line 594, in wrapper
    returnVal = wrappedFunction(*args, **kwargs)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\xxxxx\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\pyautogui__init__.py", line 1285, in moveTo
    x, y = _normalizeXYArgs(x, y)
           ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\xxxxx\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\pyautogui__init__.py", line 670, in _normalizeXYArgs
    except pyscreeze.ImageNotFoundException:
           ^^^^^^^^^
NameError: name 'pyscreeze' is not defined

Here is the code:

import pyautogui, random, time

random_coordinates = '100,200,300,400,500,600,700,800,900,1000'
random_coor_list = list(random_coordinates.split(','))
while True:
    pyautogui.moveTo(random.choice(random_coor_list), random.choice(random_coor_list))
    time.sleep(2)

Sorry if error is messy.


r/pythonhelp • • May 25 '24

Hovering / Floating effect with MoviePy

3 Upvotes

Hello. I am trying to replicate a hovering / floating effect in python using the library moviepy. To understand what I mean i suggest watching the following video. (In this case, it was applied on text with After Effects but i am intending of applying it on a video with MoviePy).

https://imgur.com/a/XFKsroC

Here's my entire code:

import logging
from moviepy.editor import ImageClip
from PIL import Image
import numpy as np
import random

logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s')

def add_floating_effect(clip, max_translation=5, max_rotation=2):
    def float_effect(get_frame, t):
        frame = get_frame(t)
        dx = random.uniform(-max_translation, max_translation)
        dy = random.uniform(-max_translation, max_translation)
        rotation = random.uniform(-max_rotation, max_rotation)
        return np.array(Image.fromarray(frame).rotate(rotation, resample=Image.BICUBIC, expand=False).transform(
            frame.shape[1::-1], Image.AFFINE, (1, 0, dx, 0, 1, dy)))
    return clip.fl(float_effect)

# Load the image
image_path = "input.png"
try:
    image_clip = ImageClip(image_path).set_duration(5)
except Exception as e:
    logging.error(f"Error loading image: {e}")
    exit()

# Apply the floating effect
floating_image_clip = add_floating_effect(image_clip)

# Save the output as video
output_path = "outputVideo.mp4"
try:
    floating_image_clip.write_videofile(output_path, codec='libx264', fps=24)
    logging.info(f"Video saved as {output_path}")
except Exception as e:
    logging.error(f"Error writing video file: {e}")

This is what i have so far, but this is nowhere what I want to achieve. It's more of a "shake" than of a float effect. See the following video as reference: https://streamable.com/lhh58v
I'm not sure with how to continue so i thought about asking this subreddit! Thanks in advance.


r/pythonhelp • • May 13 '24

ModuleNotFoundError: No module named 'colorama'

3 Upvotes

I installed colorama, yet i still get this error.

when i type "pip install colorama"
it gives me
Requirement already satisfied: colorama in c:\users\jonba\appdata\local\packages\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\localcache\local-packages\python311\site-packages (0.4.6)

but when i run my script that requires colorama it gives me
ModuleNotFoundError: No module named 'colorama'


r/pythonhelp • • Mar 12 '24

What logic would you use for this task?

3 Upvotes

Hi there. Im very new to python and have a school project to code a program. The project I'm trying to create involves user input to feed an animal which increases it's satiety_level by 1. At the same time satiety_level will start at 10 and decreases by 1 every 3 seconds. If satiety reaches 0 the animal dies and if the user tries to feed a full animal (satiety_level=10) it prints that the animal is no longer hungry.

been playing around in python for hours but can't create a loop where the satiety decreased with time, and is increased by the user feeding it, only the seperate functions.How would one approach this kind of task? Excuse my ignorance and thank you for any help.


r/pythonhelp • • Feb 04 '24

Why is it recommended to create a virtual environment for Django projects?

3 Upvotes

Why is it recommended to create a virtual environment for Django projects? Can you say why it is recommended.


r/pythonhelp • • Jan 31 '24

SOLVED Game of life code needs fixing

3 Upvotes

Got a List index out of range error on line 29, don't know why. Here's the code:

cells = [[0,0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0,0],
		[0,0,0,0,1,0,0,0,0],
		[0,0,0,0,1,0,0,0,0],
		[0,0,0,0,1,0,0,0,0],
		[0,0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0,0]]

cells = [[0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,1,0,0,0,0],
       [0,0,0,0,1,0,0,0,0],
       [0,0,0,0,1,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0]]
new_cells = [[0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0]]
def neighbors(x, y):
   return [[(x-1)%10, (y-1)%10], [(x-1)%10, y%10], [(x-1)%10, (y+1)%10],
     [x%10, (y-1)%10], [x%10, (y+1)%10],
   [(x+1)%10, (y-1)%10], [(x+1)%10, y%10], [(x+1)%10, (y+1)%10]]
def alivenb(x, y):
   res = 0
   for i in neighbors(x, y):
     if cells[i[0]][i[1]] == 1:
       res += 1
   return res

for i in range(10):
   for j in range(10):
     if cells[i][j] == 1:
       if alivenb(i, j) not in [2, 3]:
         new_cells[i][j] = 0
       else:
         new_cells[i][j] = 1
     elif cells[i][j] == 0:
       if alivenb(i, j) == 3:
         new_cells[i][j] = 1
       else:
         new_cells[i][j] = 0
for i in range(10):
   for j in range(10):
     if cells[i][j] == 0:
       print('  ', end='')
     else:
       print('##', end='')
   print('\n')

r/pythonhelp • • Nov 25 '23

err*r: argument COMMAND: invalid choice: 'activate' . Cannot activate conda environment in VSCode while it works perfectly in a command window.

3 Upvotes

Activations and deactivations work perfectly fine in a powershell prompt.

In VSCode terminal "activate" is no longer a valid choice.

I have searched far and wide for an answer to this problem, and in every case, the "answer" claimed is that I have an old version of conda and need to update. This is clearly not the case, as the versions match identically between the VSCode terminal and a powershell window.

Anyone have ideas of how to proceed here?


r/pythonhelp • • Sep 28 '23

How to open py files on chromebook terminal?

3 Upvotes

Not sure if anyone else here codes on a chromebook, but it's the only thing I have at the moment for my CS class. whenever the professor shows their screen they can run their py file from their terminal, wanted to know if i can do it on a chromebook?


r/pythonhelp • • Aug 24 '23

Coding the Pokemon card game, not sure how to structure attacks

3 Upvotes

Here's what I have so far: the Player object is a collection of CardCollection objects, which each are a collection of Card objects. Player also contains methods like draw(), place_pokemon(), and discard(). CardCollection contains methods like add_card(), move(), and find_card(). Card is mostly just an empty container for the subclass defining the specific type of card (Trainer, Energy, or Pokemon), each of which just contains information about the card.

So far so good. My problem is that each Pokemon card contains special attacks. They're different for each Pokemon, and they interact with the rules in unique ways. For example:

Agility: During your opponent's next turn prevent all effects of attacks, including damage, done to this Pokemon.
Leer: the defending Pokemon can't attack on their next turn. Benching either pokemon ends this turn.
Transparency(power): if the opponent attacks next turn they must flip a coin or it does nothing.
Mirror Move: if this Pokemon was attacked last turn, do the final effects of that attack to the opponent.
Destiny Bond: if this Pokemon is knocked out during your opponent's next turn, so is the opponent.
Leech Seed: Unless all damage is prevented from this attack, remove 1 damage counter from this Pokemon.
Retreat Aid (Power): As long as this pokemon is benched, pay 1 less to retreat your active pokemon.
Tongue Wrap: the defending pokemon is paralyzed

The ones marked "power" are passive abilities that don't use up the player's attack action for the turn.

My biggest concern is getting the architecture right at the very beginning, so that I don't fall into a tangled mess of spaghetti code and ad hoc exceptions. What would be a good way to structure the program? Specifically, the Pokemon attacks and how they interact with the rest of the code.


r/pythonhelp • • Jun 07 '23

Holding a key down like on a real keyboard

3 Upvotes

Hello, I'm very new to coding and I want to make my program hold down a key like a person would on a keyboard.

I'm currently using pynput like

   keyboard.press(button)   time.sleep(random.uniform(3, 5))   keyboard.release(button)

But it doesn't hold the key down. It's just one key press. And if I simulate it by using a loop, it still behave different then holding a key on a real keyboard.

Because holding a key on a real keyboard outputs one letter, then a small delay and then it starts printing the letters fast.

Anyone knows the soluion?


r/pythonhelp • • May 27 '23

Script not skipping scanning for volumes that have already been scanned less than one week ago

3 Upvotes

In order to reduce the amount of api calls my script does I wanted to setup a number of things like only scan for ongoing series or new series added to the comicvine website. then i created other checks like if a series has not had a new issue in 13 months mark as complete and finally if a series has already been scanned in the last seven days skip it. Issue is like my title says its still scanning for them and updating data that does not need to be updated. I know there are other issues with my script such as fields setup in the database which are not called for and lack of logging when I see under last modified for the db files it keeps updating but i dont have logs as to what its doing. I am sure there are other issues others but I am pretty new to python and need to focus on one issue at a time. here is my current script:

https://pastebin.com/ra6VrPQ8


r/pythonhelp • • May 13 '23

CS50P - Lecture 1 - Conditionals

3 Upvotes

Hi everyone. First time posting here, apologies if I have broken any rules.

I am attempting to run code of the first lecture of the titled series, named CS50P - Lecture 1 - Conditionals. The link is attached, where I am up to the 54th minute. CS50P - Lecture 1 - Conditionals.

I believe I have written up the code equivalently in my VS Code house.py programme but when I attempt to run “python3 house.py”, I receive “invalid syntax” pointing at the letter e in “match name:” May someone please point out what I have done incorrectly?

I have also attached my code for reference.

name = input("What's your name? ")

match name: case "Harry": print("Gryffindor") case "Hermione": print("Gryffindor") case "Ron": print("Gryffindor") case "Draco": print("Slytherin")

Thanks!


r/pythonhelp • • May 09 '23

args/kwargs ordering and defaults.

3 Upvotes

I have a method set() which accepts the possibility of a index and text.

def set(self, index:str|int|float=None, text:str="", **kwargs):
print(index, text)

My issue is if only 1 arg is passed i want it to be set to 'text' however if 2 or more are passed then it should be set to index, text then kwargs.

example uses:

set(0, 'some text', colour='blue') #-> index=0, text='some text', kwargs{'colour':'blue'}
set('some text') #-> index=None, text='some text'
set('end', 'some text') #-> index='end', text='some text'
set(1.0, 'some text') #-> index=1.0, text='some text'
set(text='some text') #-> index=0, text='some text'

r/pythonhelp • • Apr 08 '23

Can't install python for one user

3 Upvotes

I am trying to install python on my school laptop and the instructions we received were to uncheck the "install for all users" option when installing. However, this option is greyed out and I cant uncheck it when I'm trying to install python.

Thanks


r/pythonhelp • • Mar 23 '23

pip install giving errors with installing a certain module

3 Upvotes

Yeah, that, I want to install a module, which installs other modules, one of which requires VCPP 14 or higher, so I installed it.

After installing it now gives some other error, hjow can I fix it?

Building wheels for collected packages: twisted-iocpsupport
  Building wheel for twisted-iocpsupport (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Building wheel for twisted-iocpsupport (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [12 lines of output]
      running bdist_wheel
      running build
      running build_ext
      building 'twisted_iocpsupport.iocpsupport' extension
      creating build
      creating build\temp.win-amd64-cpython-311
      creating build\temp.win-amd64-cpython-311\Release
      creating build\temp.win-amd64-cpython-311\Release\twisted_iocpsupport
      "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -Itwisted_iocpsupport -IC:\Users\TS\AppData\Local\Programs\Python\Python311\include -IC:\Users\TS\AppData\Local\Programs\Python\Python311\Include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" /Tctwisted_iocpsupport/iocpsupport.c /Fobuild\temp.win-amd64-cpython-311\Release\twisted_iocpsupport/iocpsupport.obj
      iocpsupport.c
      c:\users\ts\appdata\local\programs\python\python311\include\pyconfig.h(207): fatal error C1083: Cannot open include file: 'basetsd.h': No such file or directory
      error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit code 2
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for twisted-iocpsupport
Failed to build twisted-iocpsupport
ERROR: Could not build wheels for twisted-iocpsupport, which is required to install pyproject.toml-based projects

r/pythonhelp • • Feb 23 '23

INACTIVE Team generator that doesn’t produce multiples

3 Upvotes

Hello,

I have this code that will produce every combination of 6 players split into 2 teams.

But unfortunately it repeats the same team as team 1 and team 2

The code

import itertools

Define list of players

players = ['Player1', 'Player2', 'Player3', 'Player4', 'Player5', 'Player6']

Use itertools to generate every possible combination of splitting 6 players into 2 teams

team_combinations = list(itertools.combinations(players, 3))

Print every combination of splitting 6 players into 2 teams

for i in range(len(team_combinations)): team1 = team_combinations[i] team2 = tuple(set(players) - set(team_combinations[i])) print("Team 1: {}\nTeam 2: {}\n".format(team1, team2))

The output

Team 1: ('Player1', 'Player2', 'Player3') Team 2: ('Player5', 'Player4', 'Player6')

Team 1: ('Player1', 'Player2', 'Player4') Team 2: ('Player5', 'Player6', 'Player3')

Team 1: ('Player1', 'Player2', 'Player5') Team 2: ('Player4', 'Player6', 'Player3')

Team 1: ('Player1', 'Player2', 'Player6') Team 2: ('Player5', 'Player4', 'Player3')

Team 1: ('Player1', 'Player3', 'Player4') Team 2: ('Player5', 'Player2', 'Player6')

Team 1: ('Player1', 'Player3', 'Player5') Team 2: ('Player2', 'Player4', 'Player6')

Team 1: ('Player1', 'Player3', 'Player6') Team 2: ('Player5', 'Player2', 'Player4')

Team 1: ('Player1', 'Player4', 'Player5') Team 2: ('Player2', 'Player6', 'Player3')

Team 1: ('Player1', 'Player4', 'Player6') Team 2: ('Player5', 'Player2', 'Player3')

Team 1: ('Player1', 'Player5', 'Player6') Team 2: ('Player2', 'Player4', 'Player3')

Team 1: ('Player2', 'Player3', 'Player4') Team 2: ('Player5', 'Player6', 'Player1')

Team 1: ('Player2', 'Player3', 'Player5') Team 2: ('Player4', 'Player6', 'Player1')

Team 1: ('Player2', 'Player3', 'Player6') Team 2: ('Player5', 'Player4', 'Player1')

Team 1: ('Player2', 'Player4', 'Player5') Team 2: ('Player6', 'Player1', 'Player3')

Team 1: ('Player2', 'Player4', 'Player6') Team 2: ('Player5', 'Player1', 'Player3')

Team 1: ('Player2', 'Player5', 'Player6') Team 2: ('Player4', 'Player1', 'Player3')

Team 1: ('Player3', 'Player4', 'Player5') Team 2: ('Player2', 'Player6', 'Player1')

Team 1: ('Player3', 'Player4', 'Player6') Team 2: ('Player5', 'Player2', 'Player1')

Team 1: ('Player3', 'Player5', 'Player6') Team 2: ('Player2', 'Player4', 'Player1')

Team 1: ('Player4', 'Player5', 'Player6') Team 2: ('Player2', 'Player1', 'Player3')

The first and the final teams are essentially the same but on different team names

Anyway to prevent this repeat?

Thanks


r/pythonhelp • • Feb 12 '23

Not working properly

3 Upvotes

Im trying to complete a project for my class and I can't get the displayWeather function to print properly. It should be triggered at the end of my Web_Data function, but nothing happens. I don't see any errors being reported, so i'm at a loss. I deleted my API key because I heard it was safer to do so when sharing code. But i have no clue because I'm so new to this. So an API key for openweathermap.org will be needed to run the code. Any help would be greatly appreciated.

# import required modules
import json
import requests

# display welcome message
print("Welcome to J.W. Weather Program.\n")


def Web_data():
    """Get zip code input for url"""

    base_url = "http://api.openweathermap.org/data/2.5/weather"
    apiKey = ""
    city = str(input("Please enter the city's zip code: "))

    url = f"{base_url}?q={city}&units=imperial&APPID={apiKey}"
    print(url)
    print()

    response = requests.get(url)
    data = response.json()
    displayWeather(data)


def displayWeather(data):
    temp = data["main"]["temp"]
    feel = data["mail"]["feels_like"]
    high = data['main']['temp_max']
    low = data['main']['temp_min']
    print(f"The temperature is: {temp} F.")
    print(f"It feels like: {feel}.")
    print(f"The high is: {high}.")
    print(f"The low is: {low}.")


def main():
    # Asks user if they want to search
    while True:
        resume = input("Do you want to know the weather? \n"
                       "Type 'Y' for yes or 'N' to quit: ")

        if resume == "y" or resume == "Y":
            try:
                Web_data()
            except Exception:
                print()
        if resume == "n" or resume == "N":
            break


main()

r/pythonhelp • • Jan 18 '23

SOLVED Python Class variable: Is None when previously set with classInstance.

3 Upvotes

The class "MyDaemon" has two methods:: "run" och "stop".In "run()" I initiate *self._controlPanel = ControlPanel()*In "stop()" I call self._controlPanel.stop() but get this error:

AttributeError: 'NoneType' object has no attribute 'Stop'

Im a python noob. I can not understand why a variable that I know has been set (see log output) is now None

Code:

class MyDaemon(Daemon):
    def __init__(self, pidfile):
        super().__init__(pidfile)
        self._controlPanel = None

    def run(self):
        self._controlPanel = ControlPanel()
        self._controlPanel.start()
        while not self.killer.kill_now:
            self._controlPanel.update()
            time.sleep(.01)
        self.cleanUp()

    def stop(self):
        logger.info("cleanup crew has arrived...")
        self._controlPanel.stop()
        super().stop()  # Stop the daemon process and remove PID file


class ControlPanel:
    @property
    def port(self):
        return self._port

    def __init__(self):
        """do important INIT stuff"""
        self._port = self.find_arduino()
        logger.info("ControlPanel initialized. Port = " + self._port)

    def find_arduino(self, port=None):
        """Get the name of the port that is connected to Arduino."""
        if port is None:
            ports = serial.tools.list_ports.comports()
            for p in ports:
                logger.info(
                    "Found: Port:%s\tName:%s\tmf:%s\tHWID:%s", p.device,
                    p.name, p.manufacturer, p.hwid)
                if p.manufacturer is not None and "Arduino" in p.manufacturer:
                    port = p.device
        return port

    def start(self):
        """Opens serial connection and other Inits..."""
        logger.info("ControlPanel starting")

    def stop(self):
        """Closes serial connection and does general cleanup"""
        logger.info("ControlPanel stopping")

    def update(self):
        """todo"""
        # maybe not have log output here as this function will be called a lot!
        # like every 5ms
        # logger.info("ControlPanel updateLoop")

Log Output:

2023-01-18 20:05:20,513 INFO    find_arduino()  Found: Port:/dev/ttyACM0        Name:ttyACM0    mf:Arduino (www.arduino.cc)
2023-01-18 20:05:20,516 INFO    find_arduino()  Found: Port:/dev/ttyAMA0        Name:ttyAMA0    mf:None 
2023-01-18 20:05:20,518 INFO      __init__()    ControlPanel initialized. Port = /dev/ttyACM0
2023-01-18 20:05:20,520 INFO         start()    ControlPanel starting
2023-01-18 20:05:24,799 INFO          stop()    cleanup crew has arrived...

Exception:

Traceback (most recent call last):
  File "/home/pi/Source/ControlPanelMasterPy/ControlPanelMasterPy/controlPanelDeamon.py", line 39, in <module>
    daemon.stop()
  File "/home/pi/Source/ControlPanelMasterPy/ControlPanelMasterPy/controlPanelDeamon.py", line 28, in stop
    self._controlPanel.stop()
AttributeError: 'NoneType' object has no attribute 'stop'

r/pythonhelp • • Jan 12 '23

A business idea - auto e-receipt

3 Upvotes

I am am aerospace design engineer looking for someone who can help me with an idea. The idea is essentially a programme which sends a receipt directly to the consumers email whenever they use their card (without the consumer having to type their email in). My issue is that I do not know any programming languages to a moderate standard. If anyone would be interested in hearing more about this please get in touch. Thank you 😁


r/pythonhelp • • Jan 03 '23

Time complexity of this code

3 Upvotes

I did the following LeetCode question and this is my solution:

class Solution:
    def longestPalindrome(self, s: str) -> str:
        hashmap = {}
        
        # Create a dictionary that shows in what locations a letter appears
        # So for "abca" it will be: {a:[0,4],b:[1],c:[2]}
        for i,c in enumerate(s):
            if c in hashmap:
                hashmap[c].append(i)
            else:
                hashmap[c] = []
                hashmap[c].append(i)
         
        # For each letter that appears more than once, check if it's a palindrome from first to last occurance
        max = 0
        for c,l in hashmap.items():
            if len(l) > 1:
                for i in range(len(l)):
                    for j in range(i+1,len(l)):
                        partial = s[l[i]:l[j]+1]
                        #print(partial)
                        if partial == partial[::-1] and len(partial) > max:
                            max = len(partial)
                            currentLongest = partial
        if max == 0:
            return s[0]
        else:
            return currentLongest

I'm trying to learn the Time complexity but I'm struggling to understand what is the time complexity of this code. Is it O(n3)? Thanks ahead!