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 • • 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 05 '23

Would it be realistic to be able to write an A.I. with Python and Tensorflow that can write unique stories using certain inputs within the span of 1-3 months starting as a beginner in A.I. programming?

3 Upvotes

For context, I have over three years of experience as a programmer. This doesn't just include studying but also in a work environment.

I've been looking into how to approach and what datasets I can use to train it but I'm honestly going in blind. I'm considering using Python and Tensorflow. Is it realistic for me to be able to do something like this in 1-3 months?

I was initially planning on using the Open AI API but it's way to costly and honestly I already wrote the code for it generally and don't feel like I'll improve much as a programmer if I continue by using the API. I'm considering pivoting as a programmer anyways and figured I might as well tackle this head on while using it for my business.


r/pythonhelp • • Jan 02 '23

Just installed python 3.11 where do I go from here?

3 Upvotes

I just installed python 3.11 on my windows pc, what is my next step to start programming. How do I start making programming projects?


r/pythonhelp • • Dec 27 '22

New to python from Matlab. Seem to be getting a strange response

3 Upvotes

I am used to defining a function in the following method, but unfortunately, it does not seem to be working. Could someone help me out?

x = np.linspace(0, 50, 2001)
for i in range(len(x)):
Vk[i] = 0.5*k*(x[i])^2 -(1/3)*a*(x[i])^3
plt.plot(x, Vk)


r/pythonhelp • • Dec 23 '22

Calculating weight on planets

3 Upvotes

Hello,

I am trying to learn python on my own and i am having a difficult time with this exercise where I have to calculate the weight of a person in a x planet, can you give some guidance pls?

Thank you all in advance.

The exercise goes like this:

"Due to the difference in gravity on each celestial body, your weight is nowhere the same as on Earth. on

on some celestial bodies the gravity is greater and you therefore weigh more, on others the gravity is less

and you weigh less.

Which celestial body is best for you to move to to achieve your ideal weight? Enter your weight, choose one

celestial body and perform your mass on the chosen celestial body.

 your mass on the moon = weight x 0.166

 your mass on Jupiter = weight x 2.36

 your mass on Mars = weight x 0.37

 your mass on Venus = weight x 0.9

 your mass on Neptune = weight x 1.12

parameters

The weight is a decimal number.

The celestial body is entered correctly: moon with a small letter, Jupiter, Mars, Venus and Neptune with

one upper case letter.

For any other celestial object or incorrect spelling, you display an error message."

I can get any further than this:

weight = float(input("Give your weight in(kg): "))
planet = input("In which planet are you? ")
#moon * 0.166
#Jupiter * 2.36
#Mart * 0.37
#Venus * 0.9
#Neptune * 1.12
if planet == moon:
  weight = weight * 0.166

print("At " + str(planet) + " your weight is " + str(weight) + " kg")

I know is not far completed but wanted to test if it calculated correctly en it doesn't.

Result is:

Give your weight in(kg): 90

In which planet are you? moon

At moon your weight is 90.0 kg


r/pythonhelp • • Dec 20 '22

AttributeError 'NoneType' object has no attribute 'group'

3 Upvotes

**What the script is about**

the script is used for scraping off Instagram and putting it in a compilation to upload it on youtube but it runs into some errors

**source**

https://github.com/nathan-149/automated_youtube_channel

**Error code**

```

Exception has occurred: AttributeError

'NoneType' object has no attribute 'group'

File "C:\Users\u\OneDrive\Desktop\Autoyt\automated_youtube_channel-master\scrape_videos.py", line 29, in scrapeVideos

looter = ProfileLooter(acc, videos_only=True, template="{id}-{username}-{width}-{height}")

File "C:\Users\u\OneDrive\Desktop\Autoyt\automated_youtube_channel-master\main.py", line 91, in routine

scrapeVideos(username = IG_USERNAME,

File "C:\Users\u\OneDrive\Desktop\Autoyt\automated_youtube_channel-master\main.py", line 137, in attemptRoutine

routine()

File "C:\Users\u\OneDrive\Desktop\Autoyt\automated_youtube_channel-master\main.py", line 146, in <module>

attemptRoutine()

```

I somehow cand find any attribute called "group" in any file in the project and dont know what could be the issue, anyone who knows what is going wrong there?

**Tried**

Code to run a fully automated youtube that can scrape content, edit a compilation, and upload to youtube daily. Fixing it by removing the attribute "group"

**Ended up with**

Not finding any attribute that is called group or even the word itself across all the files.


r/pythonhelp • • Dec 13 '22

Can't get the xformers library installed into stable diffusion

3 Upvotes

I've tried a lot of different things from github and from other places on reddit but I can't seem to figure this out so I figured it was probably time to actually investigate the issue.

So when I add --xformers to the commandline_args string in launch.py (which is supposedly the way install this) it just crashes with this output.

wh33t@wh33tbox:~/stable-diffusion-webui$ source venv/bin/activate
(venv) wh33t@wh33tbox:~/stable-diffusion-webui$ python launch.py 
Python 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0]
Commit hash: 685f9631b56ff8bd43bce24ff5ce0f9a0e9af490
Installing xformers
Traceback (most recent call last):
  File "/home/wh33t/stable-diffusion-webui/launch.py", line 294, in <module>
    prepare_environment()
  File "/home/wh33t/stable-diffusion-webui/launch.py", line 230, in prepare_environment
    run_pip("install xformers", "xformers")
  File "/home/wh33t/stable-diffusion-webui/launch.py", line 78, in run_pip
    return run(f'"{python}" -m pip {args} --prefer-binary{index_url_line}', desc=f"Installing {desc}", errdesc=f"Couldn't install {desc}")
  File "/home/wh33t/stable-diffusion-webui/launch.py", line 49, in run
    raise RuntimeError(message)
RuntimeError: Couldn't install xformers.
Command: "/home/wh33t/stable-diffusion-webui/venv/bin/python" -m pip install xformers --prefer-binary
Error code: 1
stdout: Collecting xformers
  Using cached xformers-0.0.13.tar.gz (292 kB)
  Preparing metadata (setup.py): started
  Preparing metadata (setup.py): finished with status 'error'

stderr:   error: subprocess-exited-with-error
  
  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [8 lines of output]
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "/tmp/pip-install-p_qus4ba/xformers_c337561fd2d6424ab02d68796aaf774b/setup.py", line 239, in <module>
          ext_modules=get_extensions(),
        File "/tmp/pip-install-p_qus4ba/xformers_c337561fd2d6424ab02d68796aaf774b/setup.py", line 157, in get_extensions
          raise RuntimeError(
      RuntimeError: CUTLASS submodule not found. Did you forget to run `git submodule update --init --recursive` ?
      [end of output]
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.


(venv) wh33t@wh33tbox:~/stable-diffusion-webui$

Can someone explain to me what those error messages mean? Is it because I'm using the wrong Python version or something? I don't get how this can work for so many people but not for me.


r/pythonhelp • • Dec 11 '22

Transforming a .py file to a .exe and then sending to friends

3 Upvotes

Hi everyone! First I don’t know if this belongs in this sub because it’s not directly related to my code but more about python and how to turn it into an exe the proper way and possibly send it to someone? So if this isn’t allowed I’m sorry. I’m a beginner to python so as a small little project I made a quiz type game for my friends to try out and I could practice some python. I used pip and pyinstaller to turn my .py into a .exe but now I can’t for the life of me get my friends this file. Discord blocked it, gmail blocked it, I zipped it using regular zip and 7zip and tried uploading it to a google drive and sending them the link to it and it was blocked. They’re all flagging the file as a virus even though it’s just super basic python code and nothing malicious. How in the world can I get my friends this game? I know I could send them the .py but they’re not tech savvy and then they’d have to download python and I just know there has to be a way to do this. Thanks in advance!


r/pythonhelp • • Nov 29 '22

Need assist in creating python program that simulates a simple vending machine

3 Upvotes

I'm writing a script simulating a vending machine The program needs to be able to:

1.Display choices of snacks/drinks

2.State prices in malaysian ringgit (MYR)

3. Input money and calculate change return

4. Able to track inventory of the drinks and snacks remaining

5.Profits made from selling the snacks/drinks

________________________________________________________________________________________________________

I'm a total beginner at python and just started my Foundations in IT so this is the program i chose to try and a simulate for my end semester project. I chose a vending machine because it seemed like an interesting program to try and recreate .

I apologize but you have to treat me like I'm a total laymans. So far, I wrote a couple of lines that lists the amount of inventory I'm listing for sale and it's price. It's able to calculate change but at the moment it's not as comprehensive as I'd like.

I am aware that I need to create some kind of database to store all the information regarding inventory of snacks and drink types which I've no idea how to do

On top of that I also need help on writing a code that calculates a simulated input of cash and determine the amount of change it needs to return.

It should also be able to distinguish when it is deemed appropriate to return change in the form of either coins/notes. For example:Scenario 1:

Coke = 3 $ , Input money 4$ , Change 1$ in the form of 1$ notes

Scenario 2:Coke = 3.50$, Input money 10$ , Change: 6.50$ ( 1x5$ Note , 1x 1$ Note, 1x 0.50$ Coin)

Last but not least , the database that stores the data can be accessed using a certain passcode , which allows access to quantity of inventory sold / available plus profits/ revenue made total from price mockups.

Thank you so much in advance:

Here's some of the code I made so far.

https://pastebin.com/1rPd4d2e (Code properly formatted)


r/pythonhelp • • Nov 03 '22

Can't enter this SIMPLE case in a match statement

3 Upvotes
def on_press(key):
print(type(key))
x = str(key)
print (x, type(x))
match x:
    case 'w':
        print("stop")
        etc...

Output after pressing the 'w' key:

<class 'pynput.keyboard._win32.KeyCode'>
'w' <class 'str'>

No "stop" is printed, so it fails to enter the match case.


r/pythonhelp • • Oct 26 '22

what does that mean ?

3 Upvotes

what does x^=3 when x=5 mean ?

it evaluates to 6


r/pythonhelp • • Oct 25 '22

installing module proble.

3 Upvotes

Hi, this is so basic I feel foolish but I can't figure it out. I'm very new to python and I'm trying to install requests. I've tried both

python -m pip install requests

And

pip install requests

And

pip3 install requests

All give me an invalid syntax error and I am baffled.

Thanks!


r/pythonhelp • • Sep 30 '22

How do i parallelize this simple for loop?

3 Upvotes

I want to precompute a (symmetric) distance matrix to use it later for clustering with dbscan.

However already for a tiny 51x51 test matrix takes ~10min to calculate with the actual datasets i want to cluster being on the order of >2000 points which would take upwards of 10 days to compute.

Due to that i want to parallelize this if possible.

Currently the matrix is being build like this:

        precomputed = np.zeros((len(train_features), len(train_features)))
        for i in range(len(train_features)):
            logging.info(i)
            for j in range(i + 1, len(train_features)):
                precomputed[i][j] = self.trajectory_distance(
                    train_features[i], train_features[j], "geodesic"
                )
                precomputed[j][i] = precomputed[i][j]

I feel like this should be easily be parallelized using multiprocessing.pool but i seem to have a mental block right now.


r/pythonhelp • • Sep 06 '22

How to add a term to an equation in Sympy.

3 Upvotes

I have an equation in Sympy, lets say it is :

Eq(x + 2)
How would I add another term to this like lets say I wanted to add the term x^2 so the equation would be:

Eq(x**2 + x + 2)


r/pythonhelp • • Aug 16 '22

UndefinedVariable issue in code.

3 Upvotes

Currently unable to run code due to throwing an undefined variable error. The "mod_emp_list" is whats giving the error, I'm relatively new to programming and would appreciate the help or tips to getting this figured out. I also added a link to show what the issue as well.

def main():  
mod_emp_list = to_mod_list(employee_list)  
print("Modified employee list: " + mod_emp_list + "\n")
print(f"List of usernames: {generate_usernames(mod_emp_list)}\n")
print(f"Initials and ids: {map_id_to_initial(employee_list)}")
if __name__ == "__main__":  
main()  

https://imgur.com/a/0tfADyC


r/pythonhelp • • Aug 11 '22

How is it possible that my "Print" and "Return" values are different, even though they're one after another? (Recursive function)

3 Upvotes

I'm writing a program for a game where 'num' coins are flipped, making a string "HHTT", "HTT", "TTT", etc. If one is heads, they flip again.

For each tails, I get a certain amount of "netmana". I'm trying to find the total netmana produced after all of the flipping.

My issue is that when I print "mana" at the end of the function, it's incorrect. But the 'return' value of mana is correct.

The code is as follows ("multiflips" function flips coins 'num' times and makes a string "HHT", "TTHH", etc.):

def flipmana(num, netmana):
    z = 0
    lst = multiflips(num)
    for i in range(len(lst)):
        if lst[i] == 'T':
            z += netmana
    return z

def keepflipping(num, netmana):
    z = 0
    lst = multiflips(num)
    for i in range(len(lst)):
        if lst[i] == 'T':
            z += netmana
    if 'H' not in lst:
        print("Mana: ", z)
        return z
    else:
        z += keepflipping(num, netmana)
        return z

My issue is that the code gives me this (My coinflip function prints each time):

>>>keepflipping(3,2)

Heads
Heads
Heads
Heads
Heads
Heads
Tails
Heads
Tails
Tails
Heads
Tails
Tails
Tails
Tails
Mana: 6
14

There are 7 tails, which give 2 netmana each, for a total of 14 mana, which is correct in the return function. Why is the print value different, even though it's 1 line after it in the code?

I also did a version with global variables and the print value was correct while the return value isn't! How could this be possible? Isn't z the same on both lines?


r/pythonhelp • • Aug 03 '22

encoding and decoding in python

3 Upvotes

I'm working on an encoder and decoder. my encoder works well however I can't seem to figure out how to make the decoder work. My encoder works by finding each letter's number in the alphabet. EG a = 1, b =2 and then times that number by a random number which is generated using a random.random() and a random.seed(my numbers), it then gets the last number of this float and uses it to get a letter from the dict.

Can anyone help me figure out how to get the decoder to work, if any more code or description is required please let me know?


r/pythonhelp • • Jul 03 '22

How do I delete lines consecutively in a text file?

3 Upvotes

I have been trying to make a password saver for a generator, and I want to delete lines consecutively in the file. Here is some of my code:

if occ >= 1:rewrite = input("Would you like to rewrite the password for:"+ reason+ "?\n")if rewrite == "yes":f = open(reason, "a+")f.truncate(0)f.close()os.remove(f)shutil.move('C:/Python Practice/Password-Generator-30-01-22/'+reason, 'C:/Python Practice/Password-Generator-30-01-22/Password file folder and generator')`


r/pythonhelp • • Jun 21 '22

How do i invert the colours of a video in python?

3 Upvotes

I have to invert the colours of a video for class using python. Anybody know how to do that?

This is the code i have to use:

import cv2
import numpy as np

# read videofile
butterfly = cv2.VideoCapture("Butterfly.mp4")
fps = butterfly.get(cv2.CAP_PROP_FPS) # get fps from source file

# create new File
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
dimensions = (int(butterfly.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(butterfly.get(cv2.CAP_PROP_FRAME_HEIGHT))) # selbe größe wie Originalvideo
out_writer = cv2.VideoWriter("Results/Butterfly_inverted.mp4", fourcc, fps, dimensions)

while True:
ret, frame = butterfly.read()
if not ret:
break

#################################
# YOUR CODE STARTS HERE (b) #####
# Effect: Invert colours

# YOUR CODE ENDS HERE ###########
#################################

out_writer.release()


r/pythonhelp • • Jun 14 '22

I have problems with my app

3 Upvotes

Hi guys im trying to make a Special app for my girl, im new to programming thats why it seems so bad designed but i have this last problem where i get a message, that says

in SubirDatos

conn.execute('UPDATE USUARIOS set Horas = inthorasEstudiadas WHERE Usuario = nomUser ;')

sqlite3.OperationalError: no such column: inthorasEstudiadas

I just want to update the data i get from my buttons and then put it in the database, but i get these Traceback error

from cProfile import label
from distutils.cmd import Command
from tkinter import ttk
from tkinter import *
from tkinter import font
import sqlite3
from unittest import TestCase
root = Tk()
root.title("Tabloid")
root.geometry("1006x800")
root['background']='#b78c83'
#FilaConValores = " "
#FilasVisibles= ""
#Data Base Programming:
#c.execute("""CREATE TABLE USUARIOS
#            (Usuario text,
#             Horas integer)
#            """)
conn = sqlite3.connect('Tabloid.db')
c = conn.cursor()

conn.commit()
conn.close()

#Entry
NombreEntry = Entry(root, width= 20)
#NombreUsuario = "Hola Escribe Tu Nombre"
#funciones
def CrearCuenta():  
global c
global row8_1
global contadorHoras
row8_1 = Label(root, text= NombreEntry.get() , font=("Arial", 17), bg="#b78c83").grid(column = 1, row= 8 )
global usuarioName
#Crear conexion
usuarioName= NombreEntry.get()
conn = sqlite3.connect('Tabloid.db')
#Crear Cursor
c = conn.cursor()
contadorHoras = 0
#Meter a la base de datos cierto dato
c.execute("INSERT INTO USUARIOS VALUES (:Usuario, :Horas)",
                {
'Usuario': NombreEntry.get(),  
'Horas': contadorHoras
                })
#HACER EL CAMBIO
conn.commit()
horas= Label(root, text= contadorHoras, font=("Arial", 17), bg="#b78c83").grid(column = 1, row= 22 )
def ingresar_a_Cuenta():
global c
global conn
global row8_1
global horas
row8_1 = Label(root, text= NombreEntry.get() , font=("Arial", 17), bg="#b78c83").grid(column = 1, row= 8 )
global usuarioName

conn = sqlite3.connect('Tabloid.db')
#Crear Cursor
c = conn.cursor()
#Meter a la base de datos cierto dato
c.execute("SELECT Horas FROM USUARIOS WHERE Usuario = :Usuario", {'Usuario':NombreEntry.get() })
#print(c.execute("SELECT Horas FROM USUARIOS WHERE Usuario = :Usuario", {'Usuario':NombreEntry.get() }))
#HACER EL CAMBIO
global contadorHoras
contadorHorasList=(c.fetchall())
contadorHoras1 = contadorHorasList
contadorHoras12 = contadorHoras1[0]
contadorHoras123 = str(contadorHoras12)
print(contadorHoras123)
string = contadorHoras123
characters = "[].,-()#"
for x in range(len(characters)):
string = string.replace(characters[x],"")
contadorHoras=int(string)
print(contadorHoras)
conn.commit()
#CERRAR CONEXIÓN
horas= Label(root, text= contadorHoras, font=("Arial", 17), bg="#b78c83").grid(column = 1, row= 22 )

def SumarH():
global horasEstudiadas
global contadorHoras
global horas
horasntesdesumar = int(contadorHoras)
horasEstudiadas = str(horasntesdesumar+1)
contadorHoras += 1
horas= Label(root, text= horasEstudiadas, font=("Arial", 17), bg="#b78c83").grid(column = 1, row= 22 )

def RestarH():
global horasEstudiadas
global contadorHoras
global horas
try:
if contadorHoras >0:
horasntesdesumar = contadorHoras
horasEstudiadas = str(horasntesdesumar-1)
contadorHoras -= 1
horas= Label(root, text= horasEstudiadas, font=("Arial", 17), bg="#b78c83").grid(column = 1, row= 22 )

except:
return

horas= Label(root, text= horasEstudiadas, font=("Arial", 17), bg="#b78c83").grid(column = 1, row= 22 )

def SubirDatos():
global horasEstudiadas
global contadorHoras
global horas
global c
global conn
global row8_1
global horas
nomUser= str(NombreEntry.get())
inthorasEstudiadas= int(horasEstudiadas)
conn.execute('UPDATE USUARIOS set  Horas = inthorasEstudiadas  WHERE Usuario = nomUser ;')

conn.commit()
#CERRAR CONEXIÓN

horas= Label(root, text= '0', font=("Arial", 17), bg="#b78c83").grid(column = 1, row= 22 )
#Botones
boton_nombre= Button(root, text = "Crear Cuenta", padx=0, pady= 0, font =( "Arial", 17), bg= "#baaf9b",command= CrearCuenta)
boton_subirDatos= Button(root, text= 'Actualizar Datos', font= ('Arial', 17),bg= "#baaf9b", command = SubirDatos)
boton_menosH = Button(root, text= '-', font= ('Arial', 17) ,bg= "#baaf9b", command= RestarH)
boton_masH = Button(root, text= '+', font= ('Arial', 17),bg= "#baaf9b", command= SumarH)
boton_Ingresar = Button(root, text= 'Ingresar', font= ('Arial', 17),bg= "#baaf9b", command = ingresar_a_Cuenta )
#Visualizar Botones
boton_nombre.grid(column=1, row= 23, padx= 0, pady=0)

boton_subirDatos.grid(column= 1, row = 24)
boton_masH.grid(column= 2, row = 22)
boton_menosH.grid(column= 0, row = 22)
boton_Ingresar.grid(column= 2, row = 23)
#Creación de Interface
row0 = Label(root,text ="-------------------------------------------||--------------------------------------||-------------------------------------------",
font=("Arial", 17), pady="0", bg= "#b78c83")
row1 = Label(root,text ="-------------------------------------------||--------------------------------------||-------------------------------------------",
font=("Arial", 17), pady="0", bg= "#b78c83")
row2= Label(root, text= "||      Hola Me Llamo Tabloid      ||",
font=("Arial", 17), pady="0", bg= "#b78c83")
row3= Label(root, text= "            4 Horas = Chocolate            ||     Soy Tu Nuevo Ayudante     ||            8 Horas = Ida a Gym            ",
font=("Arial", 17), pady="0", bg= "#b78c83")
row4= Label(root, text= "||           Yo Opero De La            ||",
font=("Arial", 17), pady="0", bg= "#b78c83")
row5= Label(root, text= "||          Siguiente Manera           ||",
font=("Arial", 17), pady="0", bg= "#b78c83")
row6 = Label(root,text ="-------------------------------------------||--------------------------------------||-------------------------------------------",
font=("Arial", 17), pady="0", bg= "#b78c83")  
row7 = Label(root,text ="-------------------------------------------||--------------------------------------||-------------------------------------------",
font=("Arial", 17), pady="0", bg= "#b78c83")
row8 = Label(root,text ="   5 Horas = PapasEstilo  ",
font=("Arial", 17), pady="0", bg= "#b78c83")
row8_2 = Label(root,text =" 9 Horas = Mix Dulces",
font=("Arial", 17), pady="0", bg= "#b78c83")
row9 = Label(root,text ="-------------------------------------------||--------------------------------------||-------------------------------------------",
font=("Arial", 17), pady="0", bg= "#b78c83")
row10 = Label(root,text ="-------------------------------------------||--------------------------------------||-------------------------------------------",
font=("Arial", 17), pady="0", bg= "#b78c83")
row11= Label(root, text= "||           Por Cierto Tiempo         ||",
font=("Arial", 17), pady="0", bg= "#b78c83")
row12= Label(root, text= "||        De Estudio dedicado        ||",
font=("Arial", 17), pady="0", bg= "#b78c83")
row13 = Label(root,text= "6 Horas = PyC    ||        A la semana Puedes        ||   10 Horas = Tiramisu",  
font=("Arial", 17), pady="0", bg= "#b78c83")
row14= Label(root, text= "  ||   Conseguir premios     || ",
font=("Arial", 17), pady="0", bg= "#b78c83")
row15 = Label(root,text ="-------------------------------------------||--------------------------------------||-------------------------------------------",
font=("Arial", 17), pady="0", bg= "#b78c83")
row17= Label(root, text= "||            La Mejor Oferta            ||",
font=("Arial", 17), pady="0", bg= "#b78c83")
row18 = Label(root,text = '7 Horas = SorpresaCh     ||      Aprendes Y ganas algo      ||      20 = SorpresaG          '
,font=("Arial", 17), pady="0", bg= "#b78c83")
row19 = Label(root,text ="-------------------------------------------||                                                   ||-------------------------------------------"
,font=("Arial", 17), pady="0", bg= "#b78c83")
row20 = Label(root,text ="-------------------------------------------||--------------------------------------||-------------------------------------------",
font=("Arial", 17), pady="0", bg= "#b78c83")
#row22 = Label(root,text = "", bg= "#b78c83")

#Visualización Interface
row0.grid(column= 0,row=0, columnspan=3)
row1.grid(column= 0,row=1, columnspan=3)
row2.grid(column= 0,row=2, columnspan=3)
row3.grid(column= 0,row=3, columnspan=3)
row4.grid(column= 0,row=4, columnspan=3)
row5.grid(column= 0,row=5, columnspan=3)
row6.grid(column= 0,row=6, columnspan=3)
row7.grid(column= 0,row=7, columnspan=3)
row8.grid(column= 0,row=8)
row8_2.grid(column= 2,row=8)
row9.grid(column= 0,row=9, columnspan=3)
row10.grid(column= 0,row=10, columnspan=3)
row11.grid(column= 0,row=11, columnspan=3)
row12.grid(column= 0,row=12, columnspan=3)
row13.grid(column= 0,row=13, columnspan=3)
row14.grid(column= 0,row=14, columnspan=3)
row15.grid(column= 0,row=15, columnspan=3)
row17.grid(column= 0,row=17, columnspan=3)
row18.grid(column= 0,row=18, columnspan=3)
row19.grid(column= 0,row=19, columnspan=3)
row20.grid(column= 0,row=20, columnspan=3)
#row22.grid(column= 0,row=22)
NombreEntry.grid(column=0, row=23, padx=10, pady=10 )

root.mainloop()


r/pythonhelp • • May 26 '22

what python compilers should I use?

3 Upvotes

I am looking for a new IDE and Pycharm is very good, however If there are other IDE's please let me know.

*in this post "compilers" are the same as IDE


r/pythonhelp • • May 18 '22

SOLVED Infinite looping and integer trouble

3 Upvotes

This code is supposed to take a phrase and a integer and then firstly count how many words are in that phrase then count how many words in that phrase are of the same length of the integer inputted but the whole code has completely broken and now I need help

def Main():
    string=input("Enter string: ")
    list_o_words=string.split()
    length=int(input("enter an integer: "))
    Count_Words(string)
    Count_Words_of_Length(list_o_words,length)
    return string
def Count_Words(string):
    list_o_words=string.split()
    number_of_words=len(list_o_words)
    print(f'There are {number_of_words} words in your pharse')
def Count_Words_of_Length(list_o_words,length):
    string=Main()
    wordsthataresameaslength=0
    list_o_words=string.split()
    for words in list_o_words:
        wordcount=len(words)
        if wordcount==length:
            wordsthataresameaslength+=1
    print(f'There are {wordsthataresameaslength} of length {length} in your phrase')
Main()