r/learningpython • • Mar 30 '25

How to add spacing between repeated strings?

1 Upvotes

My code:
string_to_repeat = input ("Please enter a string you like me to repeat:")

repeat_num = int(input("How many times would you like me to repeat it?:"))

print("Printing your string repeat_num times:")

print(string_to_repeat * repeat_num)

Problem - There is no space between the strings when I run the code.


r/learningpython • • Feb 28 '25

im working on a minesweeper solver.

1 Upvotes

i know it has been done before and i shouldnt reinvent the wheel, BUT i found a version of minesweeper someone made in python tkinter. link here https://github.com/Dest76ter/MineSweeper-using-Python-Tkinter . i figure the easiest way to start is by getting code going that recognizes wether a tile has been activated or not. however i have hit a rode block, i am fairly new to python and am having difficulty understanding which variable is which and how to recall or find the individule tiles. i am using a simple "import minesweeper" code so i can interact with the game outside of the document the game is held in. i suppose this is a multi faceted question, what is the variable for the button and what is the best way to aproach locating activated buttons.

(i already tried a couple if statements using variables that looked like they were promising but had no luck)


r/learningpython • • Feb 02 '25

helppp

1 Upvotes

i tried to download a new version of python, i cant even find the old one because my brother used to code on anaconda. i reinstalled python and spyder, and it works fine but the version is the 3.11 and it doesnt let me install some packages, when i try to change the path to the new version it pops this warning


r/learningpython • • Mar 20 '24

Ghost in the Machine (Not really)

Thumbnail self.xenithabyss
1 Upvotes

r/learningpython • • Mar 19 '24

Need help with something.

1 Upvotes

This assignment is due tonight, and I emailed my professor only to get no response at all.

I have the second "half" of the assignment done. The first part is stumping me. The thing I have to do is as follows;

" Get user input for a list of numbers. Write a program to turn every item of a list into its square. You cannot assume the size of the list. You must get the list of numbers from the user by using the concept of indefinite loop. "

I know how this works, I know how an indefinite loop works and everything else. But, what I'm confused on is how I should break the loop. Should I try and validate if the input is a number or not? I've tried that, but it doesn't work. I've tried other stuff as well, but the loop usually never starts, even if it seems to meet the requirements.


r/learningpython • • Jan 07 '24

Building an automated meal planner

1 Upvotes

Hi everyone!

I am looking to build myself an automated meal planner including shopping list and need some advice on how to get started and what tools to use for this, please 😊

I consider myself beginner to intermediate and this should be my first personal portfolio project.

I'd like to use the Spoontacular API, get recipes for breakfast, lunch, dinner and a snack.

I want low carb recipes that are randomly generated and only occure twice max per week.

I have looked into web scraping but have no knowledge about it yet and thought using Spoontacular might make more sense for me.

I'd like to automate sending myself a weekly plan including a grocery list per email.

I'd like to store the meals in a text file.

Do you have any other suggestions of cool features that I could implement?

I was wondering about calculating macros for each meal as well and giving the option of different diet preferences, but not sure of that would be overkill.

Grateful for any input, thank you!


r/learningpython • • Oct 26 '23

Timestamp not matching datetime.strptime format codes and I can't figure out why

1 Upvotes

Hi,

I must be missing something obvious, I'm trying to parse a time stamp with datetime.strptime and I'm getting a ValueError, but I can't figure out what's wrong?

test = '[Fri Jan 28 00:29:11 CET 2011]'
datetime.strptime(test, '[%a %b %d %H:%M:%S %Z %Y]')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[31], line 1
----> 1 datetime.strptime(test, '[%a %b %d %H:%M:%S %Z %Y]')

File ~\AppData\Local\Programs\Python\Python38\lib_strptime.py:568, in _strptime_datetime(cls, data_string, format)
    565 def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"):

    566     """Return a class cls instance based on the input string and the
    567     format string."""
--> 568     tt, fraction, gmtoff_fraction = _strptime(data_string, format)
    569     tzname, gmtoff = tt[-2:]
    570     args = tt[:6] + (fraction,)

File ~\AppData\Local\Programs\Python\Python38\lib_strptime.py:349, in _strptime(data_string, format)
    347 found = format_regex.match(data_string)
    348 if not found:
--> 349     raise ValueError("time data %r does not match format %r" %
    350                      (data_string, format))
    351 if len(data_string) != found.end():
    352     raise ValueError("unconverted data remains: %s" %
    353                       data_string[found.end():])

ValueError: time data '[Fri Jan 28 00:29:11 CET 2011]' does not match format '[%a %b %d %H:%M:%S %Z %Y]'

Any help you could give me would be greatly appreciated.


r/learningpython • • Sep 25 '23

Help Needed—Image Transformation

1 Upvotes

Hello everyone—

So I'm pretty much brand new to Python and the world of coding (some R knowledge but not much) and I'm in a class I can't get out of where some Python knowledge is needed.

In this assignment, I need to transform the long image at the bottom of this painting (a skull when you look at it from the side of the painting) into a normally-proportioned skull. This is the painting, as well as my code and output so far. For some reason, I just can't get the image to stretch.

Any advice would be greatly appreciated!


r/learningpython • • Sep 19 '23

Does anyone wants to "collaborate"?

1 Upvotes

Ive been programming in Python for several years, but as far as I can tell, I havent even come close to a Junior level, despite having experience in commercial projects and having a job where I currently work. However, Ive never worked in a team and I have no idea what its like. The people Ive met are either too novice or too advanced so I had no chance to work with someone. If you have an idea or just want to try working in a team, let me know, I would be very happy to try it.


r/learningpython • • Sep 13 '23

Data science with python

1 Upvotes

Hi everybody I am currently in college taking Data Science courses for my major, but i feel like college is no teaching us anything that can be applied for real world expirence. I wanted to ask you guys any resources that can help me understand what a day to day data science work life looks like. Including programing, meeting and how hard is it to get into the field of data science.


r/learningpython • • Sep 09 '23

Trouble Setting Up Flask_Cors in PyCharm on Mac

1 Upvotes

Hi All,

Trying to set up flask_cors in PyCharm on Mac. I have a Venv in my directory, I even installed Flask_Cors via terminal in that venv within my project, and it says it was set up fine.

Location: /Users/me/Documents/pythonProject1/my_venv/lib/python3.11/site-packages

It says that the interpreter I'm using is a 3.11 at: /Users/me/myprojname/bin/python

The issue is that I have is that Python will not recognize/find the flask_cors package in PyCharm. I get the error message: (unresolved reference flask_CORS). Any thoughts?

I've even tried to find it through the Pycharm/settings/add package to the interpreter list.

What might I be doing wrong? Did I install flask in the wrong place or something? As far as I can tell my project is set up like the following:

/my_project

/my_venv

__init__.py

app.py # This contains your entire Flask app

Thanks!


r/learningpython • • Aug 23 '23

configparser : coupling

1 Upvotes

I often use configparser for storing things like directories and different variables in a text file and importing them into the script.

Do you think it is better to create a configparser object and pass that around to different funcs, or to 1) create the config parser object and then 2) populate a custom dataclass with the config info and then pass *that* around to the various funcs.

I'm inclined to go for the latter as to me it seems to reduce coupling but wondering if there is a consensus on that.


r/learningpython • • Jul 22 '23

Mastering Lambda Functions in Python: Map, Filter, Reduce

Thumbnail
youtube.com
1 Upvotes

r/learningpython • • Jun 29 '23

Solve Digits Game Automatically with DigitsSolver - A GitHub Project

1 Upvotes

Objective: Gain exposure to a newly developed GitHub project that automates solving the Digits game.

Project Summary: Are you tired of getting stuck while playing the Digits game? Look no further! Introducing DigitsSolver, a powerful GitHub project that utilizes a Breadth-first search algorithm to solve the game for you. Whether you prefer a Command-Line Interface (CLI) or a utility package integrated with Selenium, DigitsSolver has got you covered. It even offers a "speed run mode" that allows you to solve consecutive puzzles without manually opening the browser.

Game Summary: Digits is an addictive game from The New York Times, where players combine numbers using basic operators to reach a target digit. It's only been around for two months, but it has already captured the attention of puzzle enthusiasts. If you haven't tried it yet, you can experience the game firsthand here.

Why DigitsSolver? DigitsSolver provides a game-changing solution for players struggling to overcome challenging levels. With its advanced algorithms and automation capabilities, you can sit back, relax, and watch as DigitsSolver solves the puzzles for you. Whether you're a casual player seeking a quick solution or an enthusiast looking to explore advanced strategies, DigitsSolver is the ultimate tool to enhance your gaming experience.

Ready to Explore? Visit the DigitsSolver GitHub repository here to dive into the code, discover its features, and start automating your Digits game experience. Don't forget to leave a star if you find it helpful!

Let's simplify the way we play Digits with DigitsSolver. Try it out today and unleash your puzzle-solving potential!

Note: This post is not affiliated with or sponsored by The New York Times.


r/learningpython • • Jun 08 '23

GIS python help

1 Upvotes

Hi, I am trying to compare a set of GIS coordinates but I can't seem to get it to work?

I have no idea what I am doing at this point.


r/learningpython • • Apr 08 '23

Is it more beneficial or more detrimental to use ChatGPT to learn programming?

1 Upvotes

Hello all,

I want to write an article encouraging our generation and future generations to learn programming (primarily JavaScript and/or Python). I've recently been inspired by the following:

  • The desire to automate repetitive tasks in my day job working for civil engineering firm. I am so sick of Microsoft Excel spreadsheeting.

  • The conversations about programming and AI in the Lex Fridman podcast. This has been fun because I often work outside in the field so it helps to keep my mind focused on Computer Science while doing something else.

  • My own personal journey learning JavaScript using YouTube, LinkedIn Learning, ChatGPT, and a private 25+ session bootcamp from a Senior Dev. My closest friends run a start-up and are learning JavaScript in an effort to 10x their business.

  • The notion that computer science will be just as important to reading, writing, and mathematics. Books like Program or Be Programmed as well as stories that 100% of education in China will incorporate programming to our say 5% in the US.

With all this said, I've found ChatGPT to be a blessing in debugging code and helping to explain convoluted topics related to coding. Using ChatGPT in our bootcamp has been helpful as I can research topics we are discussing in class and it gives me a succinct response to the topic at hand. I will mention that our instructor is very adamant about actually typing out examples in an effort to solve in-class challenges he designs. I feel like I have been able to pick this all up really quickly but I often wonder if it is possible to too heavily lean on models like ChatGPT?

Soliciting advice from others learning as well as other more senior programmers. Thanks in advance.


r/learningpython • • Jan 03 '23

Help me with my python code for my discord server

1 Upvotes

i want to create a discord server that let users earn "diamonds" when they type !work. i tried this code in pycharm but it displayed some errors. by the way, im a newbie in coding and this code is generated through chatgpt. so im not an expert here because my line of work is very different from the world of coding.

import discord import random

client = discord.Client()

@client.event async def on_message(message): if message.content == "!work": num_diamonds = random.randint(200, 301) # Generate a random number of diamonds between 200 and 300 for i in range(num_diamonds): # Add the specified number of diamonds to the message await message.add_reaction("💎")

client.run("YOUR_BOT_TOKEN_HERE")

Can you please point out the mistakes in this code. thanks


r/learningpython • • Dec 20 '22

[Question][Matplotlib] - Barplot : How can I do the red arrow line (description below)

1 Upvotes

Afaik I can't post a picture of the thing here (according to the subreddit rules(?) ), so I have to describe it (I am sorry)

--------------------------------------------

Imagine there is graph, with two bars: one is small (orrange) and one is big (turquoise).

There is a a annotation line on the orange bar. The position of that annotation bar is on the same height as the turquoise bar though. Also there is a red arrow pointing from the orange bar (top edge)

to the mentioned annotation line. In the middle of that arrrow, is a small text (delta percentage of orange and turquoise).

My Question is, how can I do that with **matplotlib** ? Or what is the name of the described annotation if there is already one in matplotlib.

---------------------------------------

PS: I can dm a picture of that described bar plot, if wanted.

Many Thanks in advance :) :>


r/learningpython • • Nov 30 '22

having pip problems

1 Upvotes

I was coding on my laptop and I had just downloaded python too. I typed pip install daytime and it told me pip was not recognized. so I googled it and the solutions I tried didn't work. even uninstalled and reinstalled python 3.11.0 to make sure it was downloaded to the path. please help.

edit: neverminded fixed the problem


r/learningpython • • Oct 15 '22

Calling Linux’s Syscalls directly from Python

Thumbnail
medium.com
1 Upvotes

r/learningpython • • Oct 13 '22

Find a list of words in a document

1 Upvotes

I assume this is an easy solution but I am still a noob with python.... I am trying to find a list of words within a document so it returns me the line they are in. I have been able to search a single word but I am unable to get my code to search for each instance in a list. The code below is as far as I get but it still seems to be only giving me the first word from the list. can you guys help?!

my document is: DOG2

The words are dog and cat.

if I can get real fancy, return the word with the line it resides in.

file = open('DOG2.txt', 'r')
word = ['Yellow','cat']
s = " "
count=1
for p in word:
    while(s):
      s = file.readline()
      L = s.split()
      if p in L:
          print("Line Number:",file.name,p,count,":",s)

      count+=1

Thanks for any help


r/learningpython • • Sep 27 '22

from scapy.all import *

1 Upvotes

From scapy.all import * not working. Ive already tried pip install scapy. Can anyone help me out?


r/learningpython • • Sep 13 '22

purpose of idle + how to activate run option on idle?

1 Upvotes

I'm a newbie to python and experimenting with various IDEs. I have a few questions regarding IDLE:

People say it's helpful to use IDLE as a supporting editor to VS code: why is this?

And how do I active the run option on IDLE? As can be seen in the attached pic, it seems the run option is activated simply by pressing a few enters. I'm working on mac os, and it seems fn + f5 does not work either.


r/learningpython • • Sep 06 '22

parse list inside list and add to pretty table row

1 Upvotes

Trying to print results from a list of dicts into rows in a pretty table. It works well when there is only one entry, but there is one result that has a list where I had been getting a single result. The loop will go through and only grab the value at the first index.

API response and my code:

    {
        "pagination": {
            "offset": 0,
            "limit": 20,
            "total": 2
        },
        "data": [
            {
                "name": "T1",
                "uuid": "12345",
                "description": "subnet1",
                "inboundRules": [
                    {
                        "seqNo": 1,
                        "subnets": [
                            "1.1.1.0/24"
                        ],
                        "description": "",
                        "subnet": "1.1.1.0/24",
                        "protocol": "IP",
                        "srcPort": "any",
                        "dstPort": "any"
                    }
                ],
                "metroName": "",
                "metroCode": "",
                "virtualDeviceDetails": [],
                "createdBy": "user1",
                "createdDate": "2022-08-31T18:36:24.218Z"
            },
            {
                "name": "T2",
                "uuid": "67899",
                "description": "subnet2",
                "inboundRules": [
                    {
                        "seqNo": 1,
                        "subnets": [
                            "1.1.1.0/24"
                        ],
                        "description": "s1",
                        "subnet": "1.1.1.0/24",
                        "protocol": "IP",
                        "srcPort": "any",
                        "dstPort": "any"
                    },
                    {
                        "seqNo": 2,
                        "subnets": [
                            "2.2.2.2/32"
                        ],
                        "description": "s2",
                        "subnet": "2.2.2.2/32",
                        "protocol": "IP",
                        "srcPort": "any",
                        "dstPort": "any"
                    },
                    {
                        "seqNo": 3,
                        "subnets": [
                            "3.3.3.3/32"
                        ],
                        "description": "s3",
                        "subnet": "3.3.3.3/32",
                        "protocol": "IP",
                        "srcPort": "any",
                        "dstPort": "any"
                    }
                ],
                "metroName": "",
                "metroCode": "",
                "virtualDeviceDetails": [],
                "createdBy": "user2",
                "createdDate": "2022-08-31T18:01:13.809Z"
            }
        ]
    }
def get_templates():
    """
    Gets all templates from API
    """
    api_path = "https://api.vendor.com"
    headers = {"Content-Type": "application/json", "Authorization": "Bearer " + get_token()}
    payload = {}
    templates = requests.get(f"{api_path}/v1/Templates", headers=headers, data=payload)
    table = PrettyTable(["UUID", "Name", "Inbound Subnets"])
    if templates.json()['pagination']['total'] > 0:
        for template in templates.json()['data']:
            table.add_row([template['uuid'], template['name'], template['inboundRules'][0]['subnets']])
    print(table)

Actual Results

+-------+------+-------------------+
| UUID  | Name |   Inbound Subnets |
+-------+------+-------------------+
| 12345 |  T1  |   ['1.1.1.0/24']  |
| 67899 |  T2  |   ['1.1.1.0/24']  |
+-------+------+-------------------+

Desired Results

+-------+------+--------------------------------------------------+
| UUID  | Name |                    Inbound Subnets               |
+-------+------+--------------------------------------------------+
| 12345 |  T1  |   ['1.1.1.0/24']                                 |
| 67899 |  T2  |   ['1.1.1.0/24'], ['2.2.2.2/32'], ['3.3.3.3/32'] |
+-------+------+--------------------------------------------------+

r/learningpython • • Aug 10 '22

Root finding in case of multivariable functions

1 Upvotes

Hello, everyone,

I am trying to find the roots of a function which is basically a mapping from R12x1 to R 6x3. I am using fsolve to find the roots but it throws an error saying :

fsolve: there is a mismatch between the input and output shape of the 'func' argument 'f'.Shape should be (12,) but it is (6,3).

Any suggestion would be of great help.

Thank you.