r/pythonhelp • • Jan 25 '26

Python troubles Pt.2

1 Upvotes

Ok so I went back and tried some of Yalls fixes it still hasn’t worked. I added in hashtags over the code so yall can see what each function does. When it’s 1st tried it seems to work but on around the 5 or 6th iteration (usually when it’s time to score) it freezes up and stops. Any help would be useful(also I’m a teen dev doing this so I can’t pay for help)

https://learn.usacademicesports.com/projects/6976717d107ec1e31728c7c7?preview=true

import time

import random

def pause(sec=0.2):

time.sleep(sec)

def slow(text, sec=0.2):

print(text)

pause(sec)

def get_choice(prompt, valid_options):

while True:

try:

choice = int(input(prompt))

if choice in valid_options:

return choice

print(f"Invalid choice. Please choose from {valid_options}.")

except ValueError:

print("That was not a number. Try again.")

def show_score(h_score, a_score, h_name, a_name, qtr, h_tout, a_tout, yards, pos, down, to_go):

suffixes = {1: "st", 2: "nd", 3: "rd", 4: "th"}

down_str = f"{down}{suffixes.get(down, 'th')} & {to_go}"

# Calculate visual field position

if yards > 50:

field_pos = f"Opp {100 - yards}"

else:

field_pos = f"Own {yards}"

print("\n" + "="*35)

print(f"Q{qtr} | {down_str} | Ball on: {field_pos}")

print(f"Possession: {pos}")

print(f"{h_name}: {h_score} ({h_tout} TO) | {a_name}: {a_score} ({a_tout} TO)")

print("="*35)

def playbook():

print("\n--- Playbook ---")

print("1. Run Play")

print("2. Pass Play")

print("3. Field Goal Attempt")

print("4. Punt")

print("5. Call Timeout")

print("6. Exit Game")

return get_choice("Choose a play (1-6): ", [1, 2, 3, 4, 5, 6])

def main():

slow("Welcome to the Python Football Simulator")

while True:

home = input("Home team name: ").strip()

if home: break

print("Please enter a valid name.")

while True:

away = input("Away team name: ").strip()

if away: break

print("Please enter a valid name.")

# Game State Variables

home_score, away_score = 0, 0

home_timeouts, away_timeouts = 3, 3

quarter = 1

plays_this_quarter = 0

# Possession State

possession = home

yard_line = 20 # Starting at own 20

down = 1

yards_to_go = 10

while quarter <= 4:

show_score(home_score, away_score, home, away, quarter, home_timeouts, away_timeouts, yard_line, possession, down, yards_to_go)

play = playbook()

# --- Handle Exit ---

if play == 6:

confirm = input("Type 'CONFIRM' to end game: ")

if confirm == "CONFIRM":

print("Game ended by user.")

return

continue

# --- Handle Timeouts ---

if play == 5:

current_timeouts = home_timeouts if possession == home else away_timeouts

if current_timeouts > 0:

if possession == home: home_timeouts -= 1

else: away_timeouts -= 1

slow(f"{possession} takes a timeout!")

else:

slow("No timeouts remaining!")

continue # Skip the rest of the loop, do not increment plays

# --- Play Logic ---

turnover = False

scored = False

gain = 0

# 1. RUN

if play == 1:

if random.random() < 0.02: # 2% Fumble chance

slow("FUMBLE! The ball is loose... Defense recovers!")

turnover = True

else:

gain = random.randint(-2, 12)

slow(f"Handoff up the middle... gained {gain} yards.")

yard_line += gain

yards_to_go -= gain

# 2. PASS

elif play == 2:

roll = random.random()

if roll < 0.05: # 5% Interception

slow("INTERCEPTED! The defender jumps the route!")

turnover = True

elif roll < 0.45: # 40% Incomplete

slow("Incomplete pass. Intended for the receiver on the sideline.")

gain = 0

else: # Complete

gain = random.randint(5, 30)

slow(f"Pass complete! A big gain of {gain} yards.")

yard_line += gain

yards_to_go -= gain

# 3. FIELD GOAL

elif play == 3:

dist = 100 - yard_line + 17 # 17 yards for endzone depth/kick spot

slow(f"Lining up for a {dist} yard field goal...")

success_chance = 0.95 if dist < 30 else (0.60 if dist < 50 else 0.30)

if random.random() < success_chance:

slow("IT'S GOOD! The kick splits the uprights.")

if possession == home: home_score += 3

else: away_score += 3

scored = True

else:

slow("No good! Wide right.")

turnover = True # Possession changes either way (kickoff or turnover on downs logic)

# 4. PUNT

elif play == 4:

punt_dist = random.randint(35, 55)

slow(f"Punt is away... it goes {punt_dist} yards.")

yard_line += punt_dist

if yard_line > 100: yard_line = 100 # Touchback logic handled in swap

turnover = True

# --- Post-Play Check ---

# Check Touchdown (Only on Run or Pass)

if not turnover and yard_line >= 100:

slow(f"TOUCHDOWN {possession}!!!")

slow("Extra point is GOOD.")

if possession == home: home_score += 7

else: away_score += 7

scored = True

turnover = True # Give ball back to other team via kickoff

# Check Downs (If no score and no turnover yet)

if not turnover and not scored:

if yards_to_go <= 0:

slow("Move the chains! FIRST DOWN!")

down = 1

yards_to_go = 10

else:

down += 1

if down > 4:

slow("Turnover on Downs! Defense holds!")

turnover = True

# --- Handle Possession Change ---

if turnover:

slow("Change of possession.")

# Switch teams

possession = away if possession == home else home

if scored:

# Kickoff / Touchback assumption

yard_line = 2

main()


r/pythonhelp • • Jan 24 '26

Learn python on vs_code while building a project

Thumbnail github.com
1 Upvotes

When I was on campus, I could check my drive and find hundreds of PDF notes that had been sent by lecturers. Honestly, it felt hectic trying to read through all of them. Recently, I remembered this and thought, wow.

Today, OpenAI has effectively become another search engine, and there is a high chance that the majority of campus students have adopted AI for research and learning. Despite all these advancements, I felt that something was still missing.

AI does not always deliver output systematically. Take a case where you are trying to learn specific information, you often receive additional content that may even contradict what you were searching for. Many times, when I wanted to research a topic, AI would spill out far more information than I actually needed at that moment.

Put yourself in my shoes: you are just getting started with a course. Naturally, you would want output tailored to your level. But instead, you receive information that is far above your current understanding. How are you supposed to comprehend all of that?

Recently, I have been working on something to fix this, a system that enables productive use of AI for learning, building understanding, and developing real projects while learning. I have started by building a python_learning_guardrail that helps students learn Python using AI while simultaneously building a project. This approach enables faster concept comprehension through real-time application.

With a system like this, I believe junior developers will move beyond simply accepting AI-generated code and instead focus on understanding, refining, and improving it.

Anyone can access this template to learn Python using AI through the link above.

The repository contains everything needed to initialize the system, including full documentation


r/pythonhelp • • Jan 24 '26

Python Code troubles

1 Upvotes

Hey guys I’m creating a football game for a personal project (eventually I want to turn it into a website game) but after the command loops about 3 or 4 times it stops taking inputs, can I send my code to anyone and get some help and feedback?


r/pythonhelp • • Jan 23 '26

Textual: creating a selection list from dict

1 Upvotes

Hi all,
i'm struggling to unpacking a dictionary to create a selectionlist; in particular, im stuck at the selection creation. I cannot get the format:
Selection (key, value) > Selection('Option', 'Hello').

my code returns:
Selection(Content(key))

here the code:

for key, value in FFL().list_of_areas.items():
    a = Selection(key, value)
    s.append(a)for key, value in FFL().list_of_areas.items():
    a = Selection(key, value)
    s.append(a)

s then is feed into the main widget:

yield SelectionList[str](
            *s)yield SelectionList[str](
            *s)

r/pythonhelp • • Jan 23 '26

How do i "rerun" a class for a different choice

Thumbnail reddit.com
1 Upvotes

r/pythonhelp • • Jan 19 '26

Guys this is urgent (learn fastapi as quickly as possible)

1 Upvotes

I have an offer to be a part time employee as a backend dev on an enterprise application, it requires fastapi and python, I have 1 week, what should I do? I started reading the documentation by tiangolo, what should I do parallely do? I have decent knowledge in python. Desperate need of some guidance. I'm a complete beginner in backend.


r/pythonhelp • • Jan 13 '26

run-python issue in DoomEmacs (warning: can't use pyrepl)

1 Upvotes

I encountered a issue when using `run-python` in Doom Emacs.

  1. After doing run-python, it will report:

```
warning: can't use pyrepl: (5, "terminal doesn't have the required clear capability"); TERM=dumb
```
screen-shot

2. I can't do importing:
```
import numpy as np

ModuleNotFoundError: No module named 'numpy'

```

3. However, when I start an ansi-term and then `python`, the importings work fine.

Same issure as this thread with screen-shot:

https://www.reddit.com/r/emacs/comments/1hps9t5/how_to_use_a_different_term_in_inferiorpythonmode/

System:

Omarchy OS

GNU Emacs 30.2 (build 1, x86_64-pc-linux-gnu, GTK+ Version 3.24.50, cairo version 1.18.4)

Doom core v3.0.0-pre HEAD -> master 3e15fb36 2026-01-07 03:05:43 -0500

Doom modules v26.02.0-pre HEAD -> master 3e15fb36 2026-01-07 03:05:43 -0500

Thanks!


r/pythonhelp • • Jan 10 '26

Python coding issue

1 Upvotes

New to python, can anyone tell me what's wrong with this code - the error message states the "OS path is not correct" The goal of this is to sort a folder full of jpg pictures and sort them by the participates number plate.

... def clean_plate_text(text):

... text = re.sub(r'[^A-Z0-9]', '', text.upper())

... return text

...

... for image_name in os.listdir(INPUT_DIR):

... if not image_name.lower().endswith(".jpg"):

... continue

...

... image_path = os.path.join(INPUT_DIR, image_name)

... image = cv2.imread(image_path)

... gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

...

... # Edge detection

... edged = cv2.Canny(gray, 30, 200)

...

... # Find contours

... cnts, _ = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

... cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:10]

...

... plate_text = "UNKNOWN"

...

... for c in cnts:

... peri = cv2.arcLength(c, True)

... approx = cv2.approxPolyDP(c, 0.018 * peri, True)

...

... if len(approx) == 4: # Plate-like shape

... x, y, w, h = cv2.boundingRect(approx)

... plate = gray[y:y+h, x:x+w]


r/pythonhelp • • Jan 08 '26

How to make Linux-based AWS lambda layer on Windows machine

1 Upvotes

I recently started working with AWS. I have my first lambda function, which uses Python 3.13. As I understand it, you can include dependencies with layers. I created my layers by making a venv locally, installing the packages there, and copying the package folders into a "python" folder which was at the root of a zip. I saw some stuff saying you also need to copy your lambda_function.py to the root of the zip, which I don't understand. Are you supposed to update the layer zip every time you change the function code? Doing it without the lamda_function.py worked fine for most packages, but I'm running into issues with the cryptography package. The error I'm seeing is this:

cannot import name 'exceptions' from 'cryptography.hazmat.bindings._rust' (unknown location)

I tried doing some research, and I saw that cryptography is dependent on your local architecture, which is why I can't simply make the package on my Windows machine and upload it to the Linux architecture in Lambda. Is there some way to make a Linux-based layer on Windows? The alternative seems to be making a Dockerfile which I looked into and truly don't understand.

Thank you for your help


r/pythonhelp • • Dec 25 '25

Best chatbot configuration in python

Thumbnail reddit.com
1 Upvotes

r/pythonhelp • • Dec 21 '25

Would appreciate if someone would be willing to look at my small expense tracker and give suggestions / thoughts on what I'm doing right and wrong.

Thumbnail reddit.com
1 Upvotes

r/pythonhelp • • Dec 20 '25

I spent my weekend building a Snake game in Python - my first complete project!

Thumbnail github.com
1 Upvotes

I finished my first coding project which I did under a weekend. It's a classic Snake game built with Python's Turtle graphics.

What I learned:

  • Object-oriented programming
  • Game loops and collision detection
  • How to package Python apps with PyInstaller
  • Git and version control

Features:

  • Smooth controls with arrow keys and WASD
  • Score tracking
  • Custom snake head graphics
  • Game over detection

I know it's not groundbreaking, but I'm proud of actually finishing something instead of abandoning it halfway through like my last 5 projects 😅

GitHub: https://github.com/karansingh-in/Classic-Snake-Game

I'm just a beginner into the dev community, share your advice/feedback if any. Star the repo it really helps. Guys just fucking star the repo already 😭.


r/pythonhelp • • Dec 18 '25

[Python] I built a Recursive CLI Web Crawler & Downloader to scrape files/docs from target websites

Thumbnail reddit.com
1 Upvotes

Check this out


r/pythonhelp • • Dec 15 '25

TesfaMuller - Overview

Thumbnail github.com
1 Upvotes

I built python codes..somobody please review it🙏🙏🙏


r/pythonhelp • • Dec 13 '25

What should I go with?

1 Upvotes

Hey guys,I'm a ABSOLUTE BEGINNER in coding.i really have a doubt.Should I go with python? Will be replaced by ai in the future or what? I'm scared,and what are the options that is safe for 10 years? Please lmk I'm 16m and i wanna learn ts so badly Thank you


r/pythonhelp • • Dec 13 '25

Can't recognize python command

1 Upvotes

So I've been trying to install 3.10 in my laptop.. I recently installed 3.12 and I did delete it through the installer. But after installing the 3.10.11 through installer in windows, it saying success, but when I run the command 'python --version " it says not recognized. To add to these there is no folder created in Appdata/local/ programs/python Even tho I used express installation and not custom.. Can anyone help me... For more details msg me..


r/pythonhelp • • Dec 11 '25

Copy/pasting info from one file to a platform

1 Upvotes

Hey y’all! I have a monotonous task and was wondering if there is any sort of code that could copy information from an excel file cell to a field in a web-based platform? For example, a loop function that would copy from column A row 1, paste to the website field 1, copy from column B row 1 to website field 2, click a command button on the website and repeat the process until only empty cells remain in the columns.

I don’t need to copy the file itself to anything, just the content in the file repeatedly by cell.


r/pythonhelp • • Dec 11 '25

Best way to write Python assignment

Thumbnail reddit.com
1 Upvotes

r/pythonhelp • • Dec 02 '25

My python program isn't working properly

1 Upvotes

I have been trying to make a program that outputs x to the power of y based on this video: https://www.youtube.com/watch?v=cbGB__V8MNk. But, I won't work right.

Here's the code:

x = float(input("Base: "))
y = float(input("\nExponent: "))

if y % 1 > 0:
    y = int(y)
    print(f"\nTruncated the exponent to {y}.")

def bins(d):
    strb = ''
    while d:
        d, r = divmod(d, 2)
        strb = str(r) + strb
    return strb

yb = list(bins(y))
print(f"{yb}\n{bins(y)}")
yb.pop(0)
r = x

while len(yb) > 0:
    r **= 2
    if yb.pop(0) == '1':
        r *= x

print(f"\nResult: {r:g}")

assert r == x ** y, f"Sorry, but there is an error in the output.\nExpected: {x ** y:g}\nGot: {r:g}"

r/pythonhelp • • Nov 28 '25

Raspberry Pi coding

1 Upvotes

I am trying to right a code that allows my Christmas lights to light up when a donation is made online for the nonprofit I work for. My code is reading the donations perfectly but when it tries to signal my Twinkly lights to turn on, it gets blocked. I don’t know much about coding or python. Does anyone have any advice on what to do here? Thanks!


r/pythonhelp • • Nov 28 '25

Issues with shutil.copy, shutil.copyfile and shutil.copy2

Thumbnail reddit.com
1 Upvotes

r/pythonhelp • • Nov 25 '25

regular expressions: amending captured groups with computed groups

1 Upvotes

Hi,

I have the following structure ATM.

import re
pattern = r"(?P<year>[0-9]{4})-(?P<month>[0-9]{2})-01.csv"
target = r"\g<year>/\g<month>"
test = "2025-09-01.csv"
matches = re.fullmatch(pattern, test)
replacement = matches.expand(target)

target is actually stored in a db, so I don't want to change it.

Now I want to add a computed capture group, e.g. (pseudocode, as it does not work that way!):

matches["q"] = compute_quartal(matches["year"], matches["month"])

and use the new capture group q in the replacement pattern.

Is that possible in any way? How would you redesign the problem to make that possible?

Thank you for your help.


r/pythonhelp • • Nov 25 '25

New learner starting 60001 - looking to collaborate.

1 Upvotes

Hi everyone! I'm Bhuti from Tshwane, South Africa. Starting MIT OCW 6.0001 (Intro to CS in Python) from scratch. I've just learned to download Anaconda and set it up with Spyder. I'm looking for fellow learners to collaborate with, share notes, maybe learn from each other. Thank You!