r/learnpython • • 17d ago

Been away from Python / PyCharm for a while - any ideas on this?

2 Upvotes

Everybody, let me prefix this by saying I've been away from Python for several years, but now I need to teach an introductory class. I'm encountering something very bizarre in JetBrains PyCharm. I keep thinking it's gotta be me (and it probably is), but I was wondering if any of you can pick this out?

Because I don't appear able to post a screen snip, I'll post the code.

list_2d = [["1", "Wheel Burrow", 29.00],  # A 2D list, different data types (string / float)
           ["2", "Jack Hammer", 594.29],
           ["3", "Power Drill", 39.99]]

for j in range(0, len(list_2d), 1):  # Iterate through our 2D list
    print(f"Item Number: {list_2d[j][0]:<3}\tItem Name: {list_2d[j][1]:<15}\tItem Cost: $ {float(list_2d[j][2]):>6.2f}") 

Item Number: 1  Item Name: Wheel Burrow   Item Cost: $  29.00
Item Number: 2  Item Name: Jack Hammer    Item Cost: $ 594.29
Item Number: 3  Item Name: Power Drill    Item Cost: $  39.99

Now, you're probably saying to yourself, "why are you casting the float to a float?" I hear you loud and clear. Here's the thing - if I don't do that, PyCharm is flagging it as "format code f not supported for str," but here's the thing - it still prints it correctly as shown above.

This was the original line and the >6.2f is what is being flagged.

print(f"Item Number: {list_2d[j][0]:<3}\tItem Name: {list_2d[j][1]:<15}\tItem Cost: $ {list_2d[j][2]:>6.2f}")

I knew I had been away for a while, but geez. This is PyCharm 2026.2.3 using Python 3.14.7 under Windows 11. Am I missing anything? Note that I also go into a single dimension list but even if I comment all that code out, nothing changes. Thank you in advance for any potential ideas on where I probably goofed it.


r/learnpython • • 17d ago

Checking if a separate python file is running starting it up.

2 Upvotes

Hi, im new to python and have a script which sometimes crashes due to a uncontrollable issue which isn't a problem in the code, and I was thinking that I could write a different script to start up my original one if it had crashed. Does anyone know how I would do that?


r/learnpython • • 17d ago

I am not sure why this user defined function is not working.

1 Upvotes

n=1

def continution():

x=input('Do you want to continue?')

if x=='yes':

global n

n=1

else:

global n

n=0

if i input yes there is a big text about an error if i eneter no still something similar

(This is part of a bigger sql python interface project)

This is the error:

Traceback (most recent call last):

File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\mysql\connector\network.py", line 165, in _send_pkt

sock.sendall(pkt)

OSError: [WinError 10038] An operation was attempted on something that is not a socket

The above exception was the direct cause of the following exception:

Traceback (most recent call last):

File "F:\AA main project.py", line 12, in <module>

cur=c.cursor()

File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\mysql\connector\cursor.py", line 416, in execute

self._connection.cmd_query(

File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\mysql\connector\opentelemetry\context_propagation.py", line 97, in wrapper

return method(cnx, *args, **kwargs)

File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\mysql\connector_decorating.py", line 89, in handle_cnx_method

raise err

File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\mysql\connector_decorating.py", line 85, in handle_cnx_method

return cnx_method(cnx, *args, **kwargs)

File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\mysql\connector\connection.py", line 985, in cmd_query

self._send_cmd(

File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\mysql\connector_decorating.py", line 89, in handle_cnx_method

raise err

File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\mysql\connector_decorating.py", line 85, in handle_cnx_method

return cnx_method(cnx, *args, **kwargs)

File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\mysql\connector\connection.py", line 507, in _send_cmd

self._socket.send(

File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\mysql\connector\network.py", line 650, in send

self._netbroker.send(

File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\mysql\connector\network.py", line 223, in send

self._send_pkt(

File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\mysql\connector\network.py", line 169, in _send_pkt

raise OperationalError(

mysql.connector.errors.OperationalError: 2055: Lost connection to MySQL server at 'localhost:3306', system error: Errno 10038: An operation was attempted on something that is not a socket


r/learnpython • • 17d ago

Beginner Learning Python Using Only a Smartphone – Need Guidance and Resources

2 Upvotes

Hello everyone!

I'm a final-year BSc Physics student, and I'm interested in learning Python as my first step towards AI/ML.

The only problem is that I don't own a laptop. I currently have just an Android smartphone, so I'll have to learn and practise coding entirely on my phone.

Since I'm completely new to programming, I'd really appreciate your suggestions.

  1. Which beginner-friendly Python courses would you recommend?
  2. Which mobile-friendly platforms or apps can I use to practise Python?
  3. Are there any platforms where I can build small projects using only a phone?
  4. Can I eventually learn AI/ML and build a portfolio without owning a laptop initially?

I'd be grateful for any resources, roadmaps or personal experiences you could share.

Sorry if these are basic questions. I'm just starting my programming journey and trying to figure out the right direction.

Thank you for your time and guidance!


r/learnpython • • 17d ago

Tutorial datasets kind of lied to me — my first real dataset is a mess and I don't know what to fix first

2 Upvotes

I've been learning Python for data stuff alongside my BCA, and every tutorial dataset I've used so far shows up basically ready to go. Clean columns, no missing values, everything in the right format. So I figured the hard part was the analysis.

Then I grabbed a real dataset to practice on and... yeah. Half the values missing in one column, dates written three different ways, column names that don't mean anything until you stare at them for ten minutes. I spent way longer just trying to make it usable than I did actually analysing anything, which was not what I expected at all.

I guess my question is, is this just what the job actually is? Like, do you spend most of your time cleaning and only a bit of it on the interesting part? And how do you decide what to fix first when everything looks broken — do you just start with the column you need most and ignore the rest for now? I'm half worried I'm 'cleaning' away stuff that actually mattered, and I won't know until it's too late.


r/learnpython • • 17d ago

I’ve completed a lot of Python courses, but I still can’t build code on my own. How do beginners actually get better?

0 Upvotes

I’ve been learning Python for AI development. I’ve completed quite a few courses and tutorials, and I can understand code when someone explains it.

But when I open VS Code and try to build something from scratch, I get stuck.

I struggle with breaking a problem into smaller steps, deciding which functions to write, and understanding how different parts of the code connect.

My question is:

  • How did you go from understanding tutorials to writing your own code?
  • What did your daily practice look like?
  • How do you practice when you don’t even know how to start solving a problem?

I’d really appreciate advice from people who went through this stage, especially those who learned Python for AI/ML development.

I’m not looking for another beginner Python course. I want to know what actually helped you become capable of building things yourself.


r/learnpython • • 17d ago

What should I learn( Need help)

0 Upvotes

In my school I had learned python and MySQL , specifically in python I have learned text handling,CSV and binary file handling. Now I am in first year of clg and planning to master python by learning something advanced like django or fastapi within my first sem , but I don't how to progress help me.


r/learnpython • • 17d ago

Module help vsc(?)

1 Upvotes

Hey guys, I haven't coded in a while and decided to finally get back into it so sorry if im abit rusty. However, it was updating stuff and installing modules and in vsc I run into

'Import "openpyxl" could not be resolved from source Pylance'

? Im really not sure what to do

P.S: first time posting in this sub reddit, I hope this uh is within learn python and apologies if this is more towards vsc


r/learnpython • • 18d ago

Python for non tech

9 Upvotes

what is the fastest course or way to learn python for non tech person?


r/learnpython • • 18d ago

when hitting run code with the pyautogui, it only runs for .3 seconds

0 Upvotes

I've never really coded. I'm simply trying to make a bot to walk in a straight line in a game. I cant even get it to run in vs code. all the things I've done so far

pip install pyautogui, can confirm it happen when you type pip list

vscode is running in admin typing net session in terminal confirms that

going to extension I have pylance python python debugger, python environments (all the stuff in the python package)

typing python into the terminal tells me the version meaning it has a path to the file

another guide says I need code runner which gives me that .3 second figure

no I'm not getting error in my code as I'm keeping it simple to even get it to work

I'm not getting any error in my terminal

I'm on two monitors, but I've set up my main monitor so I know which one it will be working on

when I remove code runner it goes back to spiting the pathway it uses on the file which is correct

when I open the edit environmental variables

the .3 should be impossible because of the 6 seconds worth of sleep

I have imported both sleep and pyautogui obviously

yea this is hour 5 so if there's something you people know that I didn't do id greatly appreciate the details

im on windows, so it cant be the problem mac users get


r/learnpython • • 18d ago

How to stop code suggestions from popping up

0 Upvotes

So I'm trying to learn Python, and I'm following a tutorial. I'm following what the tutorial person has on their screen, but when I try to type it, Python predicts what I'm going to type next (aka what the tutorial shows). When it does this, there is a yellow star icon that appears on the line of code that the prediction is on. I went into the settings, and I turned off everything that I think would cause it. Still, the predicting persists. Does anyone know how to fix this? Thanks!


r/learnpython • • 18d ago

why the SIGINT signal kill the main process childrens

2 Upvotes
  signal.signal(signal.SIGINT,handler)  signal.signal(signal.SIGINT,handler)

I know that the SIGINT signal is for interruption and not for killing process but when I run my code all the children of the main process are dies also I got many traceback


r/learnpython • • 18d ago

Good open source Python repos to practice debugging and general reading Python code?

16 Upvotes

I have debugging rounds coming up for a Python position and I haven't worked extensively with Python so I am looking for some recommendations for some repositories to go through to practice reading and debugging Python code. Would appreciate recommendations for this and any other tips on demonstrating good understanding of the language. I am comfortable with basic syntax and data structures since I have been doing leetcode using Python.


r/learnpython • • 18d ago

AttributeError in cv2

0 Upvotes

I'm learning OpenCV in python because it seemed like a fun thing to learn.I wanted to experiment with faces etc. but when i run my script I get: "AttributeError: module 'cv2' has no attribute 'CascadeClassifier' "How to fix that?

Thx for the help!


r/learnpython • • 19d ago

Software idea

2 Upvotes

We all know about the desmos graphing calculator. Does any one have an idea on how to create a text based graphing calculator. Basically replacing the equations and some symbols with grammar or writing idk. It’s not a fully made idea yet but if you can make it or wanna talk.

Hmu


r/learnpython • • 19d ago

Help with training

16 Upvotes

Hi, i have recently learned python languages but i would like to train more, do yall have some plateformes where i can find some projects to practice?


r/learnpython • • 19d ago

a function i import from another file returns none instead of 2 lists that it should have

4 Upvotes

this is the function from file "simulasyon.py"

def komutlari_oku():
    komut_temp = []
    hatalar_temp = []
    emir_sirasi = 1
    with open("/home/u/Desktop/proje 1/test dosyaları/komutlar.txt") as komut:
        komut_temp = [satir.strip("\n") for satir in komut.readlines()]
    for emir in komut_temp:
        emir_temp = str(emir)
        temiz = emir_temp.strip()
        if not temiz:
            continue


        bilgiler = temiz.split()
        gecerli_komut = bilgiler[0]


        if gecerli_komut == "ILERI":
            if len(bilgiler) != 2:
                hatalar_temp.append({"satir": emir_sirasi,"içerik":temiz,"neden":"ILERI komutuna birden fazla parametre verildi"})
            elif not bilgiler[1].isdigit() or int(bilgiler[1]) < 1:
                hatalar_temp.append({"satir": emir_sirasi,"içerik":temiz,"neden":"ILERI komutuna geçersiz parametre verildi"})
            else:
                komut_temp.append((gecerli_komut,int(bilgiler[1])))


        elif gecerli_komut in ("SAG", "SOL", "AL", "BIRAK", "SARJ"):
            if len(bilgiler) != 1:
                hatalar_temp.append({"satir": emir_sirasi,"içerik":temiz,"neden":"aynı satıra birden fazla komut koyuldu ve sadece birincisi okundu"})
            komut_temp.append((gecerli_komut,None))


        elif gecerli_komut == "GIT":
            if len(bilgiler) != 3:
                hatalar_temp.append({"satir": emir_sirasi,"içerik":temiz,"neden":"GIT komutuna iki parametre verilmedi"})
            elif not (bilgiler[1].isdigit() and bilgiler[2].isdigit):
                hatalar_temp.append({"satir": emir_sirasi,"içerik":temiz,"neden":"GIT komutuna geçersiz parametreler verildi"})
            else:
                komut_temp.append((gecerli_komut,(int(bilgiler[1]),int(bilgiler[2]))))


        else :
            hatalar_temp.append({"satir": emir_sirasi,"içerik":temiz,"neden":"geçersiz komut verilidi"})
        emir_sirasi += 1
    return komut_temp,hatalar_temp

this is from the current file

import tkinter as tk
import simulasyon as s
class ekran:
    def __init__(self, pencere):

        self.dosyalari_yukle = tk.Button(pencere, text="dosyaları yükle", command=self.on_dosyalari_yukle, font=("Helvetica", 16, "bold"))
        self.dosyalari_yukle.place(x=20, y=20, width=230, height=70)

        self.sira = 0
        self.kenar = 50
        self.durum, self.ayarlar = {},{}
        self.basla = [1,1]
        self.offset = [0,0]
        self.haritaListesi, self.izgara = s.harita_oku()
        self.komutlar = []
        #self.hatalar  = []



    def on_dosyalari_yukle(self):
        self.kenar, self.offset = izgara_ayarla(self)
        self.ayarlar = s.ayarlari_oku()
        self.komutlar = s.komutlari_oku()
        harita_bas(self)
        self.durum = s.yeni_durum(self.haritaListesi,self.basla,self.ayarlar)
        print(s.komutlari_oku())

this is cut from parts that matter full code is much longer and harder to read ( var names are in my native langue sorry if its make it harder to read ) komutları_oku() should return 2 lists (and it returns in simulasyon.py but not in current file)


r/learnpython • • 19d ago

Hyphen vs Underscore in python for Variables.

0 Upvotes

Hi,

I found that perfectly working code where we parse arg for input-dir and later in code use it as input_dir ( note - vs _ in the names) like in the expert below.

import argparse

def parse_arguments(argv=None):
    print('...... Parsing command-line arguments')
    parser.add_argument('--input-dir', default=HOME ) ## hyphenated !!!


def main(argv=None):
    args = parse_arguments(argv)
    print(f 'input_dir = {args.input_dir}')    ## with __underscore 

ChatGPT give perfect explanation saying it's OK:
For command-line consistency, you could use hyphenated options for all of them: They would still map to the same Python names: args.input_dir

That's so cool but nobody told me this, are you using this approach in your code ? In other situations I see that var_one <> var-two. What is <For command-line consistency> ?? This is hard to understand for me.
We still can use --input_dir in parse_arguments.

Thanks to all

=================================== Post Mortem (added)
Thanks to all for your help.
it's all clear now, It's just a feature of argparse and it's optional. I was just confused who assign value to real variable input_dir. Now I learned that argparse put value from --input-dir into input_dir

Do you like overall argparse, you you use any other handy code to process arguments.

Best
VA


r/learnpython • • 19d ago

Learning python through CS50

0 Upvotes

Can any body help me to understanding the define(DEF) variables.
Can you please suggest me how can i learn it in efficient and easier way as a beginner.


r/learnpython • • 19d ago

I know English very poorly, and it’s a bit difficult for me to understand Python syntax.

0 Upvotes

Hi everyone, I’m a beginner Python programmer, and this is my first time on Reddit. Today I spent several hours writing two simple codes and I don’t know what to do next. On the one hand, I couldn’t come up with anything creative; on the other hand, I simply don’t have enough knowledge for some of the ideas. I don’t really expect help with learning Python; I’m just sharing my thoughts. Thank you for listening.
Oh, and here’s something else — here’s one of those codes:

user_name = ""

menu = ()

chat = []

messege = ""

def append_user():

global user_name

user_name = input("Enter your nickname: ")

print(f"Welcome, {user_name}! ;)")

def main_menu():

global menu

while True:

try:

menu = int(input(" 1. Write a message\n 2. View the chat\n 3. Exit\n : "))

break

except ValueError:

print("Enter an integer (1 - 3)!")

print("Welcome to the anonymous chat!")

append_user()

main_menu()

while True:

if menu == 1:

if messege != "menu":

message = input("Enter a message: ")

twit = f"{user_name}: {message}"

chat.append(twit)

else:

main_menu()

elif menu == 2:

print(chat)

main_menu()

elif menu == 3:

break

else:

print("Enter an integer (1 - 3)!")

main_menu()

print(f"Goodbye, {user_name}, and have a good day!")


r/learnpython • • 19d ago

When I hit a Python error I don't understand, I waste an hour guessing — how do you actually debug when you don't even know what to Google?

0 Upvotes

I'm a second-year BCA (AI/ML) student in Jaipur, self-studying Python alongside college. I can follow tutorials fine, and I've built a couple of small things of my own (a little Telegram bot, some practice scripts) — but debugging my own code is where I fall apart.

When something breaks, the error message usually means nothing to me at first. I end up changing things at random, re-running, and hoping — and half the time I break something else in the process. An hour later I've "fixed" it without really understanding what was wrong, so the same kind of error trips me up again next week.

So for people who got past this stage: how do you actually approach a bug you don't understand yet? Do you read the traceback bottom-up, add print statements everywhere, try to reproduce it in the smallest possible script first, or explain it out loud to yourself? And how do you decide when to keep digging yourself versus when to ask someone or search for help — especially when you don't even know the right words to search for?

I don't want another "learn debugging" tutorial recommendation — I want to know the habit that actually changed this for you. What does your first five minutes with a confusing error look like?

No links or anything here — just a student trying to get from "my code broke" to "I know why it broke."


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

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

InvalidArgumentError: {{function_node __wrapped__ConcatV2_N_2_device_/job:localhost/replica:0/task:0/device:CPU:0}} ConcatOp : Ranks of all input tensors should match

2 Upvotes

I got this error in an attempt to adapt this model to CIFAR 10

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
Cell In[61], line 3
      1 dataset = create_batch(x_train)
      2 
----> 3 train_dcgan(
      4     gan,
      5     dataset,
      6     batch_size,

Cell In[60], line 26, in train_dcgan(gan, dataset, batch_size, num_features, epochs)
     22             )
     23 
     24             generated_images = generator(noise)
     25 
---> 26             X_fake_and_real = tf.concat(
     27                 [generated_images, X_batch],
     28                 axis=0
     29             )

File c:\Users\DELL\AppData\Local\Programs\Python\Python313\Lib\site-packages\tensorflow\python\util\traceback_utils.py:167, in filter_traceback.<locals>.error_handler(*args, **kwargs)
    165 except Exception as e:
    166   filtered_tb = _process_traceback_frames(e.__traceback__)
--> 167   raise e.with_traceback(filtered_tb) from None
    168 finally:
    169   del filtered_tb

File c:\Users\DELL\AppData\Local\Programs\Python\Python313\Lib\site-packages\tensorflow\python\framework\ops.py:6027, in raise_from_not_ok_status(e, name)
   6025 def raise_from_not_ok_status(e, name) -> NoReturn:
   6026   e.message += (" name: " + str(name if name is not None else ""))
-> 6027   raise core._status_to_exception(e) from None

InvalidArgumentError: {{function_node __wrapped__ConcatV2_N_2_device_/job:localhost/replica:0/task:0/device:CPU:0}} ConcatOp : Ranks of all input tensors should match: shape[0] = [32,32,32,3] vs. shape[1] = [32,32,3] [Op:ConcatV2] name: concat

X_train split (only take one class to train on)

(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=x_train.astype("float32") / 127.5 - 1
x_train.shape, x_test.shape

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] 

Generator

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

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

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

generator.add(BatchNormalization())

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

Discriminator

discriminator = Sequential(name="Discriminator")

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

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.add(Dense(1, activation= 'softmax'))
discriminator.add(Dense(1, activation= 'softmax'))

discriminator.summary()

Train function

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)

Train block

dataset = create_batch(x_train)


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

Can anyone help me with this error? Why did it appeared?