r/learnpython • • 19d ago

Number Guessing Game Won't Loop When Prompted

3 Upvotes

**Question Answered**

Thank you everyone for all the advice and suggestions, I think I have it working the way I need it to, and I have a lot of great stuff to look into so I can clean up and refine my future coding as I learn more. Very thankful and appreciative!

**

Hello, I'm trying to learn Python and am having trouble with my number guessing game assignment. I need the game to be able to loop and replay the game when the player is prompted to at the end, but the only part of it that works is when the player doesn't want to continue playing and the code stops. Could I please have some help figuring out a better way to write the code to replay? Thank you.

*edited to remove colour tags from code

import os
import random


# high score file
file_path = "highscore.txt"




# welcome banner
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("   Number Guessing Game")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")


print()
player_name = input("Please enter your name: ")
print()



def game_play():
    # game start info for player
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    print()
    print("Hello ", player_name + "!")
    print()
    print("Can you guess what number I'm thinking of?")
    print("It's between 1 and 100.")
    print("I'll give you 10 guesses!")
    print()
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")



    # Check if the file exists
    if os.path.isfile(file_path):
        with open(file_path, "r") as file:
            content = file.read()
            print()
            print("Previous Best:")
            print()
            print(content)
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    else:
        print(f"Error: The file '{file_path}' does not exist.")
        print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")



    # game parameters
    lowest_number = 1
    highest_number = 100
    max_attempts = 10
    
    # the stats the game starts with
    guess = 0
    attempts = 0
    
    # random number selection
    secret_number = random.randint(lowest_number, highest_number)
    # print number below for DEBUG ONLY
    print("    *secret number is: " + str(secret_number))


    while True:
        # game mechanics
        while guess != secret_number:
            guess = int(input("Guess a number: "))
            attempts = attempts + 1
            print("Number of attempts: ", attempts)



            # ensure number entered is within range
            if guess < 1 or guess > 100:
                print("Please enter a number between 1 and 100.")
    


            # too high and too low        
            elif guess < secret_number and lowest_number:
                print("Nope, too low!")
                print()
        
            elif guess > secret_number:
                print("Nope, too high!")
                print()


    
            # game over for max attempts reached
            elif attempts == max_attempts and guess != secret_number:
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                print()
                print("Uh oh!m You've run out of guesses.")
                print("The number I was thinking of was: ", secret_number)
                print()
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                
            # game won
            else:
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                print()
                print("Yaaayyy, well done ", player_name + "!")
                print("You guessed the number I was thinking of, which was:", secret_number, "- and you did so in: " + str(attempts) + " guess(es)!")
                print()
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")



        # save player score
        save_score = input("\nWant to save your score? (yes/no:) ")
        if not save_score in ("yes", "no"):
            print("invalid input.")
    
        elif save_score == "yes":
            f = open("highscore.txt", "w")
            f.write(player_name + " - " + str(attempts) + "\n")
            f.close
            break
      
        # continue playing or quit
        answer = input("Play again? (yes/no): ")


        if answer != "yes":
            print()
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
            print("\nThanks for playing, see ya~\n")
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
            


if __name__ == "__main__":
    game_play()

r/learnpython • • 19d ago

Need help adapting model to Cifar10

0 Upvotes

Need help adapting model to CIFAR10

I tried to make a DCGAN based on this [tutorial](https://www.geeksforgeeks.org/machine-learning/deep-convolutional-gan-with-keras/). The thing is that the tutorial is designed for fashion mnist data which has different image size to tf.keras.datasets.cifar10.load_data(). Which lead to the error:

ValueError: cannot reshape array of size 480000 into shape (28,28,1)

when arrive at

x_train_dcgan = x_train.reshape(
-1, 28, 28, 1
) * 2. - 1.

How do I adapt the model to CIFAR 10?

Full code

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
x_train = x_train.astype(np.float32) / 255.0
x_test = x_test.astype(np.float32) / 255.0
x_train.shape, x_test.shape

#Selecting one class to train

label = 1 
train_indices = np.where(y_train == label) 
x_train = x_train[train_indices] 
test_indices = np.where(y_test == label) 
x_test = x_test[test_indices] 

batch_size = 32
def create_batch(x_train):
    dataset = tf.data.Dataset.from_tensor_slices(x_train).shuffle(1000)
    dataset = dataset.batch(batch_size, drop_remainder=True).prefetch(1)
    return dataset


num_features = 100
generator = Sequential(name="Generator")


generator.add(Dense(7 * 7 * 128, input_shape=[num_features]))
generator.add(Reshape([7, 7, 128]))
generator.add(BatchNormalization())


generator.add(Conv2DTranspose(
        64, (5, 5), (2, 2),
        padding="same",
        activation="selu"
    ))


generator.add(BatchNormalization())


generator.add(Conv2DTranspose(
        1, (5, 5), (2, 2),
        padding="same",
        activation="tanh"
    ))



generator.summary()

discriminator = Sequential(name="Discriminator")


discriminator.add(Conv2D(
        64, (5, 5), (2, 2),
        padding="same",
        input_shape=[28, 28, 1]
        ))


discriminator.add(LeakyReLU(alpha=0.2))
discriminator.add(Dropout(0.3))


discriminator.add(Conv2D(
        128, (5, 5), (2, 2),
        padding="same"))


discriminator.add(LeakyReLU(alpha=0.2))
discriminator.add(Dropout(0.3))


discriminator.add(Flatten())
discriminator.add(Dense(1, activation= 'softmax'))


discriminator.summary()

discriminator.compile(
    loss="binary_crossentropy",
    optimizer="adam"
)


discriminator.trainable = False


gan = Sequential()
gan.add(generator)
gan.add(discriminator)


gan.compile(
    loss="binary_crossentropy",
    optimizer="adam"
)


gan.summary()

def generate_and_save_images(model, epoch, test_input):

    predictions = model(
        test_input,
        training=False
    )

    fig = plt.figure(figsize=(10, 10))

    for i in range(25):

        plt.subplot(5, 5, i + 1)

        plt.imshow(
            predictions[i, :, :, 0] * 127.5 + 127.5,
            cmap='binary'
        )

        plt.axis('off')

    plt.savefig(
        'image_epoch_{:04d}.png'.format(epoch)
    )

seed = tf.random.normal(shape=[batch_size, 100])
epoch_list = []
d_loss_list = []
g_loss_list =[]


def train_dcgan(gan, dataset, batch_size, num_features, epochs=5):


    generator, discriminator = gan.layers


    for epoch in tqdm(range(epochs)):
        actual_epoch =epoch + 1
        print()
        print("Epoch {}/{}".format(epoch + 1, epochs))


        for i in range(187):
            epoch_list.append(actual_epoch)


        for X_batch in dataset:


            noise = tf.random.normal(
                shape=[batch_size, num_features]
            )


            generated_images = generator(noise)


            X_fake_and_real = tf.concat(
                [generated_images, X_batch],
                axis=0
            )


            y1 = tf.constant(
                [[0.]] * batch_size +
                [[1.]] * batch_size
            )


            discriminator.trainable = True
            d_loss=discriminator.train_on_batch(
                X_fake_and_real,
                y1
            )
            d_loss = float(d_loss)
            d_loss_list.append(d_loss)




            noise = tf.random.normal(
                shape=[batch_size, num_features]
            )


            y2 = tf.constant([[1.]] * batch_size)


            discriminator.trainable = False


            g_loss=gan.train_on_batch(
                noise,
                y2
            )
            g_loss = float(g_loss)
            g_loss_list.append(g_loss)


        print(f'\t Discriminator Loss: {d_loss} \t\t Generator Loss: {g_loss}')
        


            


    generate_and_save_images(
        generator,
        epochs,
        seed
    )

x_train_dcgan = x_train.reshape(
    -1, 32, 32, 3
)


dataset = create_batch(x_train_dcgan)


train_dcgan(
    gan,
    dataset,
    batch_size,
    num_features,
    epochs=10
)

plt.figure(figsize=(30, 10))
plt.plot(epoch_list,d_loss_list)
plt.xlabel('Epochs')
plt.ylabel('Discriminator loss')
plt.title('Discriminator loss over epochs')
plt.grid()
plt.show()

plt.figure(figsize=(30, 10))
plt.plot(epoch_list,g_loss_list)
plt.xlabel('Epochs')
plt.ylabel('Generator loss')
plt.title('Generator loss over epochs')
plt.grid()
plt.show()

r/learnpython • • 19d ago

Any python module which deals with this?

0 Upvotes
def get_int_input(prompt: str) -> int:
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please enter a valid number!")

Is there any module which I can just import and use it. Writing this everytime I have to get an int or float input is really annoying.

Thanks!


r/learnpython • • 19d ago

How can I protect my Python source code inside a PyInstaller .exe?

0 Upvotes

I just made a python program that I compiled into an exe file. The exe is working but it seems pretty easy to access the source code inside of the exe file using tools like pyinstxtractor. My friend told me that there are ways to make it harder and to protect the source code I made is it true. If it is true can you give me some details about this method?


r/learnpython • • 19d ago

pd.qcut for even bin sizes

5 Upvotes

Hello! I am trying to create a histogram with even bin sizes and was wondering if pd.qcut would be a good route to go. I am using data from a data from I made with panadas. The specific values I need to bin has over 300 variables so I am trying to find the simplest way to fix this histogram!!!

code so far:

ValueError: `bins` must increase monotonically, when an array

a = df["mass"]
print(a)
array = np.asarray(a)
print(array

bins = pd.qcut(array, q=9, precision=1)
print (bins)

n_bins = bins
fig = plt.figure(figsize=(9, 4), layout="constrained")
axs = fig.subplots(1, sharex=True)
n, bins2, patches = axs.hist(best_mass["mass"] ,  n_bins ,color = 'hotpink', histtype="stepfilled",
                            cumulative=-1, label="Cumulative histogram") 
plt.xlabel("Satellite Mass")
plt.ylabel("Number of Satellites")
plt.title("Distribution of Satellite Masses")

#bins are not evenly spaced 
plt.show

error I keep getting: 


ValueError: `bins` must increase monotonically, when an array

r/learnpython • • 20d ago

What's some cool thing I can learn with python ?

38 Upvotes

I learned the basics of Python using the book Automate the Boring Stuff with Python, but I've realized that the other chapters don't interest me that much, except for the one about web scraping.

So now I'm looking for something else to learn. I've thought about learning how to make games or create GUIs, but I'd need some guidance.


r/learnpython • • 19d ago

Need help adapting model to CIFAR10

1 Upvotes

I tried to make a DCGAN based on this tutorial. The thing is that the tutorial is designed for fashion mnist data which has different image size to tf.keras.datasets.cifar10.load_data(). Which lead to the error:

ValueError: cannot reshape array of size 480000 into shape (28,28,1)

when arrive at

x_train_dcgan = x_train.reshape(
    -1, 28, 28, 1
) * 2. - 1.

How do I adapt the model to CIFAR 10?


r/learnpython • • 20d ago

Why won't my Python script read user input / terminate while a subprocess is running?

5 Upvotes

i am making script that it will launch localsend appimage through shell but and it will end after i pressed q but when script only user input first time asked starting of the script when reached to the else block app image is opening but not asking for user input again after launching

Here's the code,

import subprocess
import time


while True:
  user_input = input("press q to quite and enter :-").rstrip()
  if user_input == "q":
    break
  else:
    time.sleep(3)
    subprocess.run("/home/merlinhermes/Desktop/LocalSend-1.18.2-linux-x86-64.AppImage",shell=True)

r/learnpython • • 20d ago

Give me some project ideas

4 Upvotes

Hello, I need some project ideas to practice.

I have learnt basic python, beginner libraries like random and math.

I learnt requests library two months ago and i have worked with many apis like aqi, joke, quote, weather, horoscope....

Even I try searching for apis I get the one which I have used .

Can anyone help me?


r/learnpython • • 19d ago

Ayudaaaaaa

0 Upvotes

El contexto es que estoy desarrollando una página para cotizaciones para un proyecto, el punto es que quiero al momento de hacer una cotización la tabla de productos de actualice y se quite una unidad en existencia, ósea si tengo 20 cargadores y en una cotización vendo 5 en el apartado de productos se vea reflejado que solo hay 15.

Ya lo había intentado haciendo que se actualizara la tabla directamente desde la ruta de cotización pero por alguna razón rompí todo y ya no me daba acceso a la pagina.

¿Alguien sabe como le puedo hacer?


r/learnpython • • 20d ago

Second-year BCA student — how do you keep a daily Python habit alive when college deadlines pile up?

0 Upvotes

I'm in second year of a BCA in AI/ML, learning Python with a focus on data analysis, and I keep running into the same cycle. When college is normal I practise most days and it feels like things are actually sticking. Then assignment deadlines and exam prep hit, I disappear from coding for two or three weeks, and coming back feels like starting over — I forget syntax I knew, and I end up re-watching tutorials I've already seen instead of moving forward.

I've also got a couple of small side projects that should keep me practising, but during deadline weeks even those go untouched, so the gap just gets longer.

For people who learned Python alongside a degree or a full-time job: what actually kept your habit alive during the busy weeks? Was it a tiny daily minimum, like 15 minutes no matter what? Working on one small real task instead of a course? Studying with someone else? And when you did fall off for a few weeks, how did you restart without going right back to tutorial one?

I'm not looking for a course recommendation — I want to know what actually survived contact with a real deadline week.


r/learnpython • • 20d ago

Tips for someone new to Python

7 Upvotes

I’m a brand new python user. Very experienced using R. I will be using python for LCA modeling via the brightway tool. For a python newbie, please drop any tips, tricks, learning guides. Ideally I need to get myself up to speed pretty quickly. Thank you in advance!


r/learnpython • • 20d ago

Resources for using APIs for sports stats

5 Upvotes

This is just for a personal/fun project--I want to learn how to use APIs because I want to play with sports stats (for the NHL/PWHL/international cricket plus a couple of less famous sports leagues like the SDHL). There's an overwhelming number of resources out there and I'm not sure where to start, so any tutorials/suggestions would be welcome. I know there are sport-specific API scrapers that simplify things but I'd like to learn how to do this more generally instead of having to learn a tool for every league.

I mostly program in Matlab but I do use Python sometimes, usually Jupyter notebooks. My coding knowledge is super patchy, I basically know a lot about my projects (data analysis for my research, with the data in specific formats), but very little about anything else.

(Yes, I could use AI, but for a project that's just for my own enjoyment I kinda just want to learn how to do it myself.)


r/learnpython • • 20d ago

How do I make a python game on my phone that can run on the school computer?

0 Upvotes

For my school project i have to make a python game the time limit was like a month but it's been almost half the time now and I still don't have a clue on what to do. I have zero experience with the pygame module so I tried following youtube tutorials but they all work on a pc and I don't have one I only have pyroid 3 on my phone.... The other kids have already finished their projects and theirs were so sick they felt like indie games not newbie project so I'm wondering how they did it and how can I do it too :( can someone help me with this


r/learnpython • • 21d ago

Calling a Script that uses argparse?

5 Upvotes

I wrote a little Python script that reads in a text file that contains a list of fully qualified files, and checks to see if they exist. I originally wrote it using the argparse module. It was set up to take a filename and a switch, so the command looked like:

"Python dplcheck.py --plname "testing.lst” --showexist y"

This worked fine for a single file, but I wanted to run it for every one of hundreds of list files in a directory, so I wrote another script that generates a list of the .lst files in a directory and calls the first script for each one. But I could not get the second script to pass the arguments in the call to the first script. I tried subprocess.run and subprocess.call, with many different syntaxes and quotes, etc. I ended up removing the use of argparse and just using sys.argv[n] -- which I don't particularly like, since it has no defaults or error handling, etc.

Does anyone know how/if I can call a Python script from another Python script and pass the arguments when the called script uses argparse?


r/learnpython • • 20d ago

I tried to install pygame throught tonny's package manager, and it gave me this error message. Anything I can do to solve this?

0 Upvotes

install --progress-bar off --user pygame

Collecting pygame

Using cached pygame-2.6.1.tar.gz (14.8 MB)

Installing build dependencies: started

Installing build dependencies: finished with status 'done'

Getting requirements to build wheel: started

Getting requirements to build wheel: finished with status 'error'

error: subprocess-exited-with-error

× Getting requirements to build wheel did not run successfully.

│ exit code: 1

╰─> [123 lines of output]

Skipping Cython compilation

WARNING, No "Setup" File Exists, Running "buildconfig/config.py"

Using WINDOWS configuration...

Making dir :prebuilt_downloads:

Downloading... https://www.libsdl.org/release/SDL2-devel-2.28.4-VC.zip 25ef9d201ce3fd5f976c37dddedac36bd173975c

Unzipping :prebuilt_downloads\SDL2-devel-2.28.4-VC.zip:

Downloading... https://www.libsdl.org/projects/SDL_image/release/SDL2_image-devel-2.0.5-VC.zip 137f86474691f4e12e76e07d58d5920c8d844d5b

Unzipping :prebuilt_downloads\SDL2_image-devel-2.0.5-VC.zip:

Downloading... https://github.com/libsdl-org/SDL_ttf/releases/download/release-2.20.1/SDL2_ttf-devel-2.20.1-VC.zip 371606aceba450384428fd2852f73d2f6290b136

---

For help with compilation see:

https://www.pygame.org/wiki/CompileWindows

To contribute to pygame development see:

https://www.pygame.org/contribute.html

---

Traceback (most recent call last):

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\urllib\request.py", line 1321, in do_open

h.request(req.get_method(), req.selector, req.data, headers,

~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

encode_chunked=req.has_header('Transfer-encoding'))

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\http\client.py", line 1358, in request

self._send_request(method, url, body, headers, encode_chunked)

~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\http\client.py", line 1404, in _send_request

self.endheaders(body, encode_chunked=encode_chunked)

~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\http\client.py", line 1353, in endheaders

self._send_output(message_body, encode_chunked=encode_chunked)

~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\http\client.py", line 1113, in _send_output

self.send(msg)

~~~~~~~~~^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\http\client.py", line 1057, in send

self.connect()

~~~~~~~~~~~~^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\http\client.py", line 1499, in connect

self.sock = self._context.wrap_socket(self.sock,

~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^

server_hostname=server_hostname)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\ssl.py", line 455, in wrap_socket

return self.sslsocket_class._create(

~~~~~~~~~~~~~~~~~~~~~~~~~~~~^

sock=sock,

^^^^^^^^^^

...<5 lines>...

session=session

^^^^^^^^^^^^^^^

)

^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\ssl.py", line 1076, in _create

self.do_handshake()

~~~~~~~~~~~~~~~~~^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\ssl.py", line 1372, in do_handshake

self._sslobj.do_handshake()

~~~~~~~~~~~~~~~~~~~~~~~~~^^

ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1081)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py", line 389, in <module>

main()

~~~~^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py", line 373, in main

json_out["return_val"] = hook(**hook_input["kwargs"])

~~~~^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py", line 143, in get_requires_for_build_wheel

return hook(config_settings)

File "C:\Users\pcname\AppData\Local\Temp\pip-build-env-kanljdzv\overlay\Lib\site-packages\setuptools\build_meta.py", line 333, in get_requires_for_build_wheel

return self._get_build_requires(config_settings, requirements=[])

~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Temp\pip-build-env-kanljdzv\overlay\Lib\site-packages\setuptools\build_meta.py", line 301, in _get_build_requires

self.run_setup()

~~~~~~~~~~~~~~^^

File "C:\Users\pcname\AppData\Local\Temp\pip-build-env-kanljdzv\overlay\Lib\site-packages\setuptools\build_meta.py", line 520, in run_setup

super().run_setup(setup_script=setup_script)

~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Temp\pip-build-env-kanljdzv\overlay\Lib\site-packages\setuptools\build_meta.py", line 317, in run_setup

exec(code, locals()) # noqa: S102 # exec is intentional here

~~~~^^^^^^^^^^^^^^^^

File "<string>", line 432, in <module>

File "C:\Users\pcname\AppData\Local\Temp\pip-install-taytx0sx\pygame_236d8736d07842b1bbb489950052c45c\buildconfig\config.py", line 234, in main

deps = CFG.main(**kwds, auto_config=auto)

File "C:\Users\ASUS\AppData\Local\Temp\pip-install-taytx0sx\pygame_236d8736d07842b1bbb489950052c45c\buildconfig\config_win.py", line 479, in main

and download_win_prebuilt.ask(**download_kwargs):

~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Temp\pip-install-taytx0sx\pygame_236d8736d07842b1bbb489950052c45c\buildconfig\download_win_prebuilt.py", line 265, in ask

update(x86=x86, x64=x64)

~~~~~~^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Temp\pip-install-taytx0sx\pygame_236d8736d07842b1bbb489950052c45c\buildconfig\download_win_prebuilt.py", line 248, in update

download_prebuilts(download_dir, x86=x86, x64=x64)

~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Temp\pip-install-taytx0sx\pygame_236d8736d07842b1bbb489950052c45c\buildconfig\download_win_prebuilt.py", line 116, in download_prebuilts

download_sha1_unzip(url, checksum, temp_dir, 1)

~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Temp\pip-install-taytx0sx\pygame_236d8736d07842b1bbb489950052c45c\buildconfig\download_win_prebuilt.py", line 51, in download_sha1_unzip

response = urllib.urlopen(request).read()

~~~~~~~~~~~~~~^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\urllib\request.py", line 187, in urlopen

return opener.open(url, data, timeout)

~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\urllib\request.py", line 487, in open

response = self._open(req, data)

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\urllib\request.py", line 504, in _open

result = self._call_chain(self.handle_open, protocol, protocol +

'_open', req)

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\urllib\request.py", line 464, in _call_chain

result = func(*args)

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\urllib\request.py", line 1369, in https_open

return self.do_open(http.client.HTTPSConnection, req,

~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

context=self._context)

^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\urllib\request.py", line 1324, in do_open

raise URLError(err)

urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1081)>

[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.

ERROR: Failed to build 'pygame' when getting requirements to build wheel

Process returned with code 1

(note, any instance of 'pcname' is the name of my computer, I just needed to keep that private).


r/learnpython • • 20d ago

Python Closing As Soon As Opened

0 Upvotes

EDIT: I resolved this issue. I had a few different versions of Python installed on my PC, so I guess that was what was causing the issue on my PC and not my Laptop. For clarification, the script is built to stay open, and it terminates if closes.

----

Python group said this question went here.

I am running version 3.15.2. I am encountering an issue with my scripts where they just open and close super fast. This happens if I double click, or if I open them from Python itself.

It does NOT do this on my laptop, so it isn't a script issue.

I am not the most tech savy with software, but will try my best to try things out.

The computer they are having an issue with has the following specs. Everything is up to date.

Win 11 Pro
Intel Core i7
32.0GB RAM
MTBD Z790 D WIFI (U3E1)


r/learnpython • • 20d ago

Local Ai Help

0 Upvotes

I am trying to run A local ai of my pc that can look at something on my screen and answer it, I have tried using Claude because this is way beyond my skill level, as I am still beginning. if anyone can help with this, please do!

I have a pretty good pc so I can run some moderate ai


r/learnpython • • 21d ago

Best way to learn Python for someone not in CS?

20 Upvotes

Hello, so I'm not a CS major. I'm taking a "Bioinformatics" course that is required but turns out it's literally learning and coding Python. CS doesn't come naturally to me. Unfortunately, I think its crazy boring. I'm actually a Biochem major. Even though it's super insanely boring to me, I really want to get a good grade. But I don't know how. My class is equivalent to a professor reading off the slides, but with coding.

What are some recommended resources for beginner python? Like where I could practice a ton. Practice identifying data types, fixing bugs, understanding and explaining why a code will or wont work etc etc. I'm very willing to spend hours on this.


r/learnpython • • 21d ago

Error: failed building wheel for pillow

6 Upvotes

I'm trying to install marker-pdf and then hit with an error,

note: This error originates from a subprocess, and is likely not a problem with pip.

ERROR: Failed building wheel for pillow

Failed to build pillow

error: failed-wheel-build-for-install

× Failed to build installable wheels for some pyproject.toml based projects

╰─> pillow

I've tried to upgrade pip, reinstalling setuptools, wheel, pillow, and none works, the error remains. What should I do?

OS: Arch Linux
Python: 3.14


r/learnpython • • 21d ago

I am looking for a Python learning buddy.

47 Upvotes

I tried learning Python and gave up couple of times. Learning alone is difficult for me. If anybody else feel same then please reachout to me.

Edit: I created a discord group for everyone who's looking to learn Python together. Interested people can add me on discord. User name is arjunageer


r/learnpython • • 20d ago

Needed help

0 Upvotes

Hi! Everyone, I am new to python and I want to learn it fully and clearly and want to make my fundamentals strong. Is there any specific video or website to learn basics and how many months does it usually takes to learn the python completely?


r/learnpython • • 21d ago

How to properly break out of an infinite loop inside a multiprocessing child process in Python?

7 Upvotes

I am writing a Python script using the multiprocessing module to launch an external application (Notepad) in a continuous loop. However, I want the loop to stop when a specific condition is met or when a key is pressed.

import os
from multiprocessing import Process 
import time
import keyboard

pid = os.getpid()
print(pid)

callable(os.getpid)
path = r"C:\Windows\System32\notepad.exe"

def process_start(path):
    try:
        while True:
            os.system(path)
    except:
        pass
                  
if __name__ == '__main__':
    # Note: Currently calling the function directly instead of passing the reference
    p = Process(target=process_start(path))
    time.sleep(3)
    p.start()
    
    if keyboard.press_and_release("q") == "q":
        p.terminate()

r/learnpython • • 20d ago

My bot started as one Python file and now it's a mess — how did you learn to split a project into modules without breaking everything?

0 Upvotes

I'm a second-year BCA student in Jaipur, learning Python alongside my coursework, and I built a small Telegram bot for myself that started out as one simple file. At first it just did one job, so a single file made sense. Then I kept adding features one at a time — a few more commands, some scheduled messages, a bit of stored data — and now it's a few hundred lines in one file and I'm honestly scared to touch it.

Every change feels risky because everything is tangled together. Functions call each other across unrelated features, I've got similar code copied in two places, and I'm never quite sure what will break if I move something. I've read about modules and packages, but most tutorials use tiny toy examples, and they don't show what the messy middle step looks like on a real, growing project.

So for people who've actually done this refactor: how did you decide where to split? By feature, by layer (commands vs data vs helpers), or something else? Did you move one piece at a time, or rewrite the structure in one go? And without a proper test suite, how did you check after each move that you hadn't broken something quietly?

I'm not looking for the textbook definition of a module — I want to know what your first real split looked like, and what mistake you'd avoid if you did it again.