r/PythonLearning • • May 04 '26

Help Request Can someone explain queues?

0 Upvotes

I have just learnt about queues, but what do we know if it is circular one or the general one? I mean how it is created or implemented. Could someone explain it?🙏🏻


r/PythonLearning • • Sep 10 '25

Help Request Terminal displpay question

Post image
1 Upvotes

Is my terminal supposed to look like this? I'm sorry if this is a stupid question, but I'd downloaded vscode back in like 2021 to learn C++, and I don't remember if maybe there's a setting I turned on or something.


r/PythonLearning • • Jun 11 '26

Discussion Biginner python project

0 Upvotes

items=\["milk","cheese","meat"\]

prices=\[10,100,230\]

for i in range(len(items)) :

print(f" {items\[i\]} - {prices\[i\]}")

ask=int(input("how many items do you wants to buy :"))

pick=\[\]

total=0

for n in range(ask) :

item=input("what item do you wants :")

pick.append(item)

position=items.index(item)

price=prices\[position\]

total+=price

print(total)


r/PythonLearning • • Jun 11 '25

Help

0 Upvotes

How to grant gthub access to read from clipboard? Like copy and paste? Please 🙏 Step by step. 🙌🙌


r/PythonLearning • • Jun 20 '25

Help Request To contextualized, I'm a new software student

Post image
1 Upvotes

I'm studying how to import Outlook messages from my computer. I've been watching a lot of videos but my code still doesn't work, I'm racking my brain to fix it. CAN SOMEONE GIVE ME A HINT, PLEASE??


r/PythonLearning • • Jun 01 '26

python learning

0 Upvotes

HOW DO I START TO LEARN PYTHON FROM ZERO? im planning to learn AI from scratch


r/PythonLearning • • Jun 17 '25

What is going on with my code?

0 Upvotes

I'm currently working on a python game where you have to hit targets to score points.There are firrerent kinds of targets,and one of them is the yellow target that is supposed to teleport a random number of times before being removed.However,when I hit a yellow target,it doesn't teleport and immediately gets removed instead.The score changes by the amount of "lives" the yellow target has,so I'm pretty suure the if closest[7] statement is still being fulfilled when checking for yellow targets.I also noticed that the yellow targets only stopped working correctly when I added the dark red ones (closest[8]).Could it be because there is a counter for both yellow and dark red targets in the target lists,both with index 9?Thank you in advance for your help.

import pygame
import random
import math
WIDTH,HEIGHT = 800,500
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Sniper game")
clock = pygame.time.Clock()
scorefont = pygame.font.SysFont("Helvetica",30,bold = True)
livesfont = pygame.font.SysFont("Helvetica",70,bold = True)
startgameins = pygame.font.SysFont("Helvetica",40,bold = True)
statsins = pygame.font.SysFont("Helvetica",40,bold = True)
gameoverfont = pygame.font.SysFont("Helvetica",60,bold = True)
highscorefont = pygame.font.SysFont("Helvetica",40,bold = True)
avgscorefont = pygame.font.SysFont("Helvetica",40,bold = True)
avgaccuracyfont = pygame.font.SysFont("Helvetica",40,bold = True)
gobacktomainmenufromstats = pygame.font.SysFont("Helvetica",30,bold = False)
gobacktomainmenufromgameover = pygame.font.SysFont("Helvetica",40,bold = True)
tutorialinstructions = pygame.font.SysFont("Helvetica",25,bold = False)
highscore = None
numoftimesplayed = None
with open("highscoreshootinggame.txt","a") as f:
   f.write("")
with open("allscores.txt","a") as f:
   f.write("")
with open("alltotalshots.txt","a") as f:
   f.write("")
with open("timesplayed.txt","a") as f:
   f.write("")
with open("highscoreshootinggame.txt","r") as f:
   try:
      highscore = int(f.read())
   except:
      highscore = 0   
with open("timesplayed.txt","r") as f:
   try:
      numoftimesplayed = int(f.read())
   except:
      numoftimesplayed = 0   
try:
 breaksound = pygame.mixer.Sound("shootsound.mp3")
 gameoversound = pygame.mixer.Sound("mariodeathsound.mp3")
 gameoversound.set_volume(0.8)
 breaksound.set_volume(0.7)
 snipermusic = pygame.mixer.music.load("backgrroundmusicsnipergame.mp3")
except Exception as e:
   print("Sounds not found or not loading")
   print(f"Error: {e}") 
rungame = True
def startscreen():
 global rungame
 startrun = True
 while startrun:
    screen.fill((0,0,0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            startrun = False
            rungame = False
            break
        elif event.type == pygame.KEYDOWN:
           if event.key == pygame.K_e or event.key == pygame.K_d:
              startrun = False  
              return event.key  
    startins = startgameins.render("Press E to start new game",False,(255,255,255))
    screen.blit(startins,(150,150))
    stats = statsins.render("Press D to view stats",False,(255,255,255))
    screen.blit(stats,(150,300))
    pygame.display.update()  
def stats():
   global rungame
   statsrun = True
   with open("highscoreshootinggame.txt","r") as f:
      highscore = int(f.read())
   with open("allscores.txt","r") as f:
      listofscores = f.read().split(" ")
   with open("alltotalshots.txt","r") as f:
      listoftotalshots = f.read().split(" ")
   avgscore = None
   avgaccuracy = None
   try:
    listofscores.pop(-1)
    listofscores = [int(value) for value in listofscores]
    avgscore = sum(listofscores)/len(listofscores)
   except:
    avgscore = 0
   try:
    listoftotalshots.pop(-1)
    listoftotalshots = [int(val) for val in listoftotalshots]
    avgshots = sum(listoftotalshots)/len(listoftotalshots)
    avgaccuracy = avgscore/avgshots
   except:
      avgaccuracy = "-"
    
      
   while statsrun:
      screen.fill((0,0,0))
      for event in pygame.event.get():
         if event.type == pygame.QUIT:
            statsrun = False
            rungame = False
            break
         elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
               statsrun = False
               break
      highscoretext = highscorefont.render(f"Highscore: {highscore}",False,(255,255,255))
      screen.blit(highscoretext,(200,50))
      avgscoretext = avgscorefont.render(f"Average score: {round(avgscore,2)}",False,(255,255,255))
      screen.blit(avgscoretext,(200,150))
      avgaccuracytext = avgaccuracyfont.render(f"Average accuracy: {round(avgaccuracy,2) if (isinstance(avgaccuracy,int) or isinstance(avgaccuracy,float)) else avgaccuracy}",False,(255,255,255))
      screen.blit(avgaccuracytext,(200,250))
      goback1 = gobacktomainmenufromstats.render("Press A to go back to the main menu",False,(255,255,255))
      screen.blit(goback1,(200,350))
      pygame.display.update()
def game():
 global rungame      
 run = True
 listoftargets = []
 score = 0
 onehundredandfifty = False
 fifty = False
 lives = 3
 totaltargets = 2
 shotsfired = 0
 x = -100
 y = -100
 click = False
 
 if not numoftimesplayed:
    runtutorial = True
    while runtutorial:
       screen.fill((0,0,0))
       for event in pygame.event.get():
          if event.type == pygame.QUIT:
             rungame = False
             runtutorial = False
             break
          elif event.type == pygame.KEYDOWN:
             if event.key == pygame.K_s:
                runtutorial = False
                break
       instructions1,instructions2,instructions3,instructions4,instructions5,instructions6,instructions7 = "Welcome to the sniping game.","Shoot targets to gain points.","If you miss out on a target,","you usually lose lives except if it's a green target.","But beware:some types might","be more dangerous than others...","Press S to continue"
       sentencelist = [instructions1,instructions2,instructions3,instructions4,instructions5,instructions6,instructions7]
       for i in range(7):
          ins = tutorialinstructions.render(sentencelist[i],False,(255,255,255))
          screen.blit(ins,(100,50+50*i))
       pygame.display.update()  
    with open("timesplayed.txt","w") as f:
       f.write("1")
 if rungame:
  pygame.mixer.music.play(loops = -1)
  pygame.mouse.set_visible(False)
  def spawninitialtargets():
    for i in range(2):
     listoftargets.append([random.randint(50,750),random.randint(50,450),0,False,False,False,False,False,False])
  spawninitialtargets()
  while run:
    
    clock.tick(60)
    screen.fill((0,0,0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            rungame = False
            run = False
            break
        elif event.type == pygame.MOUSEBUTTONDOWN:
            shotsfired += 1
            x,y = pygame.mouse.get_pos()    
            click = True
            breaksound.play()
    
    newlist = []   
    listofhits = []
    oldlistlength = len(listoftargets)   
    difference = 0.3+0.001*score if score < 200 else 0.5  
    for i in listoftargets:
        if i[4]: 
           coloroftarget = "green"
        elif i[5]:
           coloroftarget = (70,70,70)
        elif i[6]:
           coloroftarget = "dark green"
        elif i[7]:
           coloroftarget = "yellow"
        elif i[8]:
           coloroftarget = (150,0,50)
        else:
           coloroftarget = "red"
        #coloroftarget = "green" if i[4] else "red"
        for e in range(math.ceil(i[2]/10)):
         pygame.draw.circle(screen,coloroftarget if e%2 == 0 else "white",(i[0],i[1]),i[2]-10*e)   
        if i[2] < 50 and not i[3]:

            i[2] += difference if (i[2]+difference <= 50) else 50-i[2]
        else:
            i[3] = True
            i[2]-= difference if (i[2]-difference >=0) else i[2]
        if i[2] >0:
         if math.sqrt(abs(x-i[0])**2+abs(y-i[1])**2) > i[2]:   
            newlist.append(i)  
         else:
            listofhits.append(i)
        

        else:
            lives -= 1 if not (i[4] or i[5] or i[6]) else 0
            score -= 1 if lives > 0 else 0

    if lives < 1:
        run = False
        break        
    try:
     if click:
      closest = listofhits[0]

      for i in listofhits:
       if math.hypot(x - i[0], y - i[1]) < math.hypot(x-closest[0],y-closest[1]):

            closest = i   
      willdelete = None
      if closest[4]:
        lives += 1 if lives < 3 else 0 
        willdelete = True 
      if closest[5]:
        willdelete = True
        run = False
      if closest[6]:
         if 3 <= lives < 5:
            lives += 1
         elif lives < 3:
            lives = 3
         willdelete = True
      if closest[7]:
         willteleport = random.randint(0,1)
         if willteleport and closest[9] < 2:
            willdelete = False
            if 100 <= closest[0] <= 700:
               num1 = random.choice([-1,1])
               num2 = random.randint(0,50)
               closest[0] += (num1*num2)
            elif closest[0] <= 700:
               closest[0] += random.randint(0,50)
            else:
               closest[0] -= random.randint(0,50)
            if 100 <= closest[1] <= 400:
               num1 = random.choice([-1,1])
               num2 = random.randint(0,50)
               closest[1] += (num1*num2)
            elif closest[1] <= 400:
               closest[1] += random.randint(0,50)
            else:
               closest[1] -= random.randint(0,50)
            closest[0] = max(50, min(WIDTH - 50, closest[0]))
            closest[1] = max(50, min(HEIGHT - 50, closest[1]))
            closest[9] += 1
            score += 1
         else:
            willdelete = True
      if closest[8]:
       if closest[9] > 1:
        closest[9] -= 1
        willdelete = False
        score += 1
       else:
        willdelete = True
             
         
      else:
         willdelete = True
      if willdelete:
       listofhits.pop(listofhits.index(closest))
    except:
        pass 
    listoftargets = newlist + listofhits
    newlistlength = len(listoftargets)
    for i in range(oldlistlength-newlistlength):
        if score > 25:
         movingtarget = random.randint(1,100)
         if 1 <= movingtarget <= 5:
          listoftargets.append([random.randint(50,750),random.randint(50,450),0,False,True,False,False,False,False])
         elif 6 <= movingtarget <= 10 and score > 35:
          listoftargets.append([random.randint(50,750),random.randint(50,450),0,False,False,True,False,False,False])
         elif (11 == movingtarget or 12 == movingtarget) and score > 50:
            listoftargets.append([random.randint(50,750),random.randint(50,450),0,False,False,False,True,False,False])
         elif 13 <= movingtarget <= 17 and score > 75:
           listoftargets.append([random.randint(50,750),random.randint(50,450),0,False,False,False,False,False,True,3])
         elif 18 <= movingtarget <= 22 and score > 125:
            listoftargets.append([random.randint(50,750),random.randint(50,450),0,False,False,False,False,True,False,0])
         else:
          listoftargets.append([random.randint(50,750),random.randint(50,450),0,False,False,False,False,False,False])
        else:
           listoftargets.append([random.randint(50,750),random.randint(50,450),0,False,False,False,False,False,False])
        totaltargets += 1
    if run:
        score += (oldlistlength-newlistlength)
    scorelabel = scorefont.render(f"Score: {score}",False,(0,255,255))
    screen.blit(scorelabel,(600,40))
    liveslabel = livesfont.render("♥"*lives if lives < 3 else "♥"*3,False,(0,255,255))
    liveslabel2 = livesfont.render("♥"*(lives-3) if lives > 3 else "",False,(0,100,200))
    screen.blit(liveslabel,(50,20))      
    screen.blit(liveslabel2,(175,20))
    if score > 150 and not onehundredandfifty:
        listoftargets.append([random.randint(50,750),random.randint(50,450),0,False,False,False,False,False,False])
        onehundredandfifty = True
        totaltargets += 1
    elif score > 50 and not fifty:
        listoftargets.append([random.randint(50,750),random.randint(50,450),0,False,False,False,False,False,False])   
        fifty = True 
        totaltargets += 1
    click = False
    mousex,mousey = pygame.mouse.get_pos()
    pygame.draw.line(screen,(255,255,255),(mousex+4,mousey+4),(mousex-4,mousey-4),width = 2)
    pygame.draw.line(screen,(255,255,255),(mousex-4,mousey+4),(mousex+4,mousey-4),width = 2) 
    pygame.display.update() 
  runexit = True
  pygame.mixer.music.stop()
  pygame.mouse.set_visible(True)
  def enterdatatofiles():
   with open("allscores.txt","a") as f:
    f.write(str(score)+" ")

   with open("alltotalshots.txt","a") as f:
    f.write(str(shotsfired)+" ")
   if score > highscore:
    with open("highscoreshootinggame.txt","w") as f:
       f.write(str(score))
  enterdatatofiles()
  if rungame:  
   gameoversound.play() 
   while runexit: 
    screen.fill((0,0,0))
    for event in pygame.event.get():
     if event.type == pygame.QUIT:
        rungame = False  
        runexit = False
     elif event.type == pygame.KEYDOWN:
        if event.key == pygame.K_f:
          runexit = False   
    gameover = gameoverfont.render("GAME OVER",False,(255,255,255))
    screen.blit(gameover,(200,150))
    goback2 = gobacktomainmenufromgameover.render("Press F to continue",False,(255,255,255))
    screen.blit(goback2,(200,250))
    pygame.display.update()

def main():
   global rungame
   choice = None
   while rungame:
      if rungame:
         choice = startscreen()
      if rungame:
         if choice == pygame.K_e:
          game() 
         else:
            stats() 
main()         

r/PythonLearning • • Mar 11 '26

Switching from "PM Logic" to "Python Logic" (Day 3)

1 Upvotes

I've been a PM for 10 months and I'm now teaching myself Python to automate my project audits.

Today’s win was simple but effective: Chained comparisons. Using 1 <= days_past <= 3 instead of bulky and operators made my status-reporting script much more readable.

It's a small syntax shift, but it's helping me bridge the gap between high-level oversight and technical execution. Small wins compound. 🛠️


r/PythonLearning • • Sep 20 '25

Python Beginners team

1 Upvotes

python beginners lets team up on whatsapp and make learning easier and fun, Ghana on


r/PythonLearning • • Aug 07 '26

Python discord channel

1 Upvotes

Hey, I m learning python from scratch for machine learning, anyone have discord channel please share links.


r/PythonLearning • • Jun 28 '26

Comments

0 Upvotes

Why comments are important in python and how i know what i apply where


r/PythonLearning • • Mar 05 '26

Python Crash course- Urgent

1 Upvotes

Hi I am looking for people in India to teach me Python for data analysis, Pandas, Numbpy, loops and arrays.
I am ideally looking for someone to teach me in 2-3 days, and prepare me for interviews(ofcourse I will pay)

Thanks!


r/PythonLearning • • Aug 11 '26

picture review

Post image
1 Upvotes

if i use this kind of ai generated photos for linkdin posts, is that wrong😂???


r/PythonLearning • • Jun 28 '26

Advice

0 Upvotes

I am new in computer science . I have recently started python . Doing tutorial and small beginner steps . I am confused , it's too vast .

Please suggest me from your experience , how should i do it ?


r/PythonLearning • • Nov 12 '25

Tomorrow is my exam

1 Upvotes

Can y'all help me with this concept called inheritance I'm not understanding 😔


r/PythonLearning • • Jun 30 '26

Showcase MY first lil project :)

1 Upvotes

I've been learning Python for about 12 days now:

Note: I will add a try-except ValueError thingy and constraints for i,j to be within 0-2.


r/PythonLearning • • 17d ago

Help Request split() on empty string behaves differently when delimiter specified

1 Upvotes

Splitting an empty string without a specified delimiter works as expected and returns an empty list. However when splitting an empty string with a delimiter specified returns one (empty string) item in the list, is there some way to make that return an empty list as per the no-delimiter result?

print(f'{"".split()=}')         # = []
print(f'{"".split(" ")=}')      # = ['']
print(f'{"".split(",")=}')      # = ['']

Problem is this causes an unwanted iteration of a for loop:

str = ""
for item in str.split(" "):
    print(f"{item=}")    # unwanted item

r/PythonLearning • • Aug 19 '26

Need advice on solving complex arrow/maze puzzles using Computer Vision & Logic Solvers (Low accuracy issues)

Post image
0 Upvotes

Hi everyone,
I'm working on an automated solver for a complex arrow/maze puzzle game (similar to the image attached).
Here is my current workflow:

  1. Detection: I use a custom YOLO model to detect arrowheads and their bounding box coordinates from screen captures.

  2. Grid Mapping: I map the detected center coordinates of arrowheads onto a fixed grid system.

  3. Solving: I pass the grid data into a custom logic/emulator engine to calculate the correct sequence of moves (arrows to tap).
    The Main Problem:
    My solver accuracy is very low. Here are the core technical challenges I'm running into:
    Inaccurate Grid Mapping: The arrows are densely packed with varying paths and lengths. Snapping bounding boxes to a rigid fixed grid often misaligns the true position of the arrow shafts and heads.
    Complex/Overlapping Detection: Because the arrows bend and fold, YOLO often detects multiple arrowheads in the same calculated grid cell, or misinterprets arrow directions.
    Solver Logic Failure: Due to noisy input from the detection stage, the logic solver either fails to find a valid sequence or generates incorrect moves that block execution halfway through.
    Has anyone dealt with a similar vector/maze graph detection problem? What would be a more reliable approach than simple YOLO + fixed grid snapping? Should I look into contour analysis, OCR/graph traversal, or skeletonization algorithms (like Medial Axis Transform) to trace the paths directly?
    Any suggestions, code examples, or architectural advice would be greatly appreciated!


r/PythonLearning • • Aug 10 '26

Best way to package a Python/Streamlit app as an EXE without exposing the source code?

0 Upvotes

Hi all,

I'm relatively new to Python (still learning as I build wkwkwk).

I've developed an internal engineering tool using Python + Streamlit and currently package it with PyInstaller.

The application works fine, but the packaged output still contains the main.py file, meaning users can easily open and view the source code.

What's the recommended way to distribute a Streamlit application as an EXE while avoiding visible .py files?

I'm not looking for military-grade protection, just a practical way to prevent casual access or redistribution of the source code.

Any advice would be appreciated. Thankss


r/PythonLearning • • Jun 25 '26

Is Becoming A Python Developer Worth It In The AI Era? if yes along with python which stack is most important like sql , excel or etc .. if anyone plz help me thank you

1 Upvotes

r/PythonLearning • • Jul 08 '26

Help Request Need motivation for Learning Python

1 Upvotes

Well, I started learning Python from 7th June and its been 31 days and I haven't progressed past OOPs. I was slacking off in the first week, and then I put some effort in my 2nd and 3rd week and when i completed Methods and functions I created a Tic Tac Toe game which is easy but took me long enough. Now after that I took 3-4 days break due to some personal reasons and now I find myself demotivated, mainly beacuse my holidays are ending and college is going to start in August. I wanted to complete learning the absolute basics in these holidays. I feel very unproductive now, all I need is tips for me to get back to coding without feeling demotivating. And also I.m having a hard time understanding OOPs and why __init__ is used.

Thanks in advance!


r/PythonLearning • • Nov 27 '24

Code help

Post image
6 Upvotes

Hello, It would be very nice if someone helps me figure out this issue driving me nuts. I am coding a python mini project, and i am nearing the end. So far I managed to make a project with list, variables and it is supposed to be about a LED. It starts out by asking if you want to charge it, if not, color change, and if not still, then Brighten and Dim light. I’ve managed to finish the coding for brightening, as it ends, it gives an option to dim or restart. I only managed to make it work to dim down to 90% after reaching 100% brightness. After dimming to 90%, the rest won’t be read to keeping on the coding, it just stops.

I don’t have any indented errors or space. Please help me find out why. I also tried condensing the code by using Elif but for brightness it didn’t work or dimming, only for color change and charging options.

I am not sure if that is the issue. Below is what my code looks like at the end.

Please let me know if you need more pictures to show you whole code from beginning.


r/PythonLearning • • Aug 15 '26

Showcase Hey Guys!I am 14 and this is my first completely vibe coded banger python project...

Thumbnail
github.com
0 Upvotes

This is a python projects which takes your live camera, detects your nose and mouth, moves

The mouse pointer automatically with your nose... It also has a feature which stops the mouse if your mouth is open...

All the advices, criticisms accepted


r/PythonLearning • • Jun 11 '25

is int funtion nor working in vs?

Thumbnail
gallery
6 Upvotes

So i wrote this code If i put an integer as an input it works But if i put in any non integer it doesnt seem to work at all Shows this error Can anyone help me understand my mistake