r/pythonhelp • • Apr 27 '26

How to add a string to a list, and then remove it if the string if it is not found in a second list

2 Upvotes

I'm pretty new to Python, and I'm trying to make a rudimentary "therapy chatbot" (something a little more in depth than Eliza, made more so as practice of simple concepts). I'm trying to have the user input an emotion, and then pop up with some text that it wasn't found in the majorEmotionTypes list, and then try again. I know my code is pretty far from what I want, but I'll be going back later to edit a few things.

The main issue is that it can't find 'i' in the majorEmotionTypes list. Any help would be deeply appreciated!

majorEmotionTypes = ["Sad", "Scared", "Mad", "Happy", "Disgusted", "Surprised"]
currentMajorEmotions = []
capCurrentMajorEmotions = []


for i in range(1, 3):
    currentMajorEmotions.append(input("Which of these emotions are you feeling?:
").capitalize())
    if i not in majorEmotionTypes:
        currentMajorEmotions.remove(i)
        print("Not a valid entry")
        currentMajorEmotions.append(input("Try again: ").capitalize())

r/pythonhelp • • Apr 23 '26

Need Assistance With A Problem

2 Upvotes

hey guys

I need abit of help, here's a problem I have no clue how to solve

You're given a set of rows

['0','0','0','0']

['0','0','1','0']

['1','1','0','0']

['0','1','1','0']

and given a few rules taking i as an item in each row

  1. Each row has to have an equal number of 1s and 2s and no 0s

  2. A row can't have more than 2 of the same numbers following each other (1110 is invalid but 1100 is valid)

how would you rewrite each row using python so as it works even if the number of items were 6,8 or even 12 so that each row has an equal number of 1s and 2s without any 0s in the row (Basically if 2 1s are next to each other, the next one should be a 2 and vice versa)


r/pythonhelp • • Mar 16 '26

New to Software Dev

Thumbnail reddit.com
2 Upvotes

r/pythonhelp • • Dec 03 '25

Where do I start? I’m a bit stuck.

Thumbnail reddit.com
2 Upvotes

r/pythonhelp • • Sep 24 '25

capture naughty async processes

2 Upvotes

Python noob. I'm using asyncio to interface a UCI chess engine.

Whenever I make ANY mistake in the coding inside my async main function, the script terminates but the engine (stockfish) process stays running , using significant CPU, at which point I have to terminate the process from my activity monitor. I also have the engine set to log a debug file. After the script crashes, the log immediately begins to rapidly balloon in size (like a dozen of gb per minute). Looking closer, it's just filling with $FF.

Anyway, it's getting annoying. Is there a way to make my script crash more gracefully? Ideally closing the log file and terminating the engine.

Below is a stripped down overview of my script. Sorry if I left anything important out, but I'm happy to provide. Thanks in advance.

import asyncio
import chess
import chess.engine
...

async def main() -> None:

    transport, sfEngine = await chess.engine.popen_uci("/opt/homebrew/bin/stockfish") # spawn engine
    ...
    await sfEngine.configure({"Debug Log File": sfLog})
    ...
    for number, move in enumerate(gameMoves.mainline_moves()):
        ...
        sfAnalysis = await sfEngine.analyse(gameBoard, chess.engine.Limit(depth=sfDepth, time=sfMovetime / 1000))    
        ...

    await sfEngine.quit()

asyncio.run(main(), debug=False)
...
print ("\nFinished.")

r/pythonhelp • • Sep 23 '25

SOLVED No Exceptions are thrown but no file is created.

2 Upvotes

SOLVED -- ISSUE WAS DETERMINED TO BE THAT THE OUTPUT DIRECTORY WAS NOT KNOWN, SOLVED BY USING OS.GETCWD TO FIND ITS LOCATION

I have this section of code:

    html = strbuilder()

    with open('output.html', 'w', encoding='utf-8') as wrto:
        wrto.write(html)

What this code is supposed to do:

  • Take the String created in strbuilder() (has been determined to work just fine, and does produce a string, seeing as it can successfully print to the terminal)

  • Write this string to a file named output.html with utf-8 encoding ( this program needs to be able to handle Unicode.)

The issue present is that, while no exceptions are crashing the program, no file, not even a blank file, is found at the program's directory.

(variants with a wrto.close instruction have the same result)

What could be causing this issue?


r/pythonhelp • • Sep 22 '25

Scraping on Cardmarket

2 Upvotes

I'm trying to scrape data on cardmarket with python but everytime I try to load more product I get blocked by anti BOT System.
Could anyone suggest me a strategy, please?


r/pythonhelp • • Apr 18 '25

Python Libraries Recommendation for all types of content extraction from different files extensions

2 Upvotes

I am a fresher given a task to extract all types of contents from different files extensions and yes, "main folder path" would be given by the user..

I searched online and found like unstructured, tika and others..

Here's a catch "tika" has auto language detection (my choice), but is dependent on Java as well..

Please kindly recommend any module 'or' like a combination of modules that can help me in achieving the same without any further dependencies coming with it....

PS: the extracted would be later on used by other development teams for some analysis or maybe client chatbots (not sure)


r/pythonhelp • • Mar 17 '25

I can’t figure out how to create a function that searches the user input and returns the average of the word count

2 Upvotes

i have been tasked with finding the average word count of a given list (input) which would be separated by a numbers (1. , 2. , etc) WITHOUT using loops but i can’t for the life of me figure it out.


r/pythonhelp • • Jan 30 '25

Need assistance with some code

2 Upvotes

I am a new coder and I am trying to use variables to make a calculator, but when I add them together it just pushes them together, for example 1 + 2 =12

The code is:

first_number = input(print(“First number here: “)) second_number = input(print(“Second number here: “))

print(first_number + second_number)

Any help would be much appreciated!!!


r/pythonhelp • • Jan 20 '25

What should I do?

2 Upvotes

Hello everyone,

I some how formatted one of my drive on my windows computer in which i downloaded python , and now when i am trying to install it new drive it show the Modify Setup dialog box , but if try to uninstall , modify or repair it ends up with errors like 0x80070643 and 0x80070641. I already tried running it as an administrator and repairing my .NET Framework. What can i do to run Python again.


r/pythonhelp • • Jan 04 '25

Script for matching columns in multiple txt files vs a CSV file

2 Upvotes

I have this code (below), four txt files with either 23andMe or AncestryDNA data, and a CSV file with 21 million rows of gene mutations. The goal is to match chromosome and position of the txt files to the chromosome and position of the csv file. If they match, the script puts "found" in a new column labelled "Found". and copy the rsID from the txt file into the csv file in a column labelled rsID. I need it to use the text file as the file it uses to read and the csv file to use to find and add because the CSV file is so long. (What have I gotten myself into, I know). It may find the same chromosome+position up to three times, so it needs to keep checking until it hits the three times or it reaches the end of the CSV.

After it tries to find all the chromosome and position matches, it needs to delete all the rows of the CSV file that do not contain the word "found".

This is my header plus first row for the txt files:

rsid chromosome position allele1 allele2

rs369202065 1 569388 G G

This is my header plus first row of the CSV:

#CHROM,POS,REF,ALT,genome,uniprot_id,transcript_id,protein_variant,am_pathogenicity,am_class

12,8192694,T,A,hg19,Q9P0K8,ENST00000162391.3,L89H,1.0,pathogenic

This is my code (Note I have tried #CHROM and CHROM):

# -*- coding: utf-8 -*-

"""

Created on Sat Jan 4 13:25:47 2025

@author: hubba

"""

import pandas as pd

def process_dna_files(dna_files, csv_file, output_csv):

csv_data = pd.read_csv(csv_file, delimiter=",", comment="#") # Adjust delimiter and handle comments

csv_data.columns = csv_data.columns.str.lstrip("#")

for dna_file in dna_files:

# Locate the start of the data in the DNA file

with open(dna_file, 'r') as f:

lines = f.readlines()

start_line = 0

for i, line in enumerate(lines):

if line.strip().startswith("rsid"):

start_line = i

break

dna_data = pd.read_csv(dna_file, delimiter="\t", skiprows=start_line, low_memory=False)

csv_data["Found"] = False

csv_data["rsID"] = ""

for _, dna_row in dna_data.iterrows():

# Extract chromosome and position

chromosome = dna_row["chromosome"]

position = dna_row["position"]

matches = csv_data[(csv_data["#CHROM"] == chromosome) & (csv_data["POS"] == position)]

for index in matches.index:

csv_data.at[index, "Found"] = True

csv_data.at[index, "rsID"] = dna_row["rsid"]

csv_data = csv_data[csv_data["Found"] == True]

csv_data.to_csv(output_csv, index=False, sep=",")

print(f"Updated CSV saved to: {output_csv}")

dna_files = ["Example1.txt", "Example2.txt", "Example3.txt", "Example4.txt", "Example5.txt", "Example6.txt"]

csv_file = "GeneticMutations.csv"

output_csv = "GeneticMutationsplusRSID.csv"

process_dna_files(dna_files, csv_file, output_csv)

Here is the error message I am getting:

%runfile C:/Users/hubba/OneDrive/Desktop/untitled12.py --wdir

Traceback (most recent call last):

File ~\AppData\Local\spyder-6\envs\spyder-runtime\Lib\site-packages\pandas\core\indexes\base.py:3805 in get_loc

return self._engine.get_loc(casted_key)

File index.pyx:167 in pandas._libs.index.IndexEngine.get_loc

File index.pyx:196 in pandas._libs.index.IndexEngine.get_loc

File pandas\_libs\\hashtable_class_helper.pxi:7081 in pandas._libs.hashtable.PyObjectHashTable.get_item

File pandas\_libs\\hashtable_class_helper.pxi:7089 in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: '#CHROM'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):

File ~\AppData\Local\spyder-6\envs\spyder-runtime\Lib\site-packages\spyder_kernels\customize\utils.py:209 in exec_encapsulate_locals

exec_fun(compile(code_ast, filename, "exec"), globals)

File c:\users\hubba\onedrive\desktop\untitled12.py:67

process_dna_files(dna_files, csv_file, output_csv)

File c:\users\hubba\onedrive\desktop\untitled12.py:47 in process_dna_files

matches = csv_data[(csv_data["#CHROM"] == chromosome) & (csv_data["POS"] == position)]

File ~\AppData\Local\spyder-6\envs\spyder-runtime\Lib\site-packages\pandas\core\frame.py:4102 in __getitem__

indexer = self.columns.get_loc(key)

File ~\AppData\Local\spyder-6\envs\spyder-runtime\Lib\site-packages\pandas\core\indexes\base.py:3812 in get_loc

raise KeyError(key) from err

KeyError: '#CHROM'

If it matters, Im using Spyder

What am I doing wrong???? Im losing my mind lol


r/pythonhelp • • Dec 28 '24

RuntimeError: "Timeout context manager should be used inside a task" with pytest-asyncio but works in direct Python execution

2 Upvotes

Using asyncio and aiohttp in an application I'm building and can't seem to figure out how to get pytest playing nicely. When I use pytest I always get a

RuntimeError: Timeout context manager should be used inside a task

If I do the same functions that pytest is calling just in main(), the problem seems to go away. I uploaded a repo to easily reproduce at https://github.com/bcherb2/async_bug

I have tried just about every solution and hack I can find, and nothing seems to work (nest_asyncio, pytest plugins, etc.)

Here is the failing code:

#api_client.py
import aiohttp
import uuid
import json
from enum import Enum
from typing import Optional, Dict, Any
from loguru import logger

class RetCode(Enum):
    NO_ERROR = 200
    BAD_REQUEST = 400
    UNAUTHORIZED = 401
    NOT_FOUND = 404


class DemoAPIClient:
    """Demo REST client that simulates behavior similar to ANTServerRESTClient."""
    
    def __init__(
        self,
        base_url: str = "https://jsonplaceholder.typicode.com",
        timeout: int = 30
    ):
        """Initialize the API client.
        
        Args:
            base_url: Base URL for the API
            timeout: Request timeout in seconds
        """
        self.base_url = base_url
        self.timeout = timeout
        
        # Session management
        self._session: Optional[aiohttp.ClientSession] = None
        self._session_token: Optional[str] = None

    async def _ensure_session(self) -> aiohttp.ClientSession:
        """Ensure we have an active session, creating one if necessary."""
        if self._session is None or self._session.closed:
            connector = aiohttp.TCPConnector(force_close=True)  
            self._session = aiohttp.ClientSession(
                connector=connector,
                timeout=aiohttp.ClientTimeout(total=self.timeout)
            )
        return self._session

    async def close(self) -> None:
        """Close the client session."""
        if self._session:
            await self._session.close()
            self._session = None
            logger.debug("Session closed")

    async def login(self) -> None:
        """Simulate login by making a test request."""
        try:

            test_url = f"{self.base_url}/posts/1"
            session = await self._ensure_session()
            
            async with session.get(test_url) as response:
                if response.status != 200:
                    raise aiohttp.ClientResponseError(
                        request_info=response.request_info,
                        history=response.history,
                        status=response.status,
                        message=f"Login failed with status {response.status}"
                    )
                
                # Simulate session token
                self._session_token = str(uuid.uuid4())
                logger.info("Successfully logged in to API")
                
        except Exception as e:
            logger.error(f"Login failed: {str(e)}")
            raise

    async def rest(
        self,
        endpoint: str,
        method: str,
        data: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """Execute a REST request.
        
        Args:
            endpoint: The endpoint path (e.g., '/posts')
            method: HTTP method (GET, POST, etc.)
            data: Optional request body data
            
        Returns:
            Dict containing the parsed response data
        """
        if not self._session_token:
            raise RuntimeError("Not logged in. Call login() first")
            
        session = await self._ensure_session()
        request_id = str(uuid.uuid4())[:8]
        url = f"{self.base_url}{endpoint}"

        try:
            logger.debug(f"[{request_id}] {method} {url}")
            if data:
                logger.debug(f"[{request_id}] Request body: {data}")

            headers = {"Authorization": f"Bearer {self._session_token}"}
            
            async with session.request(
                method=method,
                url=url,
                json=data,
                headers=headers
            ) as response:
                response_text = await response.text()
                logger.debug(f"[{request_id}] Response: {response_text}")
                
                if response.status >= 400:
                    raise aiohttp.ClientResponseError(
                        request_info=response.request_info,
                        history=response.history,
                        status=response.status,
                        message=f"Request failed: {response_text}"
                    )
                    
                return json.loads(response_text)

        except Exception as e:
            logger.error(f"[{request_id}] Request failed: {str(e)}")
            raise



#conftest.py

import pytest_asyncio
from loguru import logger
from api_client import DemoAPIClient

def pytest_configure(config):
    config.option.asyncio_mode = "auto"


@pytest_asyncio.fixture(scope="module")
async def api_client():
    """Fixture to provide an authenticated API client."""
    logger.info("Setting up API client")
    client = DemoAPIClient()
    
    try:
        await client.login()
        logger.info("API client logged in successfully")
        yield client
    finally:
        await client.close()
        logger.info("API client closed")




#test_api_client.py

import pytest
import asyncio
from loguru import logger
from api_client import DemoAPIClient


async def ensure_task_context():
    """Helper to ensure we're in a task context."""
    if asyncio.current_task() is None:
        task = asyncio.create_task(asyncio.sleep(0))
        await task


@pytest.mark.asyncio
async def test_client_setup(api_client):
    """Test basic client setup."""
    logger.debug("Testing client setup")
    assert api_client._session_token is not None
    assert api_client._session is not None
    logger.debug("Client setup verified")


@pytest.mark.asyncio
async def test_get_post(api_client):
    """Test retrieving a post."""
    await ensure_task_context()  # Try to ensure task context
    
    try:
        response = await api_client.rest("/posts/1", "GET")
        assert response is not None
        assert "id" in response
        assert response["id"] == 1
    except Exception as e:
        logger.error(f"Test failed: {str(e)}")
        raise


@pytest.mark.asyncio
async def test_create_post(api_client):
    """Test creating a new post."""
    await ensure_task_context()  # Try to ensure task context
    
    try:
        new_post = {
            "title": "Test Post",
            "body": "Test Content",
            "userId": 1
        }
        response = await api_client.rest("/posts", "POST", new_post)
        assert response is not None
        assert "id" in response
        assert response["title"] == "Test Post"
    except Exception as e:
        logger.error(f"Test failed: {str(e)}")
        raise


async def main():
    """Main function to run tests directly without pytest."""
    logger.info("Starting direct test execution")

    client = DemoAPIClient()
    
    try:
        await client.login()
        logger.info("Client logged in")
        
        logger.info("Running test_client_setup")
        await test_client_setup(client)
        logger.info("Client setup test passed")
        
        logger.info("Running test_get_post")
        await test_get_post(client)
        logger.info("Get post test passed")
        
        logger.info("Running test_create_post")
        await test_create_post(client)
        logger.info("Create post test passed")
        
    except Exception as e:
        logger.error(f"Test execution failed: {str(e)}")
        raise
    finally:
        logger.info("Cleaning up client")
        await client.close()
        logger.info("Client closed")


if __name__ == "__main__":
    asyncio.run(main())

then just run pytest test_api_client.py and python test_api_client.py. Why is this failing? Is there any way to fix this?


r/pythonhelp • • Dec 17 '24

"RecursionError" raises when doing "sys.argv[0]"

2 Upvotes

I am not sure what I did wrong at all!

This is the error:

Traceback (most recent call last):
  ...
  File "c:\...\Paths.py", line 11, in wrapper
    basePath: str = os.path.dirname(sys.argv[0])
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RecursionError: maximum recursion depth exceeded

And this is my code:

import os
import sys
import typing


class Paths:
    @staticmethod
    def pathDecorator(folderName: str) -> typing.Callable[..., typing.Callable[..., str]]:
        def decorator(_: typing.Callable[..., str]) -> typing.Callable[..., str]:
            def wrapper(fileName: str) -> str:
                basePath: str = os.path.dirname(sys.argv[0])
                path: str = os.path.join(basePath, "Assets", folderName, fileName)
                return os.path.normpath(path).replace("\\", "/")
            return wrapper
        return decorator

    @pathDecorator("Images")
    @staticmethod
    def image(fileName: str) -> str:
        return fileName

    @pathDecorator("Sounds")
    @staticmethod
    def sound(fileName: str) -> str:
        return fileName

    @pathDecorator("Styles")
    @staticmethod
    def styles(fileName: str) -> str:
        return fileName

r/pythonhelp • • Nov 26 '24

how do i make dynamic strings in a for loop (or alternatives)?

2 Upvotes

i am working with pandas. i read in a table built like att1, att2 .... classification and want to search elements like att1=valuex and class=valuea att1=valuex and class=valueb and so on. for that i want to build a for loop that starts with att1 and moves on to att2 and so on. how do i program something like

for i in range(something):

do something with att{i}

? i am quite bad at programming and i do not even know how i can formulate something like this to google it. please send help


r/pythonhelp • • Nov 24 '24

Clear buffer in keyboard module in Python.

2 Upvotes

I'm having difficulty with a project I'm working on.

It's a small Text RPG, I imported the keyboard module to make the choices more similar to games, but when the user presses "enter", it skips the next entry. In this case, it is a function that when I press continue skips the name entry.


r/pythonhelp • • Oct 15 '24

matplotlib boxplot and barplot not aligned

2 Upvotes

Hi,

I'm trying to plot a data set using boxplots. I want to label the mean of each category and the least-effort way I found was using a bar plot, using pyplot.bar_label() and ploting a boxplot on top. Unfortunatly, my plots don't align on their categories. Do you have any idea what's going on?

Here are my bar plot, boxplot and the combined plot : https://youtu.be/JoEuFSIH9s0 (I'm not allowed pictures, for some reason)

Here is my code for plotting :

    # I have df1, a DataFrame containing the mean Exam_Score for each category
    #   and df2, a DataFrame containing the category of each individual in the first 
    #   column and its Exam_Score in the second one

    # Plotting the bar plot
    # Ordering the categories
    categories_set = set(df1.index)
    categories = ["Male","Female"]  # This is used to order the categories

    # Order the values of Exam_Score in the same order as categories
    values = []
    for i in range(len(categories)):
        values.append(df1.iat[df1.index.tolist().index(categories[i]),0])

    # Plot bar plot
    ax = plt.bar(categories,values)
    plt.bar_label(ax)  # Add mean value labels
    
    # Plotting the boxplot
    # Make a 2D array of which each column only contains values of a certain category
    #  and which has the same column order as categories[]
    plots = []
    for i in range(len(categories)):
        plots.append(df2[df2[df2.columns[0]] == categories[i]][df2.columns[1]])

    # Plot boxplot
    ax = plt.boxplot(plots, tick_labels=categories)

    # Configure appearance
    plt.title(name) # name is declared earlier
    plt.xticks(rotation=45)
    plt.gca().set_ylim(ymin = 50)
    plt.grid()
    plt.show()

P.S. I know there are other ways to acheive what I want, but I'm not very used to working with matplotlib or python and this is for an issagnement due in a short time, so I don't hav time to dive deep in configuration functions. And besides, it would still be very helpful to know why theses don't align.


r/pythonhelp • • Jul 30 '24

python assignment

2 Upvotes

i m studying computer science and i am first semester. i need help with python assignment.


r/pythonhelp • • Jul 20 '24

INACTIVE How To Run .Py program

2 Upvotes

i have been trying to run this python program, both on mobile and pc, but I can't figure out what to do. The instructions are not very clear.

could someone could possibly give me step by step instructions on how to run and use this script? https://github.com/rahaaatul/TokySnatcher

please and thank you


r/pythonhelp • • Jul 02 '24

Import pmdarima as pm keeps giving ValueError

2 Upvotes

I'm using Pycharm and I've literally only been trying to import the pmdarima package. My code consists of only 2 lines:

import numpy as np
import pmdarima as pm

I will end up also needing to use pandas and matplotlib (to complicate the compatibility requirements that much more).

I can't imagine what I'm doing wrong in these 2 simple lines, but I have uninstalled and reinstalled numpy, pmdarima, and pandas a hundred times by now and nothing seems to be working. Also tried pip install and it has been less than useless.

Numpy version is 2.0.0

Pandas version is 2.2.2

pmdarima versio is 2.0.4

This is what I get no matter which version I use:

ValueError: numpy.dtype size changed, may indicate binary incompatibility. Expected 96 from C header, got 88 from PyObject\

Please help as this error makes no sense to me.


r/pythonhelp • • Jun 07 '24

Accessing an OpenAPI endpoint?

2 Upvotes

Hi everyone.

This feels like it should be super simple, but I just cannot figure it out.

I've downloaded the ebay openapi spec for their fulfilment api...

https://developer.ebay.com/api-docs/master/sell/fulfillment/openapi/3/sell_fulfillment_v1_oas3.json

...and I've generated the client using openapi-python-client, and imported and instantiated the client like so:

from fulfillment_api_client import AuthenticatedClient

client = AuthenticatedClient(
    base_url="https://api.ebay.com", token="XXX"
)

But then I get stuck.#

The openapi spec describes an endpoint path (e.g. /order/{orderId}) like so:

"paths": {
    "/order/{orderId}": {
      "get": {
        "tags": [
          "order"
        ],
        "description": ...",
        "operationId": "getOrder",
        "parameters": [
          {
            "name": "fieldGroups",
            "in": "query",
            "description": ...",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "orderId",
            "in": "path",
            "description": "...",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Success",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Order"
                }
              }
            }
          },
          "400": {
            "description": "Bad Request",
            "x-response-codes": {
              "errors": {
                "32100": {
                  "domain": "API_FULFILLMENT",
                  "category": "REQUEST",
                  "description": "Invalid order ID: {orderId}"
                },
                "32800": {
                  "domain": "API_FULFILLMENT",
                  "category": "REQUEST",
                  "description": "Invalid field group: {fieldGroup}"
                }
              }
            }
          },
          "404": {
            "description": "Not Found"
          },
          "500": {
            "description": "Internal Server Error",
            "x-response-codes": {
              "errors": {
                "30500": {
                  "domain": "API_FULFILLMENT",
                  "category": "APPLICATION",
                  "description": "System error"
                }
              }
            }
          }
        },
        "security": [
          {
            "api_auth": [
              "https://api.ebay.com/oauth/api_scope/sell.fulfillment",
              "https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly"
            ]
          }
        ]
      }
    }

But I have no idea how to access that using the client in python.

Can anyone help. Thank you in advance! 😊


r/pythonhelp • • Apr 18 '24

Need hel[ with coding robot barista

2 Upvotes

Hello!

I'm new to python and i was coding a robot barista, but every time i awnser "good" it just closes.

Is anyone willing to help me with this problem?

Thank you!

P.S. English is not my first language and i had to translate my code so sorry if the talking in the code sounds a bit weird.

This is my python script:

#Robot barista:

import time

input()

print ("\n")

print("Hello, Welkom to Bob's coffee!")

time.sleep(2)

print("What's your name?")

name = input()

time.sleep(1)

print ("\nHello " + name + "!")

time.sleep(1)

mood = input("How are you doing?\n")

if mood =="good":

print("Oh, that's good to hear!\n")

time.sleep(1)

if mood =="Good":

print("Oh, that's good to hear!\n")

time.sleep(1)

if mood =="Good!":

print("Oh, that's good to hear!\n")

time.sleep(1)

if mood =="good!":

print("Oh, that's good to hear!\n")

time.sleep(1)

if mood == "bad":

print("Oh, that's not nice to hear")

input ("Why are you doing bad?\n")

print("Hmm... I hope you will be ok soon!\n")

time.sleep(1)

a = input("Would you like something to Eat/Drink?\n")

time.sleep(2)

if mood == "Bad":

print("Oh, that's not nice to hear")

input ("Why are you doing bad?\n")

print("Hmm... I hope you will be ok soon!\n")

time.sleep(1)

a = input("Would you like something to Eat/Drink?\n")

time.sleep(2)

if mood == "Bad!":

print("Oh, that's not nice to hear")

input ("Why are you doing bad?\n")

print("Hmm... I hope you will be ok soon!\n")

time.sleep(1)

a = input("Would you like something to Eat/Drink?\n")

time.sleep(2)

if mood == "bad!":

print("Oh, that's not nice to hear")

input ("Why are you doing bad?\n")

print("Hmm... I hope you will be ok soon!\n")

time.sleep(1)

a = input("Would you like something to Eat/Drink?\n")

time.sleep(2)

if a == "No":

print("Ok\nBye!")

time.sleep(1)

quit()

if a == "Yes":

print(" \n" * 100)

print("This is the menu:\n Latte, Black Cofee, Ice Cofee and Appele Cake")

time.sleep(1)

print("What would you like to order?")

input()


r/pythonhelp • • Apr 03 '24

Termcolor in python

2 Upvotes

Hey guys, I'm coding a project for school and was using 'termcolor' make my text pop, but I ran into a issue where I wanted to add both a color and attribute to text but I want to store the text formatting in a variable so its easy to change.

My current line looks like: error_colour = "light_yellow", attrs = [("bold")] # Error code colour

Any help to make this work would be a great help.

Thanks.


r/pythonhelp • • Feb 22 '24

How to integrate python with snowflake dp in real time projects

2 Upvotes

Hi folks,

Could you help me understand how Python is deployed with Snowflake in real-time projects? I'm curious about its usage and implementation. Can anyone share their experience with a project where they deployed Python for migration in Snowflake or included Python in their Snowflake projects? Thank you!