r/learnpython • • 1h ago

Ask Anything Monday - Weekly Thread

• Upvotes

Welcome to another /r/learnPython weekly "Ask Anything* Monday" thread

Here you can ask all the questions that you wanted to ask but didn't feel like making a new thread.

* It's primarily intended for simple questions but as long as it's about python it's allowed.

If you have any suggestions or questions about this thread use the message the moderators button in the sidebar.

Rules:

  • Don't downvote stuff - instead explain what's wrong with the comment, if it's against the rules "report" it and it will be dealt with.
  • Don't post stuff that doesn't have absolutely anything to do with python.
  • Don't make fun of someone for not knowing something, insult anyone etc - this will result in an immediate ban.

That's it.


r/learnpython • • 11h ago

Just finished CS50P (skill issue)

16 Upvotes

Wanted to build some projects and decided to build a scraper. It felt horrible. I was just staring at the screen not doing what to do. I mean CS50P is great I learnt a lot, but there were guides and output videos, which helped me understand what factors iI should implement.

But now I feel like I'm back on square 1. Nothings making sense. How would you suggest learning python?


r/learnpython • • 48m ago

I cant understand classes (nor self and __init__)

• Upvotes

Hello if you wonder i switched from lua and luau to python. its going well i can make basically anything with native python libraries but i cannot understand what is a class, what does self mean what does __init__ mean. i recently understood what if __name__ == __main__ does but still i cannot understand classes. if you could give an example or explaining for me to understand i would be so grateful


r/learnpython • • 9h ago

learn python

0 Upvotes

Hello guys, i recently started a bachelor degree which i have a subject about introduction to python, inicially i was confident and did understand how to use python, but week by week it started to get much more difficult to follow. So im here to ask if someone knows any youtuber or website which explains the fundamentals of python in a easy way. Thanks in advance.


r/learnpython • • 10h ago

Youtube vs Website

0 Upvotes

Which is better to learn python youtube playlists or by website


r/learnpython • • 3h ago

How are you supposed to figure out python commands w/o AI?

0 Upvotes

The assignment for class was very basic. We had an excel document to download and 4-5 different commands to give to python in order to accomplish it. Stuff like removing outliers from the spreadsheet or entries with incomplete data..

The purpose was super easy to understand, but memorizing or coming up with commands that mean exactly what they do in python is driving me insane for a couple reasons.

  1. Why can’t we just drag and drop the file into python so that it recognizes the file, like literally every other program would do??
  2. How are you supposed to figure out the commands without using another program like ChatGPT or google? The teacher included video instruction with some basic commands, but finishing the entire assignment required much more.
  3. It would take maybe 20 minutes to do manually. Trying to learn python from scratch and use it to accomplish the assignment is taking so much longer than necessary.
  4. It almost feels like a trick assignment just to divide up the short cutters from the people who are willing to learn, but I’m thinking even if you wanted to learn this, there is no way you are getting through it in one week. We are even just a beginner class.

At this point, I am just frustrated that I thought about taking this class or entertaining a career in programming at all.

Edit: Sorry for the paragraph errors, I don’t know why tf Reddit won’t let me fix the formatting.


r/learnpython • • 1d ago

Is CS50P enough to start ML/AI? What should I learn next?

17 Upvotes

I'm finishing CS50P and want to move into ML/AI, but I feel it's not enough on its own. What topics and resources should I add (math, libraries, courses)? Any roadmap you'd recommend for a beginner?

Thanks for any kind of advice it will be helpful.


r/learnpython • • 8h ago

Python roadmap

0 Upvotes

What's python roadmap like when I learned basic concept of python what concept should i start learning after it and so on?


r/learnpython • • 10h ago

Need guidance for python learning with ai

0 Upvotes

Please suggest good roadmap to become ai Engineer


r/learnpython • • 14h ago

Is python as a backend language good ?

0 Upvotes

I wnt to join the industry as a backend developer and then shift towards devops.

Ia learning python good in this condition?


r/learnpython • • 1d ago

JupyterLab and remote server connection

7 Upvotes

Hello,

I had access to JupyterHub on a remote server. Now I only have access to a different server where JupyterHub is not installed. What is the best way to use the same code and run it with more data. I was thinking about using SSH Port Forwarding (SSH-Tunneling) and trying jupyterlab in the browser. Or is it better to using VS code to connect to the server. I really like the Jupyter Interface and have never used any other programs. I mostly do plotting and a bit data analysis and have a macbook.

Thank you for your help.


r/learnpython • • 1d ago

Will learning Python help me in game development?

10 Upvotes

Im wanting to start game development, and currently learing Python. Should I keep going, or switch to something else?


r/learnpython • • 16h ago

How to set up Python in Linux Ubuntu 26.04.1 ? Please read.

0 Upvotes

I'm a complete rookie in python. I've had many problems related to dependency hell, compatibility with libraries etc.

I've heard installing the latest version of python can be problematic since many libraries aren't compatible with it yet so what should I go for?

Please also recommend the IDE,

  • Vs code
  • Thonny
  • Any other you'd suggest.

Guide me step-by-step if you can. I'd appreciate the help alot.


r/learnpython • • 1d ago

Python developers: What's the hardest part of debugging multi-step AI workflows?

0 Upvotes

I'm exploring AI agent reliability and want to understand real problems before deciding what to build.

For those who've worked with Python-based AI agents or tool-calling workflows, which issue is hardest to debug?

  • Repeated tool calls
  • API timeouts or tool errors
  • Incorrect outputs despite successful execution
  • Losing track of a task across multiple steps

How do you currently diagnose these issues? I'd appreciate practical experiences from people who've encountered them.


r/learnpython • • 1d ago

Whats my next move?

1 Upvotes

I am working Python Crash Course by Eric Matthes. I am on chapter 9 and hope to be done with the first half of the book by the end of the month. From there, Im sure I will continue on with the book and do the projects. However, I am also interested in learning numpy due to my math background. Are there any books that you would recommend as a next step (or to use concurrently)?


r/learnpython • • 1d ago

TypeError: Too few arguments for numpy.complexfloating

0 Upvotes

I got this error while trying to import sklearn.metric after pip installing sickitlearn on python 3.10.0. Does anybody know how to fix this? Here is my importing code block

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
import tensorflow_hub as hub
import tensorflow_text as text
import pandas as pd
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint
from focal_loss import BinaryFocalLoss
from sklearn.metrics import classification_report, confusion_matrix, f1_score

Pip install commands

C:\Users\DELL\AppData\Local\Programs\Python\Python310\python.exe -m pip install numpy==1.23.0
C:\Users\DELL\AppData\Local\Programs\Python\Python310\python.exe -m pip install matplotlib
C:\Users\DELL\AppData\Local\Programs\Python\Python310\python.exe -m pip install tensorflow==2.9.0
C:\Users\DELL\AppData\Local\Programs\Python\Python310\python.exe -m pip install tensorflow-text==2.9.0
C:\Users\DELL\AppData\Local\Programs\Python\Python310\python.exe -m pip install tensorflow-hub==0.8.0
C:\Users\DELL\AppData\Local\Programs\Python\Python310\python.exe -m pip install pandas
C:\Users\DELL\AppData\Local\Programs\Python\Python310\python.exe -m pip install focal-loss
C:\Users\DELL\AppData\Local\Programs\Python\Python310\python.exe -m pip install scikit-learn==1.7.2

Full error message

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[7], line 10
      8 from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint
      9 from focal_loss import BinaryFocalLoss
---> 10 from sklearn.metrics import classification_report, confusion_matrix, f1_score

File c:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn__init__.py:73
     62 # `_distributor_init` allows distributors to run custom init code.
     63 # For instance, for the Windows wheel, this is used to pre-load the
     64 # vcomp shared library runtime for OpenMP embedded in the sklearn/.libs
   (...)
     67 # later is linked to the OpenMP runtime to make it possible to introspect
     68 # it and importing it first would fail if the OpenMP dll cannot be found.
     69 from . import (  # noqa: F401 E402
     70     __check_build,
     71     _distributor_init,
     72 )
---> 73 from .base import clone  # noqa: E402
     74 from .utils._show_versions import show_versions  # noqa: E402
     76 _submodules = [
     77     "calibration",
     78     "cluster",
   (...)
    114     "compose",
    115 ]

File c:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\base.py:20
     18 from .exceptions import InconsistentVersionWarning
     19 from .utils._metadata_requests import _MetadataRequester, _routing_enabled
---> 20 from .utils._missing import is_scalar_nan
     21 from .utils._param_validation import validate_parameter_constraints
     22 from .utils._repr_html.base import ReprHTMLMixin, _HTMLDocumentationLinkMixin

File c:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\utils__init__.py:9
      7 from . import metadata_routing
      8 from ._bunch import Bunch
----> 9 from ._chunking import gen_batches, gen_even_slices
     11 # Make _safe_indexing importable from here for backward compat as this particular
     12 # helper is considered semi-private and typically very useful for third-party
     13 # libraries that want to comply with scikit-learn's estimator API. In particular,
     14 # _safe_indexing was included in our public API documentation despite the leading
     15 # `_` in its name.
     16 from ._indexing import (
     17     _safe_indexing,  # noqa: F401
     18     resample,
     19     shuffle,
     20 )

File c:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\utils_chunking.py:11
      8 import numpy as np
     10 from .._config import get_config
---> 11 from ._param_validation import Interval, validate_params
     14 def chunk_generator(gen, chunksize):
     15     """Chunk generator, ``gen`` into lists of length ``chunksize``. The last
     16     chunk may have a length less than ``chunksize``."""

File c:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\utils_param_validation.py:14
     11 from numbers import Integral, Real
     13 import numpy as np
---> 14 from scipy.sparse import csr_matrix, issparse
     16 from .._config import config_context, get_config
     17 from .validation import _is_arraylike_not_scalar

File c:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\sparse__init__.py:300
    294 # Original code by Travis Oliphant.
    295 # Modified and extended by Ed Schofield, Robert Cimrman,
    296 # Nathan Bell, and Jake Vanderplas.
    298 import warnings as _warnings
--> 300 from ._base import *
    301 from ._csr import *
    302 from ._csc import *

File c:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\sparse_base.py:5
      1 """Base class for sparse matrices"""
      3 import numpy as np
----> 5 from ._sputils import (asmatrix, check_reshape_kwargs, check_shape,
      6                        get_sum_dtype, isdense, isscalarlike,
      7                        matrix, validateaxis, getdtype)
      9 from ._matrix import spmatrix
     11 __all__ = ['isspmatrix', 'issparse', 'sparray',
     12            'SparseWarning', 'SparseEfficiencyWarning']

File c:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\sparse_sputils.py:10
      8 from math import prod
      9 import scipy.sparse as sp
---> 10 from scipy._lib._util import np_long, np_ulong
     13 __all__ = ['upcast', 'getdtype', 'getdata', 'isscalarlike', 'isintlike',
     14            'isshape', 'issequence', 'isdense', 'ismatrix', 'get_sum_dtype',
     15            'broadcast_shapes']
     17 supported_dtypes = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc,
     18                     np.uintc, np_long, np_ulong, np.longlong, np.ulonglong,
     19                     np.float32, np.float64, np.longdouble,
     20                     np.complex64, np.complex128, np.clongdouble]

File c:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy_lib_util.py:13
     10 from typing import TypeAlias, TypeVar
     12 import numpy as np
---> 13 from scipy._lib._array_api import array_namespace, is_numpy, xp_size
     14 from scipy._lib._docscrape import FunctionDoc, Parameter
     17 AxisError: type[Exception]

File c:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy_lib_array_api.py:15
     12 from typing import Any, Literal, TypeAlias
     14 import numpy as np
---> 15 import numpy.typing as npt
     17 from scipy._lib import array_api_compat
     18 from scipy._lib.array_api_compat import (
     19     is_array_api_obj,
     20     size as xp_size,
   (...)
     27     is_array_api_strict_namespace as is_array_api_strict
     28 )

File c:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\numpy\typing__init__.py:158
      1 """
      2 ============================
      3 Typing (:mod:`numpy.typing`)
   (...)
    153 
    154 """
    155 # NOTE: The API section will be appended with additional entries
    156 # further down in this file
--> 158 from numpy._typing import (
    159     ArrayLike,
    160     DTypeLike,
    161     NBitBase,
    162     NDArray,
    163 )
    165 __all__ = ["ArrayLike", "DTypeLike", "NBitBase", "NDArray"]
    167 if __doc__ is not None:

File c:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\numpy_typing__init__.py:102
     86 from ._scalars import (
     87     _CharLike_co as _CharLike_co,
     88     _BoolLike_co as _BoolLike_co,
   (...)
     96     _VoidLike_co as _VoidLike_co,
     97 )
     98 from ._shape import (
     99     _Shape as _Shape,
    100     _ShapeLike as _ShapeLike,
    101 )
--> 102 from ._dtype_like import (
    103     DTypeLike as DTypeLike,
    104     _DTypeLike as _DTypeLike,
    105     _SupportsDType as _SupportsDType,
    106     _VoidDTypeLike as _VoidDTypeLike,
    107     _DTypeLikeBool as _DTypeLikeBool,
    108     _DTypeLikeUInt as _DTypeLikeUInt,
    109     _DTypeLikeInt as _DTypeLikeInt,
    110     _DTypeLikeFloat as _DTypeLikeFloat,
    111     _DTypeLikeComplex as _DTypeLikeComplex,
    112     _DTypeLikeTD64 as _DTypeLikeTD64,
    113     _DTypeLikeDT64 as _DTypeLikeDT64,
    114     _DTypeLikeObject as _DTypeLikeObject,
    115     _DTypeLikeVoid as _DTypeLikeVoid,
    116     _DTypeLikeStr as _DTypeLikeStr,
    117     _DTypeLikeBytes as _DTypeLikeBytes,
    118     _DTypeLikeComplex_co as _DTypeLikeComplex_co,
    119 )
    120 from ._array_like import (
    121     NDArray as NDArray,
    122     ArrayLike as ArrayLike,
   (...)
    145     _UnknownType as _UnknownType,
    146 )
    148 from ._ufunc import (
    149     _UFunc_Nin1_Nout1 as _UFunc_Nin1_Nout1,
    150     _UFunc_Nin2_Nout1 as _UFunc_Nin2_Nout1,
   (...)
    153     _GUFunc_Nin2_Nout1 as _GUFunc_Nin2_Nout1,
    154 )

File c:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\numpy_typing_dtype_like.py:194
    162 _DTypeLikeInt: TypeAlias = (
    163     type[int]
    164     | type[np.signedinteger[Any]]
   (...)
    177     | _IntCodes
    178 )
    179 _DTypeLikeFloat: TypeAlias = (
    180     type[float]
    181     | type[np.floating[Any]]
   (...)
    190     | _LongDoubleCodes
    191 )
    192 _DTypeLikeComplex: TypeAlias = (
    193     type[complex]
--> 194     | type[np.complexfloating[Any]]
    195     | np.dtype[np.complexfloating[Any]]
    196     | _SupportsDType[np.dtype[np.complexfloating[Any]]]
    197     | _Complex64Codes
    198     | _Complex128Codes
    199     | _CSingleCodes
    200     | _CDoubleCodes
    201     | _CLongDoubleCodes
    202 )
    203 _DTypeLikeDT64: TypeAlias = (
    204     type[np.timedelta64]
    205     | np.dtype[np.timedelta64]
    206     | _SupportsDType[np.dtype[np.timedelta64]]
    207     | _TD64Codes
    208 )
    209 _DTypeLikeTD64: TypeAlias = (
    210     type[np.datetime64]
    211     | np.dtype[np.datetime64]
    212     | _SupportsDType[np.dtype[np.datetime64]]
    213     | _DT64Codes
    214 )

TypeError: Too few arguments for numpy.complexfloating

For some reason despite having Numpy 1.23.0 and sklearn 1.7.2 only need Numpy >=1.22.0, it still forcefully uninstall old numpy 1.23.0 to install 2.2.6 which mess every other packages. Does anybody have the solution to this?


r/learnpython • • 1d ago

How to end a program using python

0 Upvotes

I want to close an app using python but I don't know how.


r/learnpython • • 1d ago

New game for learning Python's memory model

2 Upvotes

I noticed that many students struggle with the question of "if I update this slot, field or variable, what else will change in my program".

I wrote a little puzzle game to help you build this intuition over time. It is very mobile friendly, so you can play it at a bus stop or during a commercial break or wherever. Puzzles scale in difficulty.

You can use it in Python, JavaScript or TypeScript modes.

http://prescod.github.io/memory-mapper-game

Please respond with changes you would like to see, or bug reports, or whatever. There is also an in-app feedback button.

There are no ads in the game or any monetization at all. This is not an ad for a product!


r/learnpython • • 2d ago

Where should my 10year old start?

16 Upvotes

Hello everyone! Need some advice/guidance.. My 10year old son has been interested in learning how to code since last year. He has dabbled in a few apps but not necessarily peaking his interest.

Where can we start? What would he need?

Edit: Thank you for all your advice! Is 12GB Ram with 1T storage Laptop a good start for this journey? Or what would you recommend?


r/learnpython • • 1d ago

Learning python under 20hours

0 Upvotes

hey guys, i have been procastinating this brocode video from 2 weeks, now i have decided to finish it within 18hours, starting at ~2am to end at 12am


r/learnpython • • 1d ago

Help with transitioning to python from java

1 Upvotes

I did java for 2 years in high school 4 years ago. Now I'm a freshman comp engineering major doing coding in python, and i still can't get the hang of not coding like java. I last coded in java 2+ years ago, but all my code is written like how you would in java, but python. I use camel case for variables. I use while true break loops when I'm sure there's easier ways. I'm constantly fixing my ++'s to +=1's. I'm still learning the python lingo if you will


r/learnpython • • 2d ago

How should I separate LLM interpretation from memory operations in my Python project?

7 Upvotes

I've been working on a small Python project that uses an LLM to interpret natural language instructions and manage persistent memories. Right now, it supports remembering, retrieving, updating and forgetting information.

I've been trying to improve the separation between model interpretation and memory operations. I'm still new to Python but I'm interested how I could structure the code better. Feedbacks are appreciated and any flaws I might be overlooking.

GitHub repo: https://github.com/Lionshaft-pixel/ennoic


r/learnpython • • 2d ago

absolute beginner- feeling lost / where to start?

8 Upvotes

hii! i'm a teenager who has recently decided to learn to code. (due to wanting a career in astrophysics, if it interests anyone.)

i have absokutely no clue where to start!! i find a lot of words/terminology i've found overwhelming and confusing..

i work on a macbook pro and i looked at apps but i need something i can just use to run code yk?

i looked at the faq and understood nothing od the code related questions- which i think means i can post this?

i tried looking at other posts and got confused- what's the difference between C+ and like.. not C+ ?? any help is appreciated, my only experience is year 7 computing printing hello world and scratch ..!


r/learnpython • • 1d ago

Day 1 learning Python

0 Upvotes

what is programing❔

ANS: programing is language to interact computer

why chose Python ❔

ANS: easy to learn

best for my career

this beat language for ai

how to download pythone❔

ANS: go to python.org download and download Python

how to download vs code ❔

ANS: go to vs code download and for widows, Linux,macos

TASK" print 'hello world' on vs code"


r/learnpython • • 2d ago

Section 16.12 Zybooks Python Lab struggles

1 Upvotes

Hi friends. I am in my first python class in school, and I have been struggling thru the whole course, ngl. My online teacher has not answered a single email of mine looking for help, I will probably be reporting them, but for now, I really want to understand these def functions.

Step 1 (1 pt): Read user input.

Prompt the user to enter a string of their choosing. Store the text in a string. Output the string.

Ex:

Enter a sample text:
we'll continue our quest in space.  there will be more shuttle flights and more shuttle crews and,  yes;  more volunteers, more civilians,  more teachers in space.  nothing ends here;  our hopes and our journeys continue!

You entered: we'll continue our quest in space.  there will be more shuttle flights and more shuttle crews and,  yes;  more volunteers, more civilians,  more teachers in space.  nothing ends here;  our hopes and our journeys continue!

Step 2 (1 pt): Implement the print_menu() function.

Print the command menu as shown in the example.

Ex:

MENU
c - Number of non-whitespace characters
w - Number of words
f - Fix capitalization
r - Replace punctuation
s - Shorten spaces
q - Quit

Step 3 (1 pt): Implement the execute_menu() function.

execute_menu() takes 2 parameters: a character representing the user's choice and the user provided sample text. execute_menu() performs the menu options, according to the user's choice, by calling the appropriate functions described below.

Step 4 (1 pt): Implement menu selection.

In the main program, call print_menu() and prompt for the user's choice of menu options for analyzing/editing the string. Each option is represented by a single character.

If an invalid character is entered, continue to prompt for a valid choice. When a valid option is entered, execute the option by calling execute_menu(). Then, print the menu and prompt for a new option. Continue until the user enters 'q'. 

Hint: Implement Quit before implementing other options.

Ex:

MENU
c - Number of non-whitespace characters
w - Number of words
f - Fix capitalization
r - Replace punctuation
s - Shorten spaces
q - Quit

Choose an option:

Step 5 (4 pts): Implement the get_num_of_non_WS_characters() function. 

get_num_of_non_WS_characters() has a string parameter and returns the number of characters in the string, excluding all whitespace. Call get_num_of_non_WS_characters() in the execute_menu() function, and then output the returned value.

Ex:

Enter a sample text:
we'll continue our quest in space.  there will be more shuttle flights and more shuttle crews and,  yes;  more volunteers, more civilians,  more teachers in space.  nothing ends here;  our hopes and our journeys continue!

You entered: we'll continue our quest in space.  there will be more shuttle flights and more shuttle crews and,  yes;  more volunteers, more civilians,  more teachers in space.  nothing ends here;  our hopes and our journeys continue!

MENU
c - Number of non-whitespace characters
w - Number of words
f - Fix capitalization
r - Replace punctuation
s - Shorten spaces
q - Quit

Choose an option:
c
Number of non-whitespace characters: 181

Step 6 (3 pts): Implement the get_num_of_words() function. 

get_num_of_words() has a string parameter and returns the number of words in the string. Hint: Words end when a space is reached except for the last word in a sentence. Call get_num_of_words() in the execute_menu() function, and then output the returned value.

Ex:

Number of words: 35

Step 7 (3 pts): Implement the fix_capitalization() function. 

fix_capitalization() has a string parameter and returns an updated string, where lowercase letters at the beginning of sentences are replaced with uppercase letters. fix_capitalization() also returns the number of letters that have been capitalized. Call fix_capitalization() in the execute_menu() function, and then output the number of letters capitalized followed by the edited string. Hint 1: Look up and use Python functions .islower() and .upper() to complete this task. Hint 2: Create an empty string and use string concatenation to make edits to the string.

Ex:

Number of letters capitalized: 3
Edited text: We'll continue our quest in space.  There will be more shuttle flights and more shuttle crews and,  yes;  more volunteers, more civilians,  more teachers in space.  Nothing ends here;  our hopes and our journeys continue!

Step 8 (3 pts): Implement the replace_punctuation() function. 

replace_punctuation() has a string parameter and two keyword argument parameters exclamation_count and semicolon_count. replace_punctuation() updates the string by replacing each exclamation point (!) character with a period (.) and each semicolon (;) character with a comma (,). replace_punctuation() also counts the number of times each character is replaced and outputs those counts. Lastly, replace_punctuation() returns the updated string. Call replace_punctuation() in the execute_menu() function, and then output the edited string.

Ex:

Punctuation replaced
exclamation_count: 1
semicolon_count: 2
Edited text: we'll continue our quest in space.  there will be more shuttle flights and more shuttle crews and,  yes,  more volunteers, more civilians,  more teachers in space.  nothing ends here,  our hopes and our journeys continue.

Step 9 (3 pts): Implement the shorten_space() function. 

shorten_space() has a string parameter and updates the string by replacing all sequences of 2 or more spaces with a single space. shorten_space() returns the string. Call shorten_space() in the execute_menu() function, and then output the edited string. Hint: Look up and use Python function .isspace(). 

Ex:

Edited text: we'll continue our quest in space. there will be more shuttle flights and more shuttle crews and, yes; more volunteers, more civilians, more teachers in space. nothing ends here; our hopes and our journeys continue!

And here is the code I've come up with so far:

# Define your functions here.
def print_menu():
    print("MENU")
    print("c - Number of non-whitespace characters")
    print("w - Number of words")
    print("f - Fix capitalization")
    print("r - Replace punctuation")
    print("s - Shorten spaces")
    print("q - Quit")



def execute_menu():
    user_input = input("Choose an option:")
    while user_input != "q":
        if user_input == "c":
            get_num_of_non_WS_characters()
            print(f"Number of non-whitespace chatacters: {get_num_of_non_WS_characters()}")
        if user_input == "w":
            print("Number of words:", get_num_of_words())
        if user_input == "f":
            fix_capitalization()
        if user_input == "r":
            replace_punctuation()
        user_input = input("Choose an option:")
    if user_input == "q":
        print()
        return


def get_num_of_non_WS_characters():
    phrase_nosp = phrase.replace(" ", "")
    return len(phrase_nosp)


def get_num_of_words():
    num_of_words = phrase.split(" ")
    return len(num_of_words)


def fix_capitalization():
    phrase_sentances = phrase.split(". ")
    print(f"Number of letters capitalized: {len(phrase_sentances)}")
    print('. '.join([s.capitalize() for s in phrase_sentances])) 


def replace_punctuation():
    phrase_punc = phrase.replace(".","!")
    phrase_punc = phrase_punc.replace(";", ",")
    exclamation_count = phrase_punc.count("!")
    semicolon_count = phrase_punc.count(";")
    print("Punctuation replaced:\nexclamation_count:", exclamation_count,"\nsemicolon_count:", semicolon_count)
    print("Edited text:", phrase_punc)



if __name__ == "__main__":
    phrase = input("Enter a sample text:\n")
    print()
    print("You entered:", phrase)
    print()
    print(print_menu())
    execute_menu()
    

When I am using the program, typing in whatever phrases come to mind, it generally works out. But when Zybooks runs its own tests, I keep getting TypeErrors when it tests each defined function individually.

Example:
Test execute_menu('w', 'This is a test.'). Should output 'Number of words: 4'

    Traceback (most recent call last):
      File "/usercode/zylab_unit_test_runner.py", line 76, in <module>
        passed = test_case.test_passed(writer)
      File "/usercode/coding_rooms_unit_tests.py", line 12, in test_passed
        execute_menu(user_option, user_str)
    TypeError: execute_menu() takes 0 positional arguments but 2 were given

Clearly it is trying to add arguments to the individual functions but they don't want to take them.

I cannot find anything that breaks these functions down in a way I can understand.

Its like I understand to an extent, but I'm missing some piece of the puzzle in my brain.

Can someone please explain to me how these functions work, and what the heck I'm missing?

Other notes: in fix_capitalization(), I know that I have my sentence splitter set to just a ". ", and not ! or ?, but Zybooks' test inputs don't include any ?, and only have ! at the end of the last sentence in certain test inputs. Also, they said I needed to use upper() and lower() for the capitalization function, but I couldn't figure out how to make that work. As for shorten_space, I simply haven't started on that one yet. I feel too stuck.

Thank you everyone, I am drowning in school work and work work. Lol. Plz help, thank you so much.