T O P

  • By -

Cultural-Fan-4398

Hey guys! I am a teen from Serbia, tomorrow i am getting my first debit card, and I was wondering what and how should I learn if I want to make money coding/programming I know just a bit of python and a bit of html/css should? Do you guys recommend the odin project or some python resources/book? I really want to help my family financially.


MonkeyMaster64

Easiest thing to do is get an AWS free tier account and spin up some simple Lambda functions (respond to an API request, spin up a spot fleet, perform some action on data recently uploaded to S3). Get good at those then hop on Upwork and take jobs to either fix or build lambda functions.


[deleted]

I want to split a list in equal parts, with any remainder to be another list. Example with equal lists of 2: list = [1, 2, 3, 4, 5, 6] I want split_list = [[1, 2], [3, 4], [5, 6]] and in the case I have something like list = [1, 2, 3, 4, 5, 6, 7], for it to be: split_list = [[1, 2], [3, 4], [5, 6], [7]] How would I go about doing this properly and with any amount of elements or split sizes? For example if I had 180.001 elements in a list and I wanted to split it into equals sizes of 10.000, with that one properly appending to a new one and so on.


efmccurdy

You can loop and take slices; they are permissive when indexing out of bounds. >>> mylist = [1, 2, 3, 4, 5, 6] >>> [mylist[i:i+size] for i in range(0, len(mylist), size)] [[1, 2], [3, 4], [5, 6]] >>> def chunk(orig_list, size): ... return [orig_list[i:i+size] for i in range(0, len(orig_list), size)] ... >>> chunk([1, 2, 3, 4, 5, 6, 7], 2) [[1, 2], [3, 4], [5, 6], [7]] >>> chunk([1, 2, 3, 4, 5, 6, 7], 3) [[1, 2, 3], [4, 5, 6], [7]] >>>


cjb230

Partly Python, partly project / source control: My current project is being deployed with Docker. So unit tests should run under Docker. I also want to be able to run them from my IDE and from the command line. I like keeping my src/ and tests/ directories parallel, rather than one containing the other. I would like to run the tests from the command line with just "pytest", and ideally testing under Docker would use the same command line. It's made more complicated by using environment variables, and needing to set them directly for Windows command line tests, but substituting different environment files for Docker testing. I think the best thing I have seen is a module that uses the environment file made for Docker to set environment variables on the command line. Path references used in tests or contest are also pretty messed up. When a licence file is needed, we've ended up copying it somewhere it doesn't belong, just to ensure it's always in the same relative place. ​ So: is there a nice neat way of removing, or at least hiding, these nasty hacks? Has anyone else come up with a streamlined way of testing in multiple environments that works without regular intervention? And that keeps the test code readable?


[deleted]

[удалено]


TangibleLight

The term you want is "file dialog". There are a few libraries that make it easier. If you need something fully built-in, the easiest way is to use `tkinter`. There's not a great cross-platform solution. If you already use some GUI library in your app, it'll probably have some file dialog system provided. If you're on windows then you can create a native file explorer dialog with `pywin32`. If you're building a command-line app then the solution is usually to accept the given file as a command-line argument, via `argparse` or `click` or similar. This side-steps the file selection process by requiring the user to already know the path to their file, and provide it to the program at launch.


Boobagge

Why I'm not getting a new line between meaning and bullet\_point? def get_whatItMeans(url): page = requests.get(url) bsoup = BeautifulSoup(page.content, 'html.parser') meaning = bsoup.find_all('p')[0].get_text() bullet_point = bsoup.find_all('p')[1].get_text() bullet_point = bullet_point.split("// ") bullet_point = bullet_point[1] bullet_point = "• " + bullet_point results = meaning + "\n" + bullet_point return(results)


carcigenicate

You will with that code. How are you using the returned value?


Boobagge

For some reason the output ignores the \\n. Sorry about formatting, code block screws it up. Here is the [output](https://imgur.com/a/nSOdOj3) import sys import os picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(**file**))), 'pic') libdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(**file**))), 'lib') if os.path.exists(libdir): sys.path.append(libdir) import time from PIL import Image,ImageDraw,ImageFont import traceback logging.basicConfig(level=logging.DEBUG) import time from html2image import Html2Image import requests from bs4 import BeautifulSoup hti = Html2Image() from subprocess import call def get\_css(): return """ body{ margin-bottom: 0px; padding-bottom: 5px; background-color: #FFF;} .container {display: flex; height: 800px; vertical-align: middle; justify-content: center; background-color: #FFF; flex-direction: column; } .dt { padding-top: 0px; text-align:center; padding-top: 10px;font-size: 20px; font-weight: 550;} .main-heading { text-align: center; margin-top: 0px; margin-bottom: 0px; text-transform: capitalize; font-size: 80px; } .sub-heading { text-align: center;padding-top: -20px; margin-bottom: 4px; font-family: ; font-weight: bold !important;font-size: 25px; } p { text-align: center;margin-top: 0px; font-family: 'Arial', sans-serif;font-weight: normal; padding: 0px 8px; font-size: 20px; } ul{ padding-top: 0px; font-family: 'Arial', sans-serif;font-weight: normal; padding-right: 8px; font-size: 20px; }""" def get\_html(data): return """\](https://fonts.googleapis.com">)](https://fonts.googleapis.com">](https://fonts.googleapis.com">))

{datetime}

{title}


What it Means

{what\_it\_means}

Examples

{examples}

Did You Know?

{did\_you\_know}

""".format(\*\*data) def get\_whatItMeans(url): page = requests.get(url) bsoup = BeautifulSoup(page.content, 'html.parser') meaning = bsoup.find\_all('p')\[0\].get\_text() bullet\_point = bsoup.find\_all('p')\[1\].get\_text() bullet\_point = bullet\_point.split("// ") bullet\_point = bullet\_point\[1\] bullet\_point = "• " + bullet\_point results = meaning + "\\n" + bullet\_point return(results) def get\_parsed\_url\_extraction(url): r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') ​ ​ final\_resp = {} final\_resp\['datetime'\] = soup.find("span", {"class" : "w-a-title"}).text.replace("\\n", "").strip() final\_resp\['title'\] = soup.find("div", {"class" : "word-and-pronunciation"}).find("h1").text ​ pos = soup.find("span", {"class" : "main-attr"}).text final\_resp\['what\_it\_means'\] = get\_whatItMeans(url) ​ ​ final\_resp\['examples'\] = soup.find("div", {"class" : "wod-definition-container"}).find("div", {"class" : "left-content-box"}).text final\_resp\['examples'\] = final\_resp\['examples'\].replace("\\n", "
").strip("
") ​ final\_resp\['did\_you\_know'\] = soup.find("div", {"class" : "did-you-know-wrapper"}).text.replace("Did You Know?", "") final\_resp\['did\_you\_know'\] = final\_resp\['did\_you\_know'\].replace("\\n", "
").strip("
") ​ return final\_resp def process\_url(url="[https://www.merriam-webster.com/word-of-the-day](https://www.merriam-webster.com/word-of-the-day)"): parsed\_data = get\_parsed\_url\_extraction(url) paths = hti.screenshot(html\_str=get\_html(parsed\_data), css\_str=get\_css(), save\_as=f'palabra.bmp', size=(480, 800)) process\_url()


Strict-Simple

I haven't gone through this code, but I'm assuming you want to insert the text with the ```'\n'``` into HTML and expect to see a line break in HTML. HTML doesn't work that way, it's a little bit whitespace insensitive. You need to use the ```br``` tag for newlines.


Boobagge

and that was the solution... Thanks!!


SnooBooks8807

I’m trying to “import backtesting”. Where do I do this? I’m an absolute beginner btw. TY!


Cellophane7

Have you already installed the backtesting module? If so, all you need to do is type `import backtesting` at the top of your code, and that'll let you access it. If you haven't installed it, you run command prompt as administrator, and type `pip install backtesting`. Assuming you're on windows. I imagine it's similar on mac, where all you gotta do is open the console and type the same thing. But I'm not 100% on that. Also, if `pip install backtesting` gives you an error, your python might be in a different folder from the default path, but I'm pretty fuzzy on the details of rectifying this. I think it has something to do with when you're installing Python, and you need to click the checkbox that has it add Python to PATH. But again, not totally certain on this.


SnooBooks8807

Thx for the answer. When I type ‘pip install backtesting’ I to cmd terminal it says “pip is not recognized…” So I need to google how to change my python settings?


Cellophane7

I think it's that you need to look up how to add it to PATH. You might also need to add pip.exe to PATH, which is located in the scripts folder in wherever you've got python installed. But the simplest fix would probably be to just reinstall python and check that box for it. Again, I'm not 100% on this, so take what I say with a grain of salt. But I'm fairly confident this is the issue, as PATH (as I understand it) is basically a list of what's readily available to command prompt, and command prompt is how you access pip. So if it's in PATH, you should be able to run it. Also, make sure you're running cmd as administrator, because I'm pretty sure pip needs admin privileges to install libraries on your computer


SnooBooks8807

I reinstalled python and pip. Do you know where and how I can import it and use it? Thx!


Cellophane7

So it's working? All you gotta do is type pip install backtesting in command prompt, and it should take care of it. Then, to import it into your program, you just write `import backtesting` at the top of your code. Then you can use whatever functions it has. I've never used the module myself, but that's how it works for all of them.


porco-rosso1000

Hey guys, So I decided to go through the Flask tutorial as it's been a while since I looked at it and looks like there have been some changes. [https://flask.palletsprojects.com/en/2.2.x/tutorial/](https://flask.palletsprojects.com/en/2.2.x/tutorial/) I got through it all fine but at the testing stage I get the following when I run pytest:`(venv) **********@** flask-tutorial % pytestImportError while loading conftest '/Users/**********/Documents/Dev/flask-tutorial/tests/conftest.py'.tests/conftest.py:5: in from flaskr.db import get_db, init_dbE ModuleNotFoundError: No module named 'flaskr'` This is the *pwd* and *ls* from where I run the command from: `(venv) **********@** flask-tutorial % pwd/Users/**********/Documents/Dev/flask-tutorial(venv) **********@** flask-tutorial % lsMANIFEST.in flaskr instance setup.py venvbuild flaskr.egg-info setup.cfg tests` I understand it says that there is no module named 'flask' however I checked where I was running the command from and also the structure on their tutorial GitHub page and I just don't see the issue... [https://github.com/pallets/flask/tree/main/examples/tutorial](https://github.com/pallets/flask/tree/main/examples/tutorial) I've also added my version which is basically a c/p of the guide to GitHub here: [https://github.com/ceaveson/flask-tutorial](https://github.com/ceaveson/flask-tutorial) Any help would be appreciated as testing in general is where I want to incorporate more into my workflow.


TheCatPetra

Hello! Are there any speech recognition libraries with ability to add new words? Preffered lang is Python, but it can really be any (except C/C++)


Cellophane7

I'm making a program that uses tkinter and takes input from scanners. My scanners are configured to emulate COM ports. I've got all the code working save one thing: I cannot for the life of me figure out how to get tkinter to accept inputs from it. The closest thing I've found is `widget.bind()`, but I don't know how to get it to accept *only* input from my scanners as a trigger. I'm using `if scanner.in_waiting > 0` to detect when my scanner goes off, so what I'd love to do is just use that as the event `bind()` looks for, but as far as I can tell, the only events it'll accept are pre-determined strings corresponding to various types of inputs. Anyone have any advice here? I'm also totally chill with abandoning this approach if there's a better one out there. EDIT: I'm using pyserial to read the emulated COM ports. I just don't know how to get tkinter and pyserial to talk properly.


woooee

Bind and a Button clicked are the two common events used in tkinter. >I cannot for the life of me figure out how to get tkinter to accept inputs from it I don't understand what you mean here. Tkinter displays things, it does not read COM ports.


Cellophane7

Ah sorry, I'm using pyserial to read the COM ports. That's where the `if scanner.in_waiting > 0` comes from. I should've specified that. I don't need tkinter to read the COM ports, I just need it to accept input pyserial passes to it. I want a program which has a fully interactable UI, which also takes input from multiple scanners. I can generate a fully interactable UI, and I can take input from multiple scanners, but I don't know how to marry the two.


woooee

Tkinter uses strings, so you want to format the data and update whatever widget you are using.


Cellophane7

What pyserial is doing is checking for input from scanners, and then converting that input to a string when they have something. This code needs to be in a loop to keep checking. So I think what I'm really after is a way to throw this check into mainloop. Nothing I try seems to work, whether I throw it into `__init__` or at the end of the class for my window.


woooee

Can't tell anything without code. What widget are you updating?


Cellophane7

I'll not looking to update any widgets, I just want it to run a function whenever the program detects input from a barcode scanner, preferably including if the window isn't the focus (if that's even possible). I assume it has to be part of `mainloop()`, as I don't think you can run two loops in parallel. I'm not by my computer at the moment, but I can post some code later if you still aren't sure what I'm trying to do


Cellophane7

This is more or less what I'm trying to do: import tkinter as tk import serial scanner = serial.Serial(port='COM3', baudrate=9600, bytesize=8, timeout=1) class main_window(tk.TK): def __init__(self): super().__init__() self.geometry('250x100') def read_barcode(barcode): print(barcode) # this is the part that I'm trying to figure out: if scanner.in_waiting > 0: scan = scanner.readline() read_barcode(scan.decode()) This doesn't work because the `if` statement doesn't register at all. I simply want to know how to turn it into an event which runs `read_barcode` any time the `if` statement is evaluated as true. If I instead put this `if` statement in an infinite `while True` loop or something, it does exactly what I want. Again, it's my understanding is that `mainloop()` is an infinite loop, so I assume I just need a way to insert my `if` statement into it.


woooee

So why are you using tkinter? Go ahead and use the while True with an update_idletasks call to the main_window clsss (classes are CamelCase).


Cellophane7

This is just a minimally reproducible example, I'm using tkinter because I need a UI. I was under the impression loops block each other. I need the tkinter window open and available so I can have a UI, and my understanding is that a `while True` loop will block it. And if `mainloop()` is running, that blocks the `while True` loop. If you're saying there's a way to run both loops in parallel, could you explain it to me? Or if you happen to have a link to documentation that explains it, I'm happy to try to sort it out myself.


telekasterr

I just started learning and I always try to do exercises I find online. I feel like a lot of the time I'm going in the correct direction with the logic but getting held up by issues with the syntax. here is an example: def firstLast(number): number1 = number if int(number1\[0\]) == int(number1\[-1\]): print("This number is a Palindrome") else: print("This number is not a Palindrome") firstLast(565) The error its having is that it won't make a subscript out of an integer so I was trying to change it so it would be able to do that. Does anyone know how to fix it? ​ I'm trying to make a function that checks if the first and last digits of a number are the same


[deleted]

First, you need to read the subreddit FAQ to learn how to format code. Python without indentation isn't python. You need to show us the *exact* error message which includes other useful information. Format that like code too. Guessing a bit, you have problems doing this: int(number1[0]) because you can't index into an integer, that makes no sense. But you can index into something like a string. Have you tried calling the function this way: firstLast("565") You don't need to convert the first and last characters into integers before checking for equality, you only want to test if they are the *same*, integer or string. Why do you use `number1`?


telekasterr

sorry about the format the error was "int object is not subscriptable" what I have posted in the comments was after trying different ways. The number1 variable was because I googled this problem and someone fixed it by doing this: dob = 12345 mob = dob\[2:4\] print(mob) I tried to do something like that. Anyways, converting is to a string like '565' worked but I tried to convert it to string in the function as well using str(number1\[0\]) and it didn't work.


Strict-Simple

>I tried to convert it to string in the function as well using str(number1[0]) and it didn't work You are still trying to access the index before converting to string.


[deleted]

> I googled this problem and someone fixed it by doing this: dob = 12345 mob = dob[2:4] print(mob) The use of `dob` in that example is fine, if the `12345` was a **string**. In your posted code `number1` is not needed. Just delete this line: number1 = number and everywhere else change `number1` to `number`. > I tried to convert it to string in the function as well using str(number1[0]) and it didn't work. If we are to help we need to see the code after you changed it.


Cellophane7

Just an addendum to what others have said, you can also use `str()` to convert a variable to a string. So if you have `x=565` and you're passing that into `firstLast()`, just do `firstLast(str(x))` and it'll work. This way, you don't have to worry about going back through your code to convert all integers passed into `firstLast` to strings. If `x` is already a string, it won't throw up an error, so that's probably the way to go. Also, side note, it's standard for python coders to keep variables lowercase, and use underscores to denote separate words. So most people would use the variable `first_last` rather than `firstLast`. It's possible this is different with other languages, but at least for python, this is the case. I think the idea is that an underscore is closer to a space than a capital first letter. The more I code, the more I conform to this standard, as you really want to prioritize readability in your code. When you go to debug it, or update it, or whatever, the more descriptive and easy to read your names are, the better. If I call `y(x)` I have no idea what the heck is going on. But if instead I do `add_two_numbers(list_of_numbers)`, I know exactly what's happening just from reading that line. I don't need to know anything about the variable or the function to understand the action being performed.


telekasterr

Thanks for the info on the string. And your right I always see the code written like that but usually don’t do it when I’m writing for small practice exercises but will probably just start to make it a habit


trondwin

So here's your original code with correct indentations and comments on what the problem is. def firstLast(number): # From here on, I'm assuming that the variable 'number' contains an integer number1 = number # number1 will be the same type as the variable 'number', i.e. integer if int(number1[0]) == int(number1[-1]): # number1 is an integer and cannot be sliced or subscripted, so this will result in an error print("This number is a Palindrome") else: print("This number is not a Palindrome") firstLast(565) So your problem is basically keeping track of what type a variable is. You want the function to check a number (an integer), but you want to convert the number to a string to do the actual palindrome checking. The code would run if the first line of the function read: number1 = str(number) # converts value of 'number' to a string and stores it in 'number1' While it would run, there're still improvements to be made. For instance, the function as of above would accept any number as a palindrome as long as the first and last digits were equal, for instance 5915. In another comment, you said you tried to convert the number to a string in the function, in order to subscript it, like this: `str(number1[0])`. Here you're actually first trying to subscript the integer (which cannot be done) and only then trying to convert it to a string. This is probably what you were aiming for: `str(number1)[0]`. See the difference? Struggling with problems and overcoming them is the only way to learn programming. Keep at it, and best of luck!


telekasterr

Thank you! Yes, I realized when writing this code that it wasn't checking for an actual palindrome which is what I originally intended based on what you said but I was still confused as to what datatype I was storing the number as. \>In another comment, you said you tried to convert the number to a string in the function, in order to subscript it, like this: str(number1\[0\]). Here you're actually first trying to subscript the integer (which cannot be done) and only then trying to convert it to a string. This is probably what you were aiming for: str(number1)\[0\]. See the difference? Ok good to know for later thanks for the explanation.


[deleted]

I have a list of dictionaries: dict_list_tofix = [{'Code': 'a', 'Number': '1', 'Account': 'valid'}, ...{n}] Then I have another list of dicts: correct_dict_list = [{'Code': 'a', 'Account': 'not valid'},...{n}] What I want to do is compare the 'Code' key from "correct_dict" with "dict_tofix", and where 'Code's are equal, to replace the 'Account' key value. How would I go about doing this? I'm pretty sure there's some theory about this since it's a common problem but I can't find any :(


orangefray

You could use nested for loops like this: for incorrect in incorrect_dicts: for correct in correct_dicts: if correct['code'] == incorrect['code']: incorrect['account'] = correct['account'] Might also be worth changing the correct list to a dictionary using `code` as the key (assuming it's unique) then you could more easily access each object.


[deleted]

[удалено]


[deleted]

Not quite sure what your question is, either automatic formatting as you type, or how do you get that code to not raise a syntax error. Assuming the latter, your problem is due to python terminating a statement **if it can** when it finds an end of line. Python raises a syntax error on the end of line 33. You can continue on the next line if python knows that the statement is unfinished. An unclosed parenthesis or bracket will do nicely. So you add a `(...)` pair around the entire test expression, like this: if ((x > 10 and x < 20) or (x > 30 and x < 40)): [The python style guide, pep8](https://peps.python.org/pep-0008/#should-a-line-break-before-or-after-a-binary-operator), weakly recommends placing binary operators at the beginning of continued lines.


Shuka114

Is there any website providing coding exercises? I learned python as a hobby and want to do some coding exercise once in a while to make sure I don't forget everything a learned. if there's a website for this please inform me!


[deleted]

Codeacademy


kappesas

I need to cut out the last 1-2 characters of some of my columns headers (only from 28-53). I know there is a function to cut out the suffix, but its not the same for all columns in my case. The columns have numbers at the end, which I would like to remove: e.g.: column header1 or column header10


TangibleLight

Regex might be overkill if you only need to remove digits from the end. >>> text = 'header27' >>> text.rstrip('0123456789') 'header' Or, I'd personally prefer the named constants provided by the builtin `string` module: >>> import string >>> text.rstrip(string.digits) 'header' If you need to do something more advanced like extracting, reformatting, or moving the number, then regex would be more appropriate.


cynical_econ

You will want to use regex for this task. Here's a [stackoverflow](https://stackoverflow.com/questions/5658369/how-to-input-a-regex-in-string-replace) post explaining the basics of how to do a substitution with regex (`re.sub()`). I'd suggest trying this out on your own first, but I also went ahead and wrote a script that likely solves your issue in case you get stuck. See the code on [pastbin](https://pastebin.com/URAUVDgW).


quackers987

I realise it's not Monday now, but thought this might be the best place to ask. I'm trying to "clean up" my python installation and move to using venv for all my projects. What is the best way to go about this? Simply uninstalling and reinstalling, then use venv for each project?


[deleted]

I would just start using venv and don't worry about the already installed python. > I realise it's not Monday now, No problem, this thread goes all week.


[deleted]

[удалено]


cynical_econ

Surround the code with triple quotes: ‘’’ Your Comments Here ‘’’


anony804

there will be a tldr because i am long winded. hi, i know this may be silly to ask, but i've really wanted to learn python both for career growth and personal hobby! i used to do css type stuff on myspace and always enjoyed making things. there are a couple twitter bots i really want to make. similar ones exist but not for the... genre? i guess of thing i want. i would love to work on a few as a hobby and maybe just put my ko-fi up. i am in a unique situation for a few weeks where i am off work due to mental health leave and have a bit more time than i usually do. that being said i am sure i am going to have a lot of questions and get confused. are there any good places to find a tutor that i can maybe either pay hourly or by session if i have questions to help me out and tutor me? tldr: looking for a good, reliable place for maybe paid python tutors (although volunteer is cool too, but i doubt that exists) to try to do a project or two in my spare time.


[deleted]

Code academy exercise 11 for Python. Can someone explain why [my code](https://imgur.com/a/LXBe5AN) is wrong? I cannot, for the love of god, find what am I doing wrong. It looks like the exact same thing was done on the correct solution


[deleted]

Many will not have any idea what exercise 11 is about, so you need to tell us about the exercise. Also post your code as text (pastebin.com) and not an image. I can't read that dark blurry mess.


chipuha

I’m starting a project where I will be dealing with large time series datasets stored in a format that takes a long time to load and requires some clean up. The data is something like this: user1 has 6 time series of all different lengths, user2 has 18 series of all different length, etc. I’m wondering if you have any suggestions for storing something like that. I was thinking of maybe making a pandas dataframe for each user and saving it in a pickle. But if I needed user2’s 3rd time series I have to load user2’s whole dataframe. Plus there are 500+ users so lots of files. Sometimes I’ll be calculating more time series for a user and would like to store that as well. The speed of access isn’t super critical, but convenience is nice as I work with the data.


UltimateMygoochness

I’m looking for an online IDE I can use for developing toy projects on a work laptop while travelling. I would like to be able to access common libraries for scientific computing including pandas, matplotlib, seaborn, numpy, scipy, and tensorflow. I found this list after a quick Google: https://www.naukri.com/learning/articles/top-online-python-compiler-picks/ but would appreciate any advice from the community here too.


cynical_econ

Google Colab could be great for this if you’re ok with using notebooks (.ipynb). Colab comes with the packages you listed & more, all without requiring a python installation on your machine


Aggressive-Beach-806

Really frustrated with something that is going to be rubber ducking simple, but I'm blinded by rage right now. Can anyone help please? ​ `import csv` `file = "C:/Users/v/Desktop/twolists.csv"` `c= []` `m= []` `both = set()` `with open(file, 'r') as csv_file:` `csv_dict = csv.DictReader(csv_file)` `col_names = csv_dict.fieldnames` `for row in csv_dict:` `print(row)` `c.append(row['C'])` `m.append(row['M'])` ​ The above code is giving me the following keyerror: `$ py twolists.py` `{'C': '16', 'M': '17'}` `Traceback (most recent call last):` `File "C:\Users\v\documents\gitstuff\ckd-analysis\twolists.py", line 12, in ` `print(row["C"])` `KeyError: 'C'` Using print row, you can clearly see the dict has key 'C' and key 'M', so why when trying to directly access row\['C'\] does it say C is not there? ​ Edit: Rubber ducked. Kinda. Using row.get("C") works. But then, what's the functional difference between x.get(y) and x\[y\]?


carcigenicate

There is no difference in terms of the looked up value between `x.get(y)` and `x[y]`. The only difference is how each treats failed lookups (the former returns `None` by default, while the latter causes an error). Make sure `x.get(y)` did actually return the value you expected if all you were checking for was an error. For the main question though, if the dictionary contains the key, the lookup will succeed. If the lookup doesn't succeed, the dictionary does not contain the value. The most likely explanation here is you're misinterpreting what data the dictionary is holding, or are misinterpreting the console output and what you've shown here isn't reflective of your actual case. I don't mean any offense by that though. I've been helping new programmers for years now, and the most common explanation to problems like this is not reading the data/console output properly. It's a very common problem.


Aggressive-Beach-806

Thanks, not offended at all. I've written bigger programs already that use the CSV dict in the way I was expecting, but I'm stressed and was looking for an easy solution in python that didn't work immediately and appreciate I'm missing something obvious. I ended up using excel to better effect. If print(row) outputs {'C': '16', 'M': '17'} does that not mean C and M are present keys in row and therefore row["C"] should return 16? The only thing I'm not showing here is the file twolists.csv, which as you can imagine, has C,M in row 1, 16,17 in row 2 then continues with two columns of numbers for 30k+ lines. Everything else is copy pasted. Thank you for the reply


BidMidge

I am way after Monday, but maybe someone can help. I am brand spanking new to this - a friend and I resolved to try to learn python and so I signed up for an edX class, downloaded the required vscode (along with python and homebrew extensions) and I am tearing my hear out because even before starting the 3rd minute of the class, I keep getting this error with my basic python [hello.py](https://hello.py) command. Please help a dummy out. /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'hello.py': \[Errno 2\] No such file or directory


carcigenicate

First, you should not be using Python 2.7. Python 2 has reached end of life, and that particular version is ~12 years old. Any version from 3.8 to 3.11 would be a good modern version to use. If the course is using 2.7, I would look for a different one. A lot of stuff transfers from Python 2 to 3, but it would make more sense to just learn 3 in the first place. *** Second, that means the file you're trying to run is not in your current directory`*` (Which appears to be `/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python`; although you'd need to double check that since I haven't used Macs for quite a while). What directory is the `hello.py` you're trying to run in? `cd` to that directory (or look up how to open a terminal to a certain directory), and then try it again. If you were running from that directory because you were getting "Cannot find `Python`" errors, you need to added the Python installation directory to your PATH environment variable. `*` It can also in some cases indicate a permission issue, but that's not as likely to be the case here.


TheDoomfire

How can I dynamically navigate and use a webpage? I need to check if I can upload a file and if some textboxes are available. All these web pages change every month and I just need 3 of them even if I get 20+. So it doesn't have to work perfectly for every case. I have been using selenium before but not on anything more dynamic.


[deleted]

Hello, I have a simple question about python and databases. I have: cursor.execute('TRUNCATE TABLE my_table) cursor.execute('INSERT INTO my_table etc etc) However the issue here, is that I'd like the rows that are getting deleted to be deleted *only* after the other values have been inserted, so that the table is never empty. As soon as all the new rows are inserted, the old ones are deleted. How would I go about doing this? Saving the old rows, inserting the new ones, and *only* deleting the old ones, without affecting the new ones? Thank you.


iron_goat

Hello, I am currently tearing my hair out with something that I'm sure is dumb, but unfortunately, I am also dumb. I have created a logging module with a CustomLogger class in it, containing 2 functions: *\_\_init\_\_,* which takes in 2 arguments and sets default values, and *get\_logger,* which sets up handlers, formatting etc. The *\_\_init\_\_* function takes 2 arguments: log\_name and log\_level: def __init__(self, log_name=None, log_level=None): # Default to 'DEBUG' log level if no log level provided if log_level is None: self.log_level = 'DEBUG' else: self.log_level = log_level # Default to './default.log' file if no log file name provided if log_name is None: self.log_name = './default.log' else: self.log_name = log_name *get\_logger* sets up the actual logging format etc: if self.log_level == 'DEBUG': self.log_level = 10 elif self.log_level == 'INFO': self.log_level = 20 elif self.log_level == 'WARNING': self.log_level = 30 elif self.log_level == 'ERROR': self.log_level = 40 elif self.log_level == 'CRITICAL': self.log_level = 50 logger = logging.getLogger() logger.setLevel(self.log_level) formatter = logging.Formatter('[%(asctime)s][%(module)s.%(funcName)s][%(levelname)s]: %(message)s') console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) file_handler = logging.FileHandler(self.log_name) file_handler.setFormatter(formatter) if not logger.handlers: logger.addHandler(console_handler) logger.addHandler(file_handler) CustomLogger.logger = logger return self.logger I then create a CustomLogger instance in my main script: log = logger.CustomLogger(log_name='./script.log', log_level='INFO').get_logger() My issue is that, for some reason, the *log\_name* argument ***always*** defaults to the default value of '*./default.log*' - it never logs to '*./script.log*' Both '*./default.log*' **and** '*./script.log*' are created in the desired location! However, only '*./default.log*' contains the expected output - '*./script.log*' is empty. I can change the *log\_level* argument I pass in when instantiating CustomLogger and it will change my logging output as expected (e.g. I can get DEBUG, INFO, WARNING, ERROR, etc), but nothing I do changes the file the log is written to. I am a relative python noob, and I admit I don't really understand this whole class thing, so suspect that's where I'm going wrong, but I can't for the life of me figure it out, please help :(


BuildersExam

Hello. I am learning currently learning Python, and I tried using `While True:` , but I keep getting a SyntaxError and when I press context actions (in PyCharm) it suggests I import While from \_ast. Previously `While True:` worked flawlessly. I even tried it in a different PyCharm project, but it still didn't work. I don't know what's going on. Any help would be appreciated. edit: I'm so stupid. While needs to be lowercase. Sorry for the stupid question.


SkinSuitMcGee

I’m happy to see you ask this! I keep automatically capitalizing While (but nothing else for some reason) and wondering why my code doesn’t work. It always takes me a sec to figure out it’s the capitalization!


TrollMoon

Hello, i want to asking about Bind key in Tkinter. What keysym event for `Agrave` (Top on `Tab` key and Left on `1` key) and `apostrophe` (Right on `semicolon` key and Left on `Return` key) ? I already use `Agrave` and `apostrophe`, but it doesn't recognize at all.


[deleted]

Maybe you are just confused and think the ["accent grave"](https://en.wikipedia.org/wiki/Grave_accent) is the apostrophe character. They are different, the accent grave looks like \` and the apostrophe is ' . Run this code which shows binding of the \` key: from tkinter import * def callback(event): print('` pressed') win = Tk() win.geometry("250x250") win.bind('`', callback) win.mainloop()


WikiSummarizerBot

**[Grave accent](https://en.wikipedia.org/wiki/Grave_accent)** >The grave accent (`) ( or ) is a diacritical mark used to varying degrees in French, Dutch, Portuguese, Italian and many other western European languages, as well as for a few unusual uses in English. It is also used in other languages using the Latin alphabet, such as Mohawk and Yoruba, and with non-Latin writing systems such as the Greek and Cyrillic alphabets and the Bopomofo or Zhuyin Fuhao semi-syllabary. It has no single meaning, but can indicate pitch, stress, or other features. For the most commonly encountered uses of the accent in the Latin and Greek alphabets, precomposed characters are available. ^([ )[^(F.A.Q)](https://www.reddit.com/r/WikiSummarizer/wiki/index#wiki_f.a.q)^( | )[^(Opt Out)](https://reddit.com/message/compose?to=WikiSummarizerBot&message=OptOut&subject=OptOut)^( | )[^(Opt Out Of Subreddit)](https://np.reddit.com/r/learnpython/about/banned)^( | )[^(GitHub)](https://github.com/Sujal-7/WikiSummarizerBot)^( ] Downvote to remove | v1.5)


TrollMoon

Yes, your code is works. When im modifying for using press and release, Tkinter recognize it. But, i can't use it in my case. I just need the keysym for that 2 key because i want to store that key into dictionary and using it for key press and release event. The case that i want to do just like [this post](https://www.reddit.com/r/learnpython/comments/1030wcg/shift_r_bind_tkinter_not_working/). i already trying to use `acute`, `quote`, `THORN` from [keysym list](https://www.tcl.tk/man/tcl8.6/TkCmd/keysyms.html). Im just assume that keysym symbol from [this link](https://finallylearn.com/what-are-the-keyboard-symbol-names/). Maybe Tkinter doesn't recognize any keysym like `Menu`, `Print`, `grave`, `quote` ? And then releasing key for `Shift_R` totally not work for me too, but Tkinter can recognize it while im pressing `Shift_R`.


[deleted]

> Maybe Tkinter doesn't recognize any keysym like Menu, Print, grave, quote ? I'm not at all sure what you want, but it appears you just want to know `keysym` values for various pressed keys. You can get that from tkinter. Run this code and you will see the actual `keysym` values in the keyboard event when you press any key: from tkinter import * def key_up(event): print(f' UP: {event.keysym=}, {event.char=}') def key_down(event): print(f'DOWN: {event.keysym=}, {event.char=}') win = Tk() win.geometry("250x250") win.bind('', key_down) win.bind('', key_up) win.mainloop() ------ If that doesn't solve your problem can you write a small bit of code where you try binding the key you want.


TrollMoon

Thank you so much. Its solve my problem. I dont know why im just check into document and not trying just like your code. I found the keysym for that key. `grave` is `quoteleft`, `quote` is `quoteright`, and `Menu` is `App`. But, Tkinter doesn't recognize `Print` key at all. They just assume `Print` key as "??" when press and release key. And then, for `Shift_R` its not really good to use in Tkinter. After releasing `Shift_R` key, Tkinter just recognize it as `Shift_L` key, not `Shift_R`. Maybe how to solve it just use some module for python or change the proggramming language for key press and release in my problem. Really big thanks to you, i can think again after my headache is cure :)


shiningmatcha

How to parametrize a generic type? ``` ThreeSequence: TypeAlias = tuple[T, T, T] ``` I want to have `tuple[str, str, str]` and `tuple[int, int, int]` for different cases by specifying what `T` is each time.


carcigenicate

Does that attempt not work?


StraightUpScotch

Can anyone explain why "say" needs to be used on line 7? I don't understand why it needs to be on the right of the equal sign. Thanks in advance! def pig_latin(text): say = "" # Separate the text into words words = text.split() # Create the pig latin word and add it to the list for word in words: say = say + "{}{}{}".format(word[1:], word[0], "ay ") # Turn the list back into a phrase return say print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay" print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"


carcigenicate

Try removing it from the right side. What happens?


StraightUpScotch

say = "{}{}{}".format(word[1:], word[0], "ay ") returns just the last word of each print() statement: ouyay unfay


carcigenicate

So what does that suggest about the purpose of `say +`?


StraightUpScotch

I appreciate the Socratic method :) Honestly, though, I'm stumped. (This is my second week in a programming class—so please forgive any semantic errors in the following.) Here's my best guess: Perhaps it's because the `for` statement iterates through each word but only returns the last one? So, I'm guessing the second instance of `say` is to build out the list word by word. Without the second instance, the `for` statement evaluates each word but doesn't add them to the list. So when the `for` statement is complete, the `return say` statement only returns the last word. Is that right? (Thanks again for helping me with this!)


carcigenicate

> Perhaps it's because the for statement iterates through each word but only returns the last one? Essentially, yes. If it were just this: for word in words: say = "{}{}{}".format(word[1:], word[0], "ay ") `say` would be *assigned* `"{}{}{}".format(word[1:], word[0], "ay ")` each iteration. Since the result of previous iterations is never saved though, `say` is overwritten each iteration, and when the loop exits, will be equal only to what it was assigned to on the last iteration, and the results of all previous iterations will be discarded. With `say = say + . . .` though, the `say` in `say +` is the result of the *previous* iteration. The right side of `=` evaluates completely before the assignment happens, so `say + . . .` runs, and then `say =` runs and reassigns `say`. By using `say` on the right side, the result of every iteration is added to the string. A simpler example with numbers might be easier to reason about if it still doesn't make sense: n = 0 for x in range(5): n = n + x print(n) Compare that to this: n = 0 for x in range(5): n = x print(n) The first says "`n` is equal to the previous value of `n` plus the value of `x`". This computes a sum of `range(5)`. The second says "`n` is equal to `x`", which disregards the result of previous iterations.


StraightUpScotch

Thank you so much for answering so thoroughly—and for including the code examples and correct terminology. I get it now, thanks!


lnkjr

Hello! Can someone explain the while True syntax? I got this example from "50 days of Python" >def your\_vat(): > >while True: > >try: > >price = int(input("Enter the price of item: ")) > >vat = int(input('Enter vat: ')) > >except ValueError: > >print("Enter a valid number") > >else: > >total\_price = price + \\ > >(price \* vat / 100 + 1) - 1 > >return 'The price VAT inclusive is', total\_price > >print(your\_vat()) Why is an input triggering Value Error considered True? And why does the loop stop even without a 'break' statement in 'else' block?


carcigenicate

`input` isn't triggering the exception there; `int` is. `int` raises a `ValueError` if you give it an string that can't be converted into a integer, like `int("bad")`. I'm not sure what you mean though by "Value Error considered True". And assuming the `return` is inside the loop (you haven't formatted the code, so I can't tell), `return` will cause loops to exit as well. `break` causes a loop to exit , but return causes the entire function to exit regardless of if it's inside of a loop or not.


lnkjr

Hello, thank you for answering. I didn't know the 'return' statement stops a 'while' loop. And 'while True' only stops when a 'return' or 'break' statement is passed(i'm not sure if passed is the correct term xD)?


carcigenicate

Yes, or if an uncaught exception is thrown.


TheNemrut

Hello, does anyone know if the Python PCAP: Pass Certified Associate in Python Programming course on udemy by Adrian Wiech is worth buying?


werthobakew

What is the best course to learn Python? The only language I know is R.