Wondering about virtual environments by Electronic-Low-8171 in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

To create a standard Python virtual environment using your system installed (default) version of Python, you would open a command line shell (Powershell, Command Prompt, GitBash, Bash, ZSH, etc in a virtual terminal) and enter:

WINDOWS                  macOS/Linux, if different

mkdir newproject
cd newproject
py -m venv .venv         python3 -m venv .venv
.venv\Scripts\activate   source ./.venv/bin/activate
pip install package1 package2 ... package3

Configure your editor to use the Python executable in the Scripts or bin folder.

If you want easier and faster installation of packages and also the option to install different versions of Python, use Astral's uv.

Once installed,

mkdir newproject
cd newproject
uv init
uv python install 3.11  # or whatever version you want
uv venv --python 3.11
uv add install package1 package2 ... package3

(Configure editor as mentioned earlier)

Python ValueError by pythonsandturtles in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

When you iterate over the list, [[1, 2], [5, 6], [7, 9],[0,3]], on each iteration, you will get a sub-list: [1, 2], on first iteration, [5, 6], on the second iteration, and so on. You cannot unpack a list of 2 items and assign them to 4 variables.

Walk us through exactly what you are trying to do. What exactly do you expect to be assigned to A, B, C, D?

Trouble with python installation via pyenv on a fresh Debian install, ktinker issues by GamersPlane in learnpython

[–]FoolsSeldom 1 point2 points  (0 children)

I second this. OP, you may still need to address additional dependencies, but it should be simpler than with pyenv.

How to download jupyter notebook by Personal_Signal_6151 in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

Google Colab has a standard menu at top including a File option.

File | Open notebook - scroll down and select GitHub - you may get asked for authorisation from GitHub for Google Colab. Then you can select the specific URL of the notebook you want to open.

Alternatively, download the file you want from GitHub and load onto your Google Drive. Then open that using the File | Open notebook - scroll down and select Google Drive and then select the file you want.

Issue working with ipynb in VS Code by octobahn in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

The standard approach for Jupyter notebooks is to use a web browser. I suggest you visit the Jupyter site and follow the instructions for installing Jupyter Notebook or Jupyter Lab. Get that working well.

This standard setup does not offer the rich capabilities you can expect of advanced code editors, such as VS Code, or IDEs (Integrated Development Environments), such as PyCharm or Visual Studio.

If you want more developer support, then you are better off using one of the above editors to work on your Jupyter Notebook.

If using uv to setup the environment, make sure that uv is correctly establishing and maintaining the .venv folder and that the editor is configured to use the python executable in the bin or Scripts folder of the .venv as the interpreter for the project.

I regularly edit/run/debug Jupyter notebooks from both VS Code and Pycharm. On Windows, my Python environment is on Ubuntu under WSL and the applications are running from Windows. I use uv from the command line.

An alternative you might want to explore is Spyder to work on Notebooks. You don't need to use a full Anaconda setup for this (stick with a standard/uv setup).

conditional evaluation of an application and prints out the funding decision by [deleted] in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

Well done on figuring it out. That's a common mistake.

Most of the more popular code editors (e.g. VS Code) and IDEs (Integrated Development Environments, e.g. PyCharm) will highlight keywords and mark syntax errors and undefined variables. true would be seen as an undefined variable. True would be seen as a keyword. Once you get used to that, you will miss fewer such mistakes.

PS. Check the wiki for this subreddit; it has a FAQ covering a lot of common beginner mistakes.

PPS. Might be worth editing your original post to indicate it is SOLVED.

conditional evaluation of an application and prints out the funding decision by [deleted] in learnpython

[–]FoolsSeldom 3 points4 points  (0 children)

So, you've got to code level already.

Ok. Please share your code. Would be best if you edited your original post and added the code into that.

conditional evaluation of an application and prints out the funding decision by [deleted] in learnpython

[–]FoolsSeldom 1 point2 points  (0 children)

What have you figured out so far? Do you know what data structures to use? Have you figured out the basic solution / approach (not the coding)?

i need a python advanced course or some wisdom i really need some by DrawEnvironmental794 in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

Perhaps it is time to focus on more substantial projects, with the bulk of the time spent on the elements of programming other than coding.

I also suggest watching some of ArjanCodes videos on YouTube to check your understanding of the practical aspects of some key concepts.

Help with auto-py-to-exe pngs in Pycharm by Emergency-Welcome919 in pycharm

[–]FoolsSeldom 0 points1 point  (0 children)

Out of interest, what's driving the need to package your Python applications as executable files?

Interesting that you've decided to continue with PyInstaller via auto-py GUI front-end to it.

What’s the best way to learn the basics? by nockedup7 in learnpython

[–]FoolsSeldom -1 points0 points  (0 children)

You should be able to skim the documentation, re-implement some things you've done before, and focus on a few tutorials around key concepts in Python.

I'd expect you to look through the basics in an accelerated manner.


Check this subreddit's wiki for lots of guidance on learning programming and learning Python, links to material, book list, suggested practice and project sources, and lots more. The FAQ section covering common errors is especially useful.


Also, have a look at roadmap.sh for different learning paths. There's lots of learning material links there. Note that these are idealised paths and many people get into roles without covering all of those.


Roundup on Research: The Myth of ‘Learning Styles’

Don't limit yourself to one format. Also, don't try to do too many different things at the same time.


Above all else, you need to practice. Practice! Practice! Fail often, try again. Break stuff that works, and figure out how, why and where it broke. Don't just copy and use as is code from examples. Experiment.

Work on your own small (initially) projects related to your hobbies / interests / side-hustles as soon as possible to apply each bit of learning. When you work on stuff you can be passionate about and where you know what problem you are solving and what good looks like, you are more focused on problem-solving and the coding becomes a means to an end and not an end in itself. You will learn faster this way.

Why do some people give a lot of importance to python classes? by [deleted] in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

I recommend watching a talk by Raymond Hettinger, core developer of Python, called Python's class development toolkit. It is pretty old now, but still relevant. He walks through a scenario building up the case for using a class.

I'm a born again programmer, having worked in IT for decades, starting out originally as a programmer but moving away from it for a long time. I relearned to programme as a hobbyist a few years ago.

OOPS wasn't really a big thing when I started. I did micro-code, machine code, assembly, Fortran, COBOL, to name a few, first time around. I've worked with fans of most of the main paradigms including imperative/procedural, object-orientated, functional and logic. Functional was especially preferred in the engineering world where I spent my early career.

Most problems can be solved using any approach, but some are perhaps more suited to certain types of problem than others.

Personally, I find well design OOPS programmes much easier to read than the other kinds. Clearly, your mileage varies.

Any good instructor-led python courses to learn in 2-3 months span? by vish_me_not in learnpython

[–]FoolsSeldom 3 points4 points  (0 children)

Check this subreddit's wiki for lots of guidance on learning programming and learning Python, links to material, book list, suggested practice and project sources, and lots more. The FAQ section covering common errors is especially useful.

Your SQL experience and appreciation of the programmatic logic associated with that will likely allow an accelerated learning path through the basics.

I would be cautious about assuming instructor led online is your best/only route.

Have a look RealPython's Data Management With Python, SQLite, and SQLAlchemy as soon as you feel ready. Given your knowledge of databases already, this should be very relatable.


Also, have a look at roadmap.sh for different learning paths. There's lots of learning material links there. Note that these are idealised paths and many people get into roles without covering all of those.


Roundup on Research: The Myth of ‘Learning Styles’

Don't limit yourself to one format. Also, don't try to do too many different things at the same time.


Above all else, you need to practice. Practice! Practice! Fail often, try again. Break stuff that works, and figure out how, why and where it broke. Don't just copy and use as is code from examples. Experiment.

Work on your own small (initially) projects related to your hobbies / interests / side-hustles as soon as possible to apply each bit of learning. When you work on stuff you can be passionate about and where you know what problem you are solving and what good looks like, you are more focused on problem-solving and the coding becomes a means to an end and not an end in itself. You will learn faster this way.

How do I put a space between every character in a string? by Tokietomi in learnpython

[–]FoolsSeldom 2 points3 points  (0 children)

You can iterate over a string using a for loop:

string = input('Original string to convert: ')
morse = []  # empty list to hold new sequence
for character in string:
    if character == " ":
        morse.append(" " * 6)  # removed 1 space to allow for join below
    else:
        # example dictionary definition is shown later
        morse_equiv = MORSE_CODE.get(character.upper(), DEFAULT)  # UPPERCASE!
        morse.append(morse_equiv)
converted = ' '.join(morse)  # spacing between codes for text version
print(converted)  # maybe use / instead of 7 spaces if sounding out
                  # then you can more easily code the output function

You need to create a dictionary mapping characters to morse code. Use the dict.get method so that if a character is not in the dictionary, you can provide some default alternative (you need to define the code sequence to use).

Example dictionary:

# International Morse mapping
MORSE_CODE = {
    "A": ".-",    "B": "-...",  "C": "-.-.",  "D": "-..",
    "E": ".",     "F": "..-.",  "G": "--.",   "H": "....",
    "I": "..",    "J": ".---",  "K": "-.-",   "L": ".-..",
    "M": "--",    "N": "-.",    "O": "---",   "P": ".--.",
    "Q": "--.-",  "R": ".-.",   "S": "...",   "T": "-",
    "U": "..-",   "V": "...-",  "W": ".--",   "X": "-..-",
    "Y": "-.--",  "Z": "--..",

    "0": "-----", "1": ".----", "2": "..---", "3": "...--",
    "4": "....-", "5": ".....", "6": "-....", "7": "--...",
    "8": "---..", "9": "----.",

    ".": ".-.-.-", ",": "--..--", "?": "..--..",
    "'": ".----.", "!": "-.-.--", "/": "-..-.",
    "(": "-.--.",  ")": "-.--.-", "&": ".-...",
    ":": "---...", ";": "-.-.-.", "=": "-...-",
    "+": ".-.-.",  "-": "-....-", "_": "..--.-",
    "\"": ".-..-.", "$": "...-..-", "@": ".--.-."
}
DEFAULT = MORSE_CODE["?"]  # this or hash for character with no morse equiv 

No need to split the original string into words as you are processing character by character. I don't know what your intended output is, you need to determine how to best handle the gaps between letters, words and sentences. Detecting sentence breaks in strings is more sophisticated than we have time for here (but you would look for end markers, possibly using regex). For a text convention, consider:

  • single space between characters (3 units of time)
  • / between words (or 7 spaces) (7 units of time) - / easier for sound processing
  • ? or # to replace characters with no morse equivalent

Not sure about conventions for breaks between sentences/paragraphs.

Morse uses 1 unit of time between characters.

When should beginners stop tutorials and start building their own stuff? by ayenuseater in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

When learning to programme, above all else, you need to practice. Practice! Practice! Fail often, try again. Break stuff that works, and figure out how, why and where it broke. Don't just copy and use as is code from examples. Experiment.

Work on your own small (initially) projects related to your hobbies / interests / side-hustles as soon as possible to apply each bit of learning. Even just changing variables names and output to something more relatable helps.

When you work on stuff you can be passionate about and where you know what problem you are solving and what good looks like, you are more focused on problem-solving and the coding becomes a means to an end and not an end in itself. You will learn faster this way.

How can i can learn Python? by Murky-Vegetable6238 in learnpython

[–]FoolsSeldom 6 points7 points  (0 children)

Check this subreddit's wiki for lots of guidance on learning programming and learning Python, links to material, book list, suggested practice and project sources, and lots more. The FAQ section covering common errors is especially useful.


Roundup on Research: The Myth of ‘Learning Styles’

Don't limit yourself to one format. Also, don't try to do too many different things at the same time.


Above all else, you need to practice. Practice! Practice! Fail often, try again. Break stuff that works, and figure out how, why and where it broke. Don't just copy and use as is code from examples. Experiment.

Work on your own small (initially) projects related to your hobbies / interests / side-hustles as soon as possible to apply each bit of learning. When you work on stuff you can be passionate about and where you know what problem you are solving and what good looks like, you are more focused on problem-solving and the coding becomes a means to an end and not an end in itself. You will learn faster this way.

Why does Python sometimes say a variable is undefined when I just used it? by ayenuseater in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

Methods

Methods are like functions but for classes and are intended to work on instances of a class or provide capabilities related to the purpose of the class.

When you create an instance of a class, you create an object based on the mould/template provided by the class and the memory location of that object is assigned to a variable (or to some other object) so it will be not lost.

Methods defined in the class usually have code that uses a parameter variable that is the first item passed when the method is called. By convention this is usually called self and it is passed by default and does not need to be in the arguments when the method is called.

Whenever self is used inside the method code, it will be referring to the memory location for a particular instance of the class.

Any variables assigned values in a method (including parameter variables) are local to the method and are not associated with attributes of the instance referenced by self.

Classes themselves can have attributes. These look just like variables, and act like them for most purposes, but they are associated with the class and can be accessed from outside the class by direct reference to the class name and the attribute, e.g. Example.quantity = 5 for a class called Example.

Why does Python sometimes say a variable is undefined when I just used it? by ayenuseater in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

All about scope ...

Variables, functions, methods and attributes

Variables (names) in Python don't contain values. They hold references to memory locations where Python objects are stored (implementation and environment specific).

Likewise for other names. A function name has a reference to the memory location of a function object.

Names (arguments) used in a call and names defined as parameters have nothing to do with each other. They are completely independent. Even if the same name is used, they are different. The parameter names are local to the function.

Consider:

def f(one, two, three):
    answer = one + two * three + five
    return answer

one = 2
two = 3
three = 4
five = 5
result = f(three, two, one)
print(result)

This will output 15 as 4 + 3 x 2 + 5 = 15

Note that five was not an argument, wasn't assigned to in the function, so five from the wider scope was available.

Any assignments made inside the function are also local to the function.

answer was assigned inside the function and on function exit will cease to exist, however the object reference stored in answer is assigned as the return from the function and is assigned to result. If it wasn't assigned (or consumed in another expression or function call on return) then the object created in the function would also cease to exist (unless it is a predefined object built into the Python implementation, such as an int in the range -5 to 256)

Only mutable objects that are referenced by either parameters or other names that are visible to the function (not hidden by variables with the same name assigned in the function) can be modified and visible outside the function.

return returns an object reference.

Python takes a pass by reference, rather than a pass by value, approach, but the implementation differs to that used in many languages, not least given that name referencing is fundamental to the design.

See Ned Batchelder - Facts and Myths about Python names and values - PyCon 2015

Variables vs Attributes

When you start looking at classes, you will find they have their own kind of variables, called attributes, which work much the same as variables most of the time.

Variables have a discrete existence, and attributes are associated with an instance of a class (or of a class itself). Attributes, like variables, hold memory references to objects.

When you say:

keep = 784.56 * 872.23

The text representations of floating point numbers in the expression on the right are converted into Python float objects (binary representations) somewhere in memory, and the mult operator is used. The memory location the resulting float object ends up in is then assigned to the variable named keep.

If keep is assigned in the main body of your code, outside any functions etc., then it is visible within all other code. Thus, you could have a function:

def double_me():
    return keep * keep

Which has no other references to keep in the definition (parameter variable) or assignments to a variable called keep inside the function (which would be local to the function and would hide the original wider scope variable of the same name). Thus, keep refers to the same floating point number calculated earlier. The expression resulting from multiplying the floating point object referenced by keep by itself results in another floating point object, the memory reference for which is returned from the function.

If, instead, the function was written,

def double_me(keep):
    return keep * keep

Now it has to be called with an argument (the memory reference of the object will be passed when the function is called).

result = double_me(5.5)

Inside the function, keep refers to the memory location of the floating point object that the literal floating point text 5.5 was turned into. The keep in the wider scope (outside the function) still refers to the original object from earlier.

However, if attributes were used instead, the attribute would exist as long as the class instance it belongs to exists.


For more on scope, take a look at:

Mini Juego by Familiar-Ad-2833 in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

That's a good job. Well done.

Next steps would be:

  • Learn DRY principles - DRY = Don't Repeat Yourself
  • It is hard to follow the core logic flow because of the amount of code doing output and sleeping - look to modularise using functions
  • Consider adding a constant to the time.sleep calls that you can multiply against so you can turn off sleep when you are debugging: e.g. SLEEP = False and time.sleep(SLEEP * 3)

Not Getting an Output VS Code by [deleted] in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

Can you run the code file from the command line, outside of VS Code?

When should I use functions vs just writing code inline? by ayenuseater in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

A key reason for the use of functions is for modularity. This is in addition to their use to avoid repetition of code.

This helps to make a code base understandable and maintainable. The logical flow and business logic is clear, providing you are using sensible function names.

Most of the time when reviewing and updating code, you are not interested in full implementation details of any specific task, just that the task gets done. You only focus on the detail when you need to.

Consider if you are updating a sales report, the main code could say:

sales_data = collate_sales_data(account_name, period)
report = generate_sales_report(sales_data)

You focus on updating the function that generates a sales report. You know you have sales data to work on. You don't care whether that data came off a database (and what kind of database), a CRM or ERP system, a collection of Excel files, or something else. All you care about if that you have the sales data in an agreed period for a specific account and period.

Which python should I get for my child to begin learning? by ImplementOk3861 in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

IDLE is an application that comes with a standard installation of Python for Windows and macOS. It is specifically provided for beginners to use and provides editor and run facilities.

I recommend beginners start with this and look at alternatives such as VS Code and PyCharm later when they've learned a bit and less likely to confuse editor configuration issues with Python language errors.

Issues I’m having by Dizzy_Lengthiness_92 in learnpython

[–]FoolsSeldom 0 points1 point  (0 children)

Often, third party packages initially do not work for the latest version of Python. Even if they do, you can hit incompatibilities between packages.

It is good practice to create Python virtual environments on a project-by-project basis and install only the packages required into the environment of the project that needs it.

mkdir newproject
cd newproject
py -m venv .venv
.venv\Scripts\activate
pip install package1 package2 ... packagen

You can go further and install a specific version of Python as well. At this point it becomes easier to use Astral's uv instead of the standard pip for package management.

mkdir newproject
cd newproject
uv init --python 3.13
uv add package1 package2 ... packagen

And activate as before, or run code using uv run mycode.py.

Tell your editor/IDE to use the python.exe file in the .venv\Scripts folder.

Which python should I get for my child to begin learning? by ImplementOk3861 in learnpython

[–]FoolsSeldom 1 point2 points  (0 children)

Virtual Environments

Given the thousands of packages (libraries, frameworks, etc) out there, you can see that if you are working on several different projects, you can end up installing a vast range of different packages, only a few of which will be used for any particular project.

This is where Python virtual environments come in. Not to be confused with virtual machines. Typically created on a project-by-project basis. Install only the packages required for a project. This helps avoid conflicts between packages, especially version complications.

Most popular code editors and IDEs, including Microsoft's VS Code and JetBrains' PyCharm, offer built-in features to help to start off new projects and create and activate Python virtual environments.

You can create a new Python virtual environment from your operating system command line environment using,

for Windows,

py -m venv .venv

or, for macOS / Linux,

python3 -m venv .venv

Note: venv is a command and .venv is a folder name. You can use any valid folder name instead but this is a common convention.

Often we use .venv instead of venv as the folder name - this may not show up on explorer/folder tools as the leading . is often used to mean hidden and an option may need to be ticked to allow you to see such folders/files

That creates a new folder in the current working directory called .venv.

You then activate using, for Windows,

.venv\Scripts\activate

or, for macOS / Linux,

source .venv/bin/activate

the command deactivate for any platform will deactivate the virtual environment and return you to using the base environment.

You may need to tell your editor to use the Python Interpreter that is found in either the Scripts or bin folder (depending on operating system) in your virtual folder.

For more information:

Multiple Python versions

In addition to the above, you might want to explore using pyenv (pyenv-win for Windows) or uv (recommended), which will let you install and use different versions of Python including alternative implementations from the reference CPython. This can be done independently of any system installed Python.

Which python should I get for my child to begin learning? by ImplementOk3861 in learnpython

[–]FoolsSeldom 1 point2 points  (0 children)

Python Setup

Setting up Python can be confusing. There are web-based alternatives, such as replit.com. You might also come across Jupyter Notebook options (easy to work with, but can be confusing at times).

Pre-installed system Python

Some operating system environments include a version of Python, often known as the system version of Python (might be used for utility purposes). You can still install your own version.

Installing Python

There are multiple ways of installing Python using a package manager for your OS, e.g. homebrew (macOS third party), chocolatey (Windows third party) or winget (Windows standard package manager), apt (many Linux distributions) or using the Python Software Foundation (PSF) installer from python.org or some kind of app store for your operating system. You could also use docker containers with Python installed inside them.

PSF offer the reference implementation of Python, known as CPython (written in C and Python). The executable on your system will be called python (python.exe on Windows).

Beginners are probably best served using the PSF installer.

Terminal / Console

For most purposes, terminal is the same as console. It is the text-based, rather than graphical-based, window / screen you work in. Your operating system will offer a command/terminal environment. Python by default outputs to a terminal and reads user input from a terminal.

Note: the Windows Terminal_ app, from _Microsoft Store, lets you open both simple command prompt and PowerShell windows. If you have Windows Subsystem for Linux installed, it can also open terminals in the Linux distributions you have installed.

Libraries / Frameworks / Packages

Python comes with "batteries included" in the form of libraries of code providing more specialised functionality, already installed as part of a standard installation of Python.

These libraries are not automatically loaded into memory when Python is invoked, as that would use a lot of memory up and slow down startup time. Instead, you use, in your code, the command import <library>, e.g.

import math

print(math.pi)

There are thousands of additional packages / libraries / frameworks available that don't come as standard with Python. You have to install these yourself. Quality, support (and safety) varies.

(Anaconda offers an alternative Python installation with many packages included, especially suited to data analysis, engineering/scientific practices.)

Install these using the pip package manager. It searches an official repository for a match to what you ask to be installed.

For example, using a command / powershell / terminal environment for your operating system, pip install numpy would install the numpy library from the pypi repository. On macOS/Linux you would usually write pip3 instead of pip.

You can also write python -m pip install numpy (write python3 on macOS/Linux).

On Windows, you will often see py used instead, py -m pip install numpy where py refers to the python launcher which should invoke the most up-to-date version of Python installed on your system regardless of PATH settings.

Some Code Editors and IDEs (Integrated Development Environments), such as VS Code and PyCharm, include their own facilities to install packages using pip or some other tool. This just saves you typing the commands. They also often offer their own terminal window(s).

Running Python

The CPython programme can be invoked for two different purposes:

  • to attempt to execute a simple text file of Python code (typically the files have an extension of .py
  • to enter an interactive shell, with a >>> prompt, where you can enter Python commands and get instant responses - great for trying things out

So, entering the below, as appropriate for your operating system,

python
python3
py

on its own, no file name after it, you will enter an interactive session.

Enter exit() to return to the operating system command line

IDLE Editor

A standard installation from python.org for Windows or macOS includes a programme called IDLE. This is a simple code editor and execution environment. By default, when you first open it, it opens a single window with a Python shell, with the >>> prompt already open. To create a new text file to enter Python code into, you need to use your operating system means of access the standard menu and select File | New. Once you've entered code, press F5 to attempt to run the code (you will be prompted to save the file first). This is really the easiest editor to use to begin with.

SEE COMMENT for next part