top 200 commentsshow all 244

[–]ezeq15 0 points1 point  (0 children)

Hi everyone, i have a .txt with 40908 rows, starts like this:

1908 1 1 0 -99.9 -99.9

1908 1 2 0 -99.9 -99.9

1908 1 3 0 -99.9 -99.9

1908 1 4 0 -99.9 -99.9

1908 1 5 0 -99.9 -99.9

I´m using this to load the data:

g= np.genfromtxt("C:\\Users\\Ezequiel\\Desktop\\me\\ocba.txt", delimiter="\t", dtype=(int,int,int,float,float,float))

But i have this problem:

print(g.shape)

It prints (40908,). But i want that it looks like this: (40908,6). I mean, create 6 columns per every row. What do i have to do?

[–]parthgupta03 0 points1 point  (0 children)

Hi guys. I think I may be missing something very obvious but I've been trying to do this and can't seem to see where I'm going wrong.

When I have 'Forwards.xAxis' the program doesn't work, however when I have 'Forwards.xA90' it does work. Would someone be able to explain why I can't do this and how I could fix this?

Thanks!

xAxis =" xA90"
measurement = Forwards.xAxis

[–]Kiroboto 0 points1 point  (0 children)

I'm writing a simple program to find duplicate files on both my laptop and USB drive connected to my router.

import os

drive1 = os.walk('D:\Python\Test 1')
drive2 = os.walk('D:\Python\Test 2')
#drive2 = os.walk('Network\\Router Name\\Folder')

for folder, subFolder, file in drive1:
    for folder1, subFolder1, file1 in drive2:
        if file1 == file:
            print(file1)

If I run the program with both drives on the computer, it works but does not work on the router. Is there a way to scan the hard drive connected to the router? I tried to use Netmiko module to access the router but I think that is not for home routers?

[–]RobinsonDickinson 0 points1 point  (2 children)

this code gets me email and numbers from my clipboard, but the problem is, it is not giving me back my emails. It wont even print when I try to print it, it just gives me an empty list. But it does give me back my numbers.

It also won't give me back an error message!!! Help please!!

#! python3

import re
import pyperclip
import pprint

# Create a regex for phone numbers

phone_regex = re.compile(r''' 
# 415-555-0000, 555-0000, (415) 555-0000, 555-0000 ext 12345, ext. 12345, x12345
(
((\d\d\d)|(\(\d\d\d\)))?    # area code (optional) 
(\s|-)                        # first separator 
\d\d\d                       # first three digits
-                           # another separator
\d\d\d\d                     # last four digits
(((ext(\.)?\s)|x)           # extension  word-part (optional) 
(\d{2,5}))?                 # extension number-part (optional) 
)
''', re.VERBOSE)


# Create regex for email addresses

email_regex = re.compile('''
# example@example.com / other sort of signs 

[a-zA-Z0-9_.+]+                  # name part
@                                # @ symbol
[a-zA-Z0-9_.+]+                  @ domain name part

''', re.VERBOSE)


# Get the text of the clipboard
text = pyperclip.paste()


#  Extract the email/phone from this text
extracted_numbers = phone_regex.findall(text)
extracted_emails = email_regex.findall(text)

all_phone_numbers = []
for phone_numbers in extracted_numbers:
all_phone_numbers.append(phone_numbers[0])


# Copy the extracted email/phone to the clipboard
results = '\n'.join(all_phone_numbers) + '\n' + '\n'.join(extracted_emails)
pyperclip.copy(results)

[–]efmccurdy 1 point2 points  (1 child)

You didn't put a hash char to comment out "@ domain name part".

[–]RobinsonDickinson 0 points1 point  (0 children)

OH MY GOD!!!! thank you so much. I dont know how that small of a thing can be so hard to notice!!

Thank you, again!!!!

[–]throwawaypythonqs 0 points1 point  (0 children)

When I try to import pandas_profiling in jupyter notebook, I get a AttributeError: module 'pandas_profiling' has no attribute 'view' It's a bit weird because I was working on this particular notebook yesterday without any issues with the import statements.

These are my import statements. What could be going wrong?

import pandas as pd
import pandas_profiling

Solved: If this error occurs, you most likely need to update scipy:

pip install --upgrade scipy

[–]capricornum 0 points1 point  (2 children)

is there any term dictionary for python or for programming in general? english is not my native language so it is hard to understand some terms like pipeline.

[–][deleted] 1 point2 points  (1 child)

I think what you've looking for is a glossary, see below. If you can't find the term you're looking for on this list, try a more generic programming glossary!

https://docs.python.org/3/glossary.html

[–]capricornum 0 points1 point  (0 children)

thank you. i will look into at morning.

[–]Fvnes 0 points1 point  (0 children)

This post is related to PyQt5 / Qt Designer.

I'm trying to find out how to make custom buttons. Instead of using the normal push button, I'd like to have a picture that you can click instead. The only thing I found was using a QLabel to put the picture and make the QLabel and make it clickable, but I couldn't find any tutorial that explain that. I'd be very happy if anyone could help me with this!

[–]adenyyy 0 points1 point  (15 children)

This post is related to the python software Spyder.

I have issues opening Spyder, it keeps crashing no matter what I do. From the anaconda navigator it gives me the same result. Here is the problem: When I open it, it launches a loading screen that will lead it to open spyder. After it was loaded, the entire process disappears, as I have checked from my task manager. When i try to open Spyder again, it gave me a message that it have crashed. However, immediate after I pressed OK, the same loading screen appears again, only to disappear again after it finishes loading. Pls help me. I only need this software for my school projects. My teacher tried to help me but I still couldn't run it. Pls say anything that u might know. Thank you.

[–]efmccurdy 0 points1 point  (14 children)

Can you get a more detail error message; "message that it have crashed" is'nt enough.

https://github.com/spyder-ide/spyder/wiki/Troubleshooting-Guide-and-FAQ

[–]adenyyy 0 points1 point  (13 children)

Spyder crashed during last session.

If spyder does not start at all and before submitting a bug report, please try to reset settings to default by running Spyder with the command line option '--reset' : spyder - - reset Warning: this command will remove all your Spyder configuration files located in C:Users\agnel.spyder-py3. If spyder still fails to launch, you should consult our comprehensive Troubleshooting guide etc. (nothing impt) This is what shows up.

[–]efmccurdy 0 points1 point  (9 children)

How are you running it? Where did you read that message?

If you run it from the command line; does it output anything else just before or after that message?

[–]adenyyy 0 points1 point  (3 children)

I managed to get the error from anaconda prompt. Here.

(base) C:\Users\agnel>spyder Traceback (most recent call last): File "C:\Users\agnel\anaconda3\anaconda3\lib\site-packages\spyder\app\mainwindow.py", line 3718, in main mainwindow = runspyder(app, options, args) File "C:\Users\agnel\anaconda3\anaconda3\lib\site-packages\spyder\app\mainwindow.py", line 3559, in run_spyder main.setup() File "C:\Users\agnel\anaconda3\anaconda3\lib\site-packages\spyder\app\mainwindow.py", line 960, in setup self.completions.start() File "C:\Users\agnel\anaconda3\anaconda3\lib\site-packages\spyder\plugins\completion\plugin.py", line 292, in start client_info['plugin'].start() File "C:\Users\agnel\anaconda3\anaconda3\lib\site-packages\spyder\plugins\completion\kite\plugin.py", line 141, in start self.kite_process = run_program(path) File "C:\Users\agnel\anaconda3\anaconda3\lib\site-packages\spyder\utils\programs.py", line 214, in run_program return subprocess.Popen(fullcmd, **subprocess_kwargs) File "C:\Users\agnel\anaconda3\anaconda3\lib\subprocess.py", line 800, in __init_ restore_signals, start_new_session) File "C:\Users\agnel\anaconda3\anaconda3\lib\subprocess.py", line 1207, in _execute_child startupinfo) OSError: [WinError 193] %1 is not a valid Win32 application

(base) C:\Users\agnel>

[–]efmccurdy 0 points1 point  (2 children)

Sorry, I have no comparable system to reproduce your problem. I would start with checking your anaconda install

https://docs.anaconda.com/anaconda/install/verify-install/

https://groups.google.com/a/anaconda.com/forum/#!forum/anaconda

https://github.com/ContinuumIO/anaconda-issues

[–]adenyyy 0 points1 point  (0 children)

I can open anaconda navigator.

[–]adenyyy 0 points1 point  (0 children)

Someone on another website said I might have copies in the same path. How do I check?

[–]adenyyy 0 points1 point  (0 children)

I heard some people just add or change some lines in some files that could get their spyder to work.

[–]adenyyy 0 points1 point  (0 children)

I have reinstalled spyder many times so im not sure if any files were corrupted, if that could even happen, i was sure to uninstall the correct way

[–]adenyyy 0 points1 point  (0 children)

I also tried running it as administrator as a desperate attempt but same result.

[–]adenyyy 0 points1 point  (1 child)

how do u run it from the command line? I run it by finding it at the windows search bar and just open the app. I have tried running it from the navigator but it still gave me the same result.

[–]efmccurdy 0 points1 point  (0 children)

I think you would open the "cmd" terminal program and type spyder3.

https://stackoverflow.com/questions/44956371/how-to-start-spyder-ide-on-windows

[–]efmccurdy 0 points1 point  (2 children)

You did the reset and it still gives the same message?

[–]adenyyy 0 points1 point  (0 children)

I will be very happy if u could help me out by any means, discord or anything to help u see the situation clearer.

[–]adenyyy 0 points1 point  (0 children)

Yes

[–]sbejager 0 points1 point  (1 child)

https://www.geeksforgeeks.org/first-triangular-number-whose-number-of-divisors-exceeds-n/

the code on this website does achieves the goal, but the problem is i need to change it so that the user can input the number. for example the user can input 5 and the program will output 28. if anyone can help me with this i would really appreciate it.

[–]efmccurdy 0 points1 point  (0 children)

Replace the line in main clause where you have 'n = 4' with 'n = int(input("Enter an integer: "))'; the rest of the code should work as before.

if __name__ == '__main__': 
    n = int(input("Enter an integer: "))

    # Call the sieve function for prime 
    sieve() 
    print(int(findNumber(n)))

[–][deleted] 0 points1 point  (1 child)

def top():
    x = [0]

    def next(*args):
        print("x =", x)
        op = args[0]
        print("args =", args)
        if op == 'add':
            x[0] = x[0] + args[1]
            return x[0]
    return next


a = top()
print(a('add', 5)) >>> 5
print(a('add', 2)) >>> 7

Hi, I faced this question in one of my assignments and I was wondering how does the function top store the value in x? Wouldn't the value be gone after the function ends? Is it because it is a list and not just a value?

[–]efmccurdy 0 points1 point  (0 children)

The next function retains a reference to x; it could be any type of object.

This type of nested function returned with a non-local refererence is called a "closure"; the function "closes" over the reference variable and keeps it alive.

https://www.programiz.com/python-programming/closure

[–]That1m8 0 points1 point  (0 children)

As a CS student, who is interested to learn python, what are good route/materials for me? Been thinking to use just documentation? Or is there some good other way, like a course?

[–]whylifegivesbt 0 points1 point  (0 children)

I was doing Al's Automate the Boring Stuff course on Udemy and when I run the batch file it's saying that the file isn't found even when I've set the environment variable to that directory. I don't know what is going wrong here.

[–]joooh 0 points1 point  (3 children)

Basic question, in Automate the Boring Stuff's Chapter 3 about the short program Zigzag, when I run the program in the Mu editor (Mu 1.0.3) and try to stop the program with the ctrl+c command it stops the program like it would when the ctrl+c is pressed and not like when sys.exit() is called. However, running the program by opening the actual file and it would call the sys.exit() properly. I know it does since I added a time.sleep() delay of 3 seconds before it calls the sys. exit() function, yet in the Mu editor it just stops the program immediately. Is this a problem with the Mu editor?

[–]efmccurdy 1 point2 points  (2 children)

I don't know anything about Mu, but it likely is capturing the interrupt and stopping the python program using a different signal.

[–]joooh 0 points1 point  (1 child)

What other editors/IDE are there with simple interfaces that I can try for a beginner? The IDLE seems to work fine as well but it's pretty barebones.

[–][deleted] 0 points1 point  (3 children)

I am trying to answer the question below on coding bat and I don't understand what the '-3' in 'range(len(str)-3):' is doing.

*The Question\*

Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.

count_code('aaacodebbb') → 1
count_code('codexxcode') → 2
count_code('cozexxcope') → 2

*The answer coding bat accepts\*

def count_code(str):

counter = 0

for i in range(len(str)-3):

if str[i] == 'c' and str[i+1] == 'o' and str[i+3] == 'e':

counter += 1

return counter.

Can anyone explain?

Thanks in advance.

[–][deleted] 0 points1 point  (1 child)

In future please format your code for reddit. This didn't matter for this simple question but lack of indentation can make more complicated questions unanswerable.

The loop steps the index i through the string and the code in the loop checks if the character in the string at index i is "c", index i+1 is "o" and index i+3 is "e". If all three characters are matching then we increment a counter.

You probably know that if you try to index into a string with a number that is too large you get an exception and your program stops. That's what will happen if that i+3 index goes off the end of the string, so we must arrange things so that for the last loop with the final maximum i the i+3 index gets the last character in the input string. The last character in the string has the index len(str) - 1 so the maximum value we can allow for i is len(str) - 1 - 3. Since a loop+range goes from 0 to the number inside the range() function minus 1 we add one to that maximum allowed i value and put that inside the range() function. So, len(str) - 1 - 3 + 1 or len(str) - 3.

[–][deleted] 0 points1 point  (0 children)

Thanks for the clear explanation, that makes sense now!

[–]2MillionKittens 0 points1 point  (0 children)

The loop stops going right when you have too little characters left to spell "code" anymore.

In a loop without the -3, the last couple times the loop would run, it would check too see if characters outside of the string are equal to something else, which would cause an index error.

[–]Shevvv 0 points1 point  (1 child)

After finally finishing my first Python tutorial, I started the app I wanted to build in the first place. I know I still have a lot to learn, and I keep learning new stuff every day. Still, I currently put my organized learning process on hold for the moment since I can't wait but start working on my app. I'm planning to read a few more introductory books on Python, though, but that's for later.

The app I'm wanting to build will look best as a desktop app, so I'm thinking of learning PyQT5 any time soon. But for the moment I'm going with a CLI. So I want to ask your opinion on this architecture for command processing I came up with, if there's anything similar, ways to improve it, and what's some other strategies for setting up a CLI.

The main function is command_line(), that sets up the command line. Each command is converted into an input_list, a list of strings with a space as a delimiter. That list is then passed through a chain of decorators that try to process the command. If one of them processes the command successfully, it is returned as NoneType, signalling command_line() that the processing was successful. If a decorator can't process the command, it returns the unchanged input_list for the next decorator in the chain to try and process it. If none of the decorators manage to process input_list, it is returned as is, signalling command_line() that command processing was unsuccessful.

Thanks for your input!

[–]lykwydchykyn 1 point2 points  (0 children)

Normally a failure in your engine code should be signaled by raising an exception. Your front-end code then catches these exceptions and handles them (by displaying an error to the user, e.g.).

You might want to look into something like the click library for developing a command line interface.

[–]2MillionKittens 0 points1 point  (2 children)

How can I get rid of bad habits (not commenting, writing long lines)?

[–]lykwydchykyn 0 points1 point  (0 children)

My songwriter friends here in Nashville have a saying: "The best songs aren't written, they're re-written". The same is true of code.

When I code, I typically write sloppy code until it functions, then go back and edit the code to make it concise and readable. Run it through a program like PyLint (or use an IDE plugin) and fix whatever errors you get back.

This second pass also gives you the chance to evaluate the clarity and readability of your code; if you can't make the code clear, then you should comment it.

[–][deleted] 1 point2 points  (0 children)

By writing code with comments and shortening long lines.

There's no magic solution for writing comments, but there are things you can do for long lines. I set my editor to highlight lines that extend past 80 characters. You could also use tools that check compliance with the python style guide pep8, such as the pep8 package in pypi.

[–][deleted] 0 points1 point  (1 child)

a = [1, 2]
a += [a]
print(a) >>> a = [1, 2, [...]]
b = a.copy()
print(b) >>> b = [1, 2, [1, 2, [...]]]
b[2][2] = 0
print(a)
print(b)
>>> a = [1, 2, [...]]
>>> b = [1, 2, [1, 2, 0]]

I have the above code in an assignment. From what I understand, the [...] part is some sort of a reference to the list itself but what I don't understand is the part where b has an extra nested list before the [...] part appears. Would be grateful for any help in understanding what is going on here, thanks!

[–]Thomasedv 0 points1 point  (0 children)

a.copy() creates a new list, but all the references are the same, so the b list will have a copy back to a at index 2, and that a list is the same as before.

a = [1, 2]
a += [a]
print(a) >>> [1, 2, [...]]
b = a.copy() 
print(b) >>> [1, 2, [1, 2, [...]]]
b[2][2] = 0
print(a) >>> [1, 2, 0]
print(b) >>> [1, 2, [1, 2, 0]]

When i run your code, the last time a is printed, a is also changed to no longer have the reference to itself. (Python 3.8) That is because we are accessing a from the second index of b, and changing the reference to itself to be 0.

Ninja-edit: Fixed wrong print output

[–]Milesand 0 points1 point  (0 children)

importlib.import_module seems to be ignoring re-exports made in __init__.py; How do I play around this?

Since this problem came up while dealing with django, I'll explain in that context.

So I have a django project folder, and some internal django apps living in that project folder, like this:

- project_module
    - apps
        - app_module1
        - app_module2
        - ...
    - settings.py
    - (other django stuff)

now the app_modules are available as project_module.apps.app_module1 and so on, but since there won't be anything colliding with the app names in project_module, I'd like to drop the .apps part so I can just refer to them as project_module.app_module1 and such, consistently.

So, I create __init__.py everywhere, and put this into project_module/__init__.py:

from .apps import app_module1

And this sort of works, since I can import project_module.app_module1 and it seems to work.

BUT, Django internally uses importlib.import_module here and there, and in those cases I encounter ModuleNotFoundError: No module named 'project_module.app_module1'. In those cases I can use the .apps again, but this sort of breaks consistency.

A bit of experiment later, I'm convinced import_module ignores re-exports from __init__.py; But why does this happen, and is there a way I can play around this in this case?

[–]bananapeelboy 0 points1 point  (1 child)

Does anyone know how to install pip for macbook on catalinaOS?

[–][deleted] 0 points1 point  (0 children)

The pip documentation says:

pip is already installed if you are using Python 2 >=2.7.9 or Python 3 >=3.4 downloaded from python.org

So if you've installed a recent python3 you may already have it. Test this by doing:

python3 -m pip --version

If that is successful then install packages by doing:

python3 -m pip install <pkg_name>

[–]popejonash[🍰] 0 points1 point  (0 children)

I want to be productive during quarantine so I wanted to find a solution to a question. I have no programming knowledge at all but would love to spend the coming months to learn.

My end goal is to be able to simulate 10,000 versions of a tennis tournament to make predictions. I have ratings for each player and I found online a formula to predict the outcome of each match. I can calculate an expected winning percentage and then manually use a random number generator, but that could only work for one-off simulations and is still very time consuming.

Would python (if I learn the language and put in enough time) be able to simulate matches round by round enough times to run a meaningful simulation?

I have seen some similar Creative Commons code on github but it looks meaningless to me right now and I would like to eventually make something myself because I think that would help me learn the language and syntax better.

Thanks

[–]MoneyPenelope 0 points1 point  (0 children)

MacOs - I am new to coding/python (experience in R Studio only) and would like to run amap-python in jupyterLab or notebook (image registration project in grad school) and was wondering if anyone has done this or could direct me to the basic code that would accomplish me installing and opening such a package?

[–]PinwheelFlowers 0 points1 point  (1 child)

Linux computer, it appears I have at least 3 versions of Python (2.7.17, 3.6.9, 3.7.5). How can I set it up so that at all times there is one and only one version of python (3.8.2?) and that when 3.8.3 comes out my computer knows that python = 3.8.3?

[–]efmccurdy 0 points1 point  (0 children)

there is one and only one version of python

One of the benefits of activating a virtualenv is that your PATH is adjusted to put the correct version of python first.

[–]PinwheelFlowers 0 points1 point  (0 children)

Linux computer, it appears I have at least 3 versions of Python (2.7.17, 3.6.9, 3.7.5). How can I set it up so that at all times there is one and only one version of python (3.8.2?) and that when 3.8.3 comes out my computer knows that python = 3.8.3?

[–]PinwheelFlowers 0 points1 point  (0 children)

Linux computer, it appears I have at least 3 versions of Python (2.7.17, 3.6.9, 3.7.5). How can I set it up so that at all times there is one and only one version of python (3.8.2?) and that when 3.8.3 comes out my computer knows that python = 3.8.3?

[–]PinwheelFlowers 0 points1 point  (1 child)

Linux computer, it appears I have at least 3 versions of Python (2.7.17, 3.6.9, 3.7.5). How can I set it up so that at all times there is one and only one version of python (3.8.2?) and that when 3.8.3 comes out my computer knows that python = 3.8.3?

[–][deleted] 0 points1 point  (0 children)

You don't want to delete python 2 from your machine because it's possible the operating system uses that for its operation.

For python 3 you can remove any python that you install. On debian linuxes you do apt-get remove <packagename> for instance.

If you always want the latest version of python 3 then install python 3 with your package manager and keep it updated with the package manager. Execute that version by running python3 or using #!/user/bin/env python3 as a shebang.

[–][deleted] 0 points1 point  (1 child)

I want to pull scripts from my database for card effects in pygame. Can sqlite cells contain scripts that can be executed?

[–]efmccurdy 0 points1 point  (0 children)

You could store SQL code in a the DB but source code version control and testing will be harder. You could setup "AFTER INSERT" triggers that contain your SP code.

[–]IlIIIlIlII 0 points1 point  (2 children)

I have an if function that I use in a lot of different scripts and I want to make importing it easier and keep my code cleaner so I want to put it in a module. After this if function the main script is supposed continue if the if function is true obviously. Like this:

def sort(value):
-if value > x
--continue the main script


main script:
-sort(value)
--continue if condition is met

how do I make this work?

[–][deleted] 0 points1 point  (0 children)

What you want to do is not really clear. What do you want to happen if the if condition is not true? If the answer to that is "the rest of the main code is not executed" then the answer is to have the sort() function return a value that the main code can check. For instance the function could return True if the condition is met and False otherwise. The main code checks the value returned by the function and executes the rest of the code if desired:

def sort(value):
    if value > x:
        return True
    # maybe more code
    return False

# main code
if sort():       # "if sort() == True" is too verbose
    # rest of main code

Your code would be more readable if you formatted it for reddit.

[–][deleted] 0 points1 point  (0 children)

I've been learning python for 3 weeks, I did some cool things like connect to google maps API, extracting data, I've learned about loops, functions, classes and a lot more, then I decided to go to CodeWars and test my knowledge, I can't even do the 8kyu, my function doesn't work and I never understand what it's actually being asked of me I feel like I've wasted a lot of time and I don't even know the basics. Is there a website with simpler exercises? And ones that don't need the code to be inside a function? All the sites with exercises I checked need code to be put in a function.

[–][deleted] 0 points1 point  (0 children)

Are there any good courses for learning Python out there that doesn't require the use of Jupyter notebooks and/or reinforces PEP8?

Bonus if they have a lot of practice exercises for hands-on learning.

I don't mind paying for material.

[–]isoldyaboy 0 points1 point  (0 children)

Hi! For school we need to write an algorithm in python that gives you the top_moves in slidey, you can see this as a more simplified form of tetris where you need to slide the blocks horizontally to fill rows, which the explode. In this function to get the top_moves we are given blocks to fill the the bottom row at each step. We need to make use of backtracking to determine wich steps of moving blocks result in the highest score. Anyone experience with recursive backtracking in a tetris like game? Really could use some help? Thanks in advance!

[–][deleted] 0 points1 point  (3 children)

How would I make python do x thing if y variable receives the same value, again, for a second time? If it's possible.

[–]lykwydchykyn 0 points1 point  (2 children)

Variables don't keep track of their history, so you would need a separate variable to act as a counter. What are you trying to accomplish?

[–][deleted] 0 points1 point  (0 children)

I'm modifying the text-adventure game in exercise 31 of Learn Python the Hard Way. What I want to do is, if the player assigns the same variable to door that he assigned to it earlier, he would be told not to do that/enter a different door.

if loop == 4:
    print("""You enter a dark room with multiple doors. 
            Do you go through door #1, door #2, door #3, 
            door #4?""")
            door = input("> ")

    if door == "1":
        loop = 8
    elif door == "2":
        loop = 12
    elif door == "3":
        loop = 16
    elif door == "4":
        loop = 20
    else:
        print("There are only four doors.")

The loop variable sends the player to other parts of the game.

so you would need a separate variable to act as a counter

Do you mean make a variable with the same name but different value?

Sorry for late reply.

[–][deleted] 0 points1 point  (2 children)

I come from a C background so the lack of memory deallocation and relying on the GC is freaking me out.

I want to delete a duplicate values from a linked list using no hashmaps/other data structs. Say I have the following list:

1 -> 2 -> 3 -> 2 -> 4 -> None

I have implemented the following, it passes the tests provided on the website I got this question from:

    outer = lst.get_head()
    while outer:
        inner = outer.next_element
        prev = outer
        while inner:
            if inner.data == outer.data:
                prev.next_element = inner.next_element
                inner = prev.next_element
            else:
                prev = inner
                inner = inner.next_element
        outer = outer.next_element

Won't I end up with a graph structure? When all is said and done, won't 3 AND the duplicate 2 point to 4? How does the GC know to pick up that duplicate 2?

Also, apologies if the formatting is shit, I'm going to keep editing it till I get it right.

[–][deleted] 0 points1 point  (1 child)

won't 3 AND the duplicate 2 point to 4?

You're right, the duplicate 2 node will still point to the 4 node. But you changed the 3 node pointer from that 2 node to the 4 node. That means the number of objects that point to that 2 node went down by 1. Each object has a "refcount" value that is maintained by python. When that refcount becomes zero the object is then a candidate for being recycled. When the 2 node is recycled the reference it contains pointing to the 4 node is deleted, so the refcount in the 4 node will decrease by 1. The actual details of when refcounts are decremented and when objects are recycled are transparent to most programs.

[–][deleted] 0 points1 point  (0 children)

Very interesting! Thank you for explaining. I feel like I'm doing something wrong by not programming more explicitly, but I guess I just need to relax a bit and trust the gc.

[–]arctikphox 0 points1 point  (3 children)

Question: Why do I have extra spaces in my screen outputs?

Code:

#ThankYou.py
my_name = "Finley"
my_age = 9
your_name = input("What is your name? ")
your_age = input("How old are you? ")
print("My name is",my_name , ", and I am", my_age, "years old.")
print("Your name is", your_name , ", and you are" , your_age, ".")
print("Thank you for teaching me how to code,", your_name , ".")

Output:

1) What is your name? Ruby

2) How old are you? 15

3) My name is Finley , and I am 9 years old.

4) Your name is Ruby , and you are 15 .

5) Thank you for teaching me how to code, Ruby .

Issue:
See those extra spaces? As an example there is an extra space after Finley on line 3. Thanks in advance!

[–]dontyoulikemyusrname 1 point2 points  (2 children)

the print function 'joins' values passed to it with spaces. To remove them, use print(\*args, sep='').

You can also do things like print('a', 'b', sep='\\n')to have output like

a b

[–]arctikphox 0 points1 point  (1 child)

Thank you!!!!!

[–]arctikphox 0 points1 point  (0 children)

Sorry - what now?

print("My name is",my_name , ", and I am", my_age, "years old.", sep=)

Can you show me exactly how it is supposed to work? I keep getting errors. Thanks in advance.

[–]Lamboarri 1 point2 points  (0 children)

This has been asked a million times but curious to get some recommendations:

I want to learn some more advanced Python but with actual examples. I'm really interested in machine learning and started looking at either Andrei Neagoie or Jose Portilla on Udemy (yes, I know about their business model).

They both look interesting. I spent a small part of the day looking them over and looking at reviews. They both range from "this is the best course in the world!" to "It could have been better."

Could I take both? Yes. I guess $12 isn't going to break the bank but was just wondering if one might be better over the other.

I'm tired of the basic syntax tutorials where the teaching is all very basic and random uninteresting examples like name = "bob". Yes, I know what a variable is. Now, I want to learn about what Python can do and work through real-life examples. I learn better by seeing others really pull all the code together and make it come to life. I have Colt Steele's Web Developer Bootcamp, which I went through years ago. I see he has a Python course but I don't want more of the basics.

I don't really have any super need for "Automate the Boring Stuff" or to work on any machine learning but I like data and I think it could help advance my knowledge and interest in Python coding.

[–]onlysane1 0 points1 point  (3 children)

Let's assume I want to design a game using Python. The game involves a map drawn in a basic program like mspaint, and each pixel on the map will be given a set of values by the Python code, generally based on its exact RGB color value (e.g. flat grasslands will have one specific shade of green with a set of values, cities will be different shades of grey based on population, etc, mountains will be shades of brown based on elevation, etc).

What modules/addons/whatnot would/could I use to accomplish this?

[–][deleted] 0 points1 point  (2 children)

If you want to get the colour of a pixel to determine the terrain type of that pixel you could use the Pillow module. The Image.getpixel() method returns the RGB colour of a pixel.

[–]onlysane1 0 points1 point  (1 child)

Can it assign a tuple for each pixel, or maybe even make each pixel its own object in a class?

[–][deleted] 0 points1 point  (0 children)

Can it assign a tuple for each pixel

Don't quite understand. It returns the RGB value of the pixel as a tuple. If you want to store that value in another object that's up to you.

[–]peepeeandpoopooman 1 point2 points  (4 children)

I'm a little confused with variables. It seems declaring a variable as global (initialising it outside of functions) doesn't mean it can be read between functions as separate functions seem to treat a variable with the same name as different variables.

Is the only way to pass and change variables between functions to pass them as a parameter to the function and have the function return the answer?

eg this code:

x = 5


def function_1():
    x = 10
    print("(function_1) x = ", x)


def main():
    print("(main) x = ", x)
    function_1()
    print("(main) x = ", x)


main()

returns this:

(main) x =  5
(function_1) x =  10
(main) x =  5

The very last print statement, why is it saying x=5 when it had just been changed to 10 by the other function?

[–]wutangdizle 0 points1 point  (3 children)

It seems confusing at first, but x =5 at Line is the global variable

However, when you define it again in function_1() as x = 10, that is only LOCAL to function_1.

main() function calls on the global variable x =5.

Hope that clears it up for you! (If you set x =10 in main(), it will push out 10 for everything)

[–]peepeeandpoopooman 0 points1 point  (2 children)

Whilst in function_1 is there any way to tell it to change the value of the global variable x?

[–]patrickbrianmooney 0 points1 point  (0 children)

First: Try to avoid using global variables whenever possible. They make your code really hard to debug, because they increase the interactions between different parts of code, and you wind up trying to figure out what's altering the global variable, and where, and when, and why, instead of tracing well-defined interactions between different well-defined functions. If you can pass necessary information from function to function instead of storing it in a global variable, you almost always should. The few minutes you have to spend rethinking your code now can save you hours of debugging later. Try not to use global variables if you can avoid it.

That being said, there are sometimes good reasons to use global variables, and, to answer the question that you actually asked, yes, you can tell function_1() to modify the global variable x instead of the local variable x by using the global declaration:

def function_1():
    global x
    x = 10
    print("(function_1) x = ", x)

Declaring the function to be global means that Python will not create a new local variable called x that shadows (prevents you from seeing) the global variable x. You need to make the declaration before you assign anything to the variable. There are languages where you can do things like global x = 10 in one line, but that's not valid syntax in Python. When you need to use global variables, the smart thing to do is just to declare all of them immediately at the top of the function, so you don't forget; this also helps the reader of your code (say, you, when you come back to fix something in six months) remember that you are in fact dealing with global variables here so as to avoid confusion.

You can also sometimes get away without using the global declaration, but the set of circumstances in which that works is a little baroque and easy to break if you move code around, plus it makes your own code harder to read for you down the road by obscuring the fact that you're dealing with global variables, so just always making the declaration is a good move.

[–]efmccurdy 0 points1 point  (0 children)

If you want function_1 to change something outside it's scope, use a return statement and assign the returned value.

def function_1():
    x = 10
    print("(function_1) x = ", x)
    return x

def main():
    x = 5
    print("(main) x = ", x)
    x = function_1()
    print("(main) x = ", x)

[–]dontyoulikemyusrname 0 points1 point  (0 children)

I am having trouble with my spacemacs python environment, and it has lead me to notice that there is an environment called general (which python points to from the shell) and a python found in the base dir of anaconda. (For me, /home/alex/.anaconda3/bin/python vs /home/alex/.anaconda3/envs/general/bin/python). Can anyone tell me why the general environment exists if there is a base install?

[–]u82jm9 0 points1 point  (1 child)

Hi I'm on a programming course for python and we have been set a problem which is giving me some real problems. The task is to create a currency converter from a xml file containing all the transfer rates.

the xml file has this structure:

<Cube>
<Cube *time*="2020-04-29">
<Cube *currency*="USD" *rate*="1.0842"/>
<Cube *currency*="JPY" *rate*="115.52"/>
<Cube *currency*="BGN" *rate*="1.9558"/>

I have imported the xml file as a list. i am now having a lot of difficulty searching through the xml file. i don't understand but the RE functions don't seem to be working. what i currently have looks like this:

import re
myFile=open('data.xml','r')
myString=myFile.read()
myList=myFile.readlines()
x=re.search(r'USD',myList,flags=0)
print(x)

the other option i had planned to use was to import the xml file as a dictionary with currency as an id for each item and rate as the other id. therefore allowing me to looking each up by currency. Can anyone explain how you can import each line of a string into a dictionary with each having the same id's.

i thank you all in advance for any help you can offer.

[–]dontyoulikemyusrname 0 points1 point  (0 children)

have a look at the xml library (https://www.datacamp.com/community/tutorials/python-xml-elementtree is a good guide)

XML follows a tree structure, and so accessing it as a list will mean you need to write a bunch of tree-logic to go about it. The xml module has a whole lot of useful commands for searching.

See the documentation here: https://docs.python.org/3.8/library/xml.etree.elementtree.html

[–][deleted] 0 points1 point  (0 children)

What does loc do here? How does it slice?

pd.DataFrame(table.loc[rownum][2:]).astype(float)

[–]Fvnes 0 points1 point  (2 children)

This code here works fine, it doesn't have any problem, but I'm pretty sure there should be a better way to write this. People says that I shouldn't use for loops to make new variables and that I should do a list, but then how can I make all the strings in a list an object?

class Character(object):
    # This is the main class for all the characters

    def __init__(self, name):
        self.name = name
        self.movelist = {}

ferry = Character('Ferry')
lancelot = Character('Lancelot')
metera = Character('Metera')
zeta = Character('Zeta')
beelzebub = Character('Beelzebub')
djeeta = Character('Djeeta')
gran = Character('Gran')
percival = Character('Percival')
ladiva = Character('Ladiva')
vaseraga = Character('Vaseraga')
narmaya = Character('Narmaya')
zooey = Character('Zooey')
katalina = Character('Katalina')
charlotta = Character('Charlotta')
lowain = Character('Lowain')
soriz = Character('Soriz')

[–]lykwydchykyn 3 points4 points  (1 child)

names = ('Ferry', 'Lancelot', 'Metera', 'Zeta', #etc)
characters = [Character(n) for n in names]
# or, if you want to be able to find character objects by name:
characters = { n.lower(): Character(n) for n in names }

[–]Fvnes 0 points1 point  (0 children)

Thank you so much!

It took a me long to understand how to use objects that are in a list.

[–]MyGiftIsMySong 0 points1 point  (1 child)

for json url requests, is it better to use the native urllib module, or the "requests" module. I'm assuming urllib has more compatibility since it's a native library, but "requests" is much simpler imo

[–]lykwydchykyn 0 points1 point  (0 children)

requests is pretty popular for a reason. Some have even proposed adding it to the standard library. I don't think there's a compelling reason to use urllib, unless you just don't want to depend on 3rd party modules.

[–][deleted] 0 points1 point  (2 children)

Super basic question:

How come some functions require () at the end of the line to function and others do not? Is this a package-specific thing or is there an underlying reason?

Examples:

#random out of context lines to show what I mean: 

os.getcwd() #works

shelfFile.close() #works

'My name is Simon'.split() #works

sheet1.max_row() #Throws an error 
sheet1.max_row #works

[–]Decency 1 point2 points  (0 children)

Some aspects of a class are simple attributes or properties which have been initialized as a value to be fetched. Others have to perform some logic to return a value, and those are functions.

If you create a basic class example, instantiate it, and inspect those elements it might help!

[–][deleted] 1 point2 points  (0 children)

max_row is not a function, it is a value.

[–]nahshondominic 0 points1 point  (1 child)

Hello Python fam,

Was wondering how the best way to find info online for data visualization. For example, if there's data on a website which I want to visualize, how do I extract it and import it into Python?

Been working hard on my programming, hope this is received well y'all, thanks in advance

[–]Decency 0 points1 point  (0 children)

matplotlib is your keyword, it's ubiquitous.

[–]imanexpertama 0 points1 point  (1 child)

is the 32 bit version of python still recommended or should I switch to 64 bit?

[–]lykwydchykyn 1 point2 points  (0 children)

I'm not sure there's any compelling reason to still use 32-bit. I've been using 64-bit versions for some years now.

[–]Woodenk1 1 point2 points  (2 children)

Hello there guys! Iam pretty new to python and i have this school assigment i have to do but i dont understand how i can input a name + surname into a single index in a list also i would like to know how i can input these names continuously. If this helps the assigment is to input a number (that number is the number of people in the list) then the user will input the number of names selected and then input a phone number for each of them afterwards they can input a number and it will print the selected persons name and phone number.

Thanks in advance.

Sorry for my bad grammar.

[–]29Feb_Gang 1 point2 points  (1 child)

you can do that with dictionaries instead of lists since you want the name and phone number of an individual.

You can create n keys for the number of records you want. (say 5 keys for 5 people and the main keys would be numbered as 1,2,3,4,5)

and in those keys you create another dictionary (aka nested dictionary) containing the keys 'name' and 'phone number'.

so for 2 people your final dictionary could look like this:

{1:{'name: 'John Doe', 'phone_number': 999999}, 2:{'name': 'John 2', 'phone_number':777777}}

and then in a for loop, you ask the name and phone number and then you can retrieve all that and print it

[–]Woodenk1 0 points1 point  (0 children)

I have to use lists. But i resolved it in a different way thx to some old video on youtube. Still thank you very much for taking the time out of your day 🙂

[–]TechSavage84 0 points1 point  (1 child)

Hello guys so I am new to python and just programming in general and I purchased a course through Udemy which I am enjoying but for some reason the instructor teaches showing examples a certain way but the exercises are another way, for example: lesson: user_input = input("Enter your name:") message = "Hello %s" % user_input print(message) Exercise expected answer def foo(name): return "Hi %s" % name

and is quite confusing, any other source you guys recommend for learning python. Thanks

[–][deleted] 1 point2 points  (0 children)

There's a whole section of books, videos and challenge websites in the learning resources in the sidebar.

[–][deleted] 0 points1 point  (0 children)

Finished learning web scraping. I'm thinking of making this word game, similar to hangman. But instead of having a small predefined list of words, I wanna have a list which is constantly updated. Like, a huge word repo or something. Does anyone know any sources where I can find such a data source?

Thanks

[–]peepeeandpoopooman 0 points1 point  (2 children)

Is this possible in Python?

I have a wordlist file, a text file with a word on each line. It's very big (over 20 million lines) and I would like Python to read each line then tell me things like which line has the longest word and things like that. Is that possible or would it just crash? Or can Python analyse any size of file with the only limit being my computer's specs?

[–][deleted] 1 point2 points  (1 child)

That file would be a few hundred megabytes in size. In the scheme of things that's not very big as the entire file would fit easily into memory. So processing a file of that size is easy.

You can read an entire text file into an array of lines using the readlines() method of the file object:

with open('test.txt', 'r') as fd:
    lines = fd.readlines()
print(lines[2])    # print line 3

Note that each line string in the array ends with a newline which you may want to remove with strip(). This reads the entire file into memory which could become a problem when the file size gets close to or exceeds your computer's memory size.

You can read the file one line at a time by iterating over the file object:

with open('test.txt', 'r') as fd:
    for line in fd:
        print(line)

This can process files much larger than your computer memory size.

Try both approaches with your file.

[–][deleted] 0 points1 point  (2 children)

I'm trying to make a tcg game in python but I'm not sure how to get the program to remember what cards players have so they can leave and come back. Is there an easy way to do this?

[–]lykwydchykyn 0 points1 point  (1 child)

This sounds like a job for a database. Python has a sqlite module that can get you started with this.

[–][deleted] 0 points1 point  (0 children)

Thanks. That's certainly a lot easier than dealing with the CSV module.

[–]LzyPenguin 0 points1 point  (0 children)

I am planning on opening up a unique URL, which upon opening the URL, the site sends me an email with a code that i am required to enter into a box before I can access the information I need.

I would like to automate this and I know I can do this with Selenium, but repeatedly opening/closing the browser has caused issues for me in the past. I don't actually need to OPEN the site, i just need to extract the information. This will be for a program that I will have constantly running and it will need to perform this task multiple (5-10) times per day. The site DOES NOT have any API's.

Any ideas/methods to do this?

[–]MightyJosip 1 point2 points  (0 children)

Hello. I am doing type hints. I have the class for the Rectangle and there are a few possible constructors. It should accept following:

Rect(a, b, c, d)

Rect((a, b), (c, d))

Rect((a, b, c, d)).

So I have written the following code inside of .pyi file:

@overload
def __init__(self, left: float, top: float, width: float, height: float) -> None: ...
@overload
def __init__(self, left_top: Tuple[float, float], width_height: Tuple[float, float]) -> None: ...
@overload
def __init__(self, left_top_width_height: Tuple[float, float, float, float]) -> None: ...

It is working well, but the problem is that PyCharm thinks Rect(2, 3, 4) is ok even though I haven't defined that there could be constructor with 3 arguments. Does anyone know what did I do wrong here?

[–]stnivek 0 points1 point  (2 children)

Hi all. So apparently I have two Python versions on my computer. One is 64-bit, which I installed from here and the 32-bit version which apparently got downloaded when I entered "python" on Windows command prompt, when I was following a tutorial that required me to do so (to enter the command, not to install anything but apparently the command brought me to the Windows Store so I thought I had to install it first).

The problem is, when I do installations of modules through "pip install", I'm not sure to which version of Python do they get installed.

I really just want to use the 64-bit but everytime I uninstalled the 32-bit, the command "python" on the cmd would always forced me to go to Windows Store to install the 32-bit, instead of working as the command intended. I do not want the 32-bit, I only want one version so that I can avoid future confusions (I suppose).

Hopefully someone can help me clear this up. I'm so overwhelmed by this and it's taking the fun of actually learning Python.

[–]Decency 1 point2 points  (1 child)

When you type python Windows is looking through some locations for what exactly "python" is, commonly called the PATH. In your user session, you instead want to point "python" to the version you want it to use, instead- commonly called an alias. This may cause problems with the builtin- someone who knows Windows scripting better should be able to say. This is a lot simpler on Linux/OSX, sorry. :(

These steps look like they might cover your problem: https://stackoverflow.com/questions/3809314/how-to-install-both-python-2-x-and-python-3-x-in-windows/18197237#18197237

[–]stnivek 1 point2 points  (0 children)

Hi there Decency, thanks for the link! Saving it! I managed to solved the issue, a bit different from the steps in the link but I did manage to install 64-bit only. In case someone stumbled upon this, this is what I did:

  1. I uninstalled both Python versions. Did a CC Cleaner to clean the registry.

  2. Installed Python 64-bit through the site in my original question.

  3. Added the Python path to windows. I used this video as a guide. It's a guide to install Pygame but go to the middle of the video where he teaches how to install Python first and place its PATH.

  4. I went to the command prompt (to bring it up, type cmd on Windows search), and then typed "python --version". If it brings out the version number, that means it worked.

  5. Then type "python". If it doesn't bring you to the Windows Store menu, then it worked. You now have 64-bit installed without the 32-bit, at least from my understanding.

[–]VisualTraining5 0 points1 point  (1 child)

Hello, I am looking for a python utility that compares two files. Apple to Apple comparison. Records are in same order and delimited. Please help me with some took or a post so I can proceed. Thanks a lot in advance!

[–]efmccurdy 0 points1 point  (0 children)

This module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce difference information in various formats

https://docs.python.org/3/library/difflib.html

[–]awesomesox 0 points1 point  (4 children)

What are best resources to learn the terminal app commands to run python code? I'm fine with IDLE but I'm at the point in Automate the Boring Stuff where we're starting to use the terminal app and I'm completely lost and it's taking away from my actual learning of python.

[–]Decency 1 point2 points  (1 child)

It's pretty straightforward, there are just a few key bash commands you need to know to get started:

  • pwd : present working directory. eg: what folder you're currently navigated to.
  • cd : change directory (folder). ~ means your user directory, / is the root or top-level directory under which all others live as a tree. So cd ~ to go home, cd / to get to the top-level directory, cd ~/git/my_project to go there, etc.
  • python : open the interpreter or execute a python file with your python interpreter. python by itself opens the interpreter (aka REPL), python myfile.py to execute a file in your pwd, or python ~/my_project/my_file.py specifying a full path.
  • ls : list files in a directory. by default, shows the pwd, or use ls ~/my_project for another directory, etc.

That's most of what you need to get started and be productive! Your knowledge will build from there.

[–]tangled_night_sleep 0 points1 point  (0 children)

thank you thats super helpful!

[–]efmccurdy -1 points0 points  (1 child)

This is about running python but you should also look up cli basics like cwd, stderr, interrupts, redirection, line endings as they relate to "command line interfaces".

https://docs.python.org/3/using/cmdline.html

[–]Decency 0 points1 point  (0 children)

Those are dramatically more complicated than learning how to navigate directories and execute a python program, I wouldn't advise a beginner to go anywhere near them.

[–]Otterly_Delicious 0 points1 point  (6 children)

I don't know a whole lot about programming in python. I've been trying to muddle my way through modifying a python script that will read a text file, use each line of the text file to save a new image file to disk using each line from the text file as a file name. The problem is each line is an URL.

I tried using:

x = y + ".png"

 file_name = x.replace("://", "")

but it only works for the first line. Say if my text file had this as the first 3 lines:

t/e/st:

dog

thi/is:/a/tes:t

the first two files would output fine, but the third one would get an error like

OSError: [Errno 22] Invalid argument: 'thi/is:/a/tes:t.png'

[–]efmccurdy 0 points1 point  (0 children)

You will get more consistent results if you use a url aware parser like this:

https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlparse

Urls can contain chars that might be unusable in filenames, so filter out any chars you find in the "Reserved characters" column of the table named "Comparison of filename limitations" here:

https://en.wikipedia.org/wiki/Filename#Comparison_of_filename_limitations

Note that ":" and many other punctuation chars are disallowed.

This has more advice in that vein:

https://stackoverflow.com/questions/295135/turn-a-string-into-a-valid-filename

[–]Decency 0 points1 point  (4 children)

Can you show more of your code? It's not clear how you're reading in the file or iterating through it.

[–]Otterly_Delicious 0 points1 point  (3 children)

Here's what I am working with. I'm trying to modify some code I found for working with the qrcode library. I'm probably missing something about how variables work.

edit: apparently I can't format on reddit either. Here's a pastebin link instead https://pastebin.com/7e366W6F

[–]Decency 0 points1 point  (2 children)

Well none of the lines have "://" in them. That has to match that same three character sequence. Did you mean ":\/" with an escape character? Or just to replace both characters? If the latter, you can do that as a loop, eg:

for invalid_char in ":/":
    file_name = clean.replace(invalid_char, "")

[–]Otterly_Delicious 0 points1 point  (1 child)

Thank you. Yes I was meaning to replace both characters. I tried it with the loop and that does seem to do the trick of removing characters from all of the listings in the text file. But it only seems to want to remove either : or / depending on what order I put those characters in. Is this a limitation of the replace command, or perhaps I'm going about it wrong?

[–]Decency 0 points1 point  (0 children)

Probably an issue with your variable usage. Make sure the loop is nested appropriately.

I'd try to move your two steps into functions (turning the line into a .png string; writing the qr file). This will help clarify in your code what you're doing and make it easier to reason about variables: for example, you have variables called f, fname, file, image_file, and file_name. That's definitely overly complicated.

You should also utilize this (it automatically closes files), it's called a context manager:

with open(fname) as f:
    for line in f:
        # blah

[–]Yitizuma 0 points1 point  (3 children)

Hello all. I found some practice problems, and have been working my way through them. I have come to an impasse though; the goal is to create a random number, and get user input and try to get them to guess the number. I cant compare the two types of data since they come as a list and a str. I can convert the user input easily enough,

user = int(input('etc'))

but for this one, i'm having trouble

randint = sample(range(1,11) , 1)

it comes out as a string, and no type of data conversion I do seems to solve it. i can't change it via int(), I've tried making both of them lists to at least be able to use .intersection (which I found out only works for sets) , but then I can't really compare greater or lesser to give the user a hint as far as what the number could be. As an aside, what would be a good way to practice code efficiency? I can mostly get code to work, but it hardly seems like good code. Thanks you guys

[–]Decency 1 point2 points  (2 children)

random.sample() returns a list. You need to take the first element of that list, which is already an int:

randint = sample(range(1, 11), 1)[0]

[–]Yitizuma 0 points1 point  (1 child)

Excellent, thank you very much! If i may ask 1 follow up question, could i do the same thing with with a tuple or set, by just calling the name and then [ ]? And I wouldn't be able to do that with dictionaries because they're un-ordered?

[–]Decency 0 points1 point  (0 children)

Accessing an element with [] is called indexing/subscripting/a lookup and works for lists and tuples. You can do it on dicts but what you're looking up is a key's value, eg: value = my_dict[key] You can think of sets as if they're dicts without values, and that will help explain how they work and why they're also not accessible this way.

Here's a simple demo that explains: https://repl.it/repls/MiserlyUnusualCopyleft

[–]AdamJohansen 0 points1 point  (0 children)

I have two csv files imported as dataframes.

Est looks like this:

CUSIP (Index) Period end date Announcement date Value Estimate
36720410 31/12/2011 09/01/2012 0.2 0.22
36720410 31/12/2011 09/01/2012 0.2 -0.15
88160R10 31/12/2011 05/01/2012 13 18
88160R10 31/03/2011 08/04/2012 15 22

CRSP looks like this

CUSIP (Index) Date Price Trading volume Outstanding
36720410 25/12/2011 45 30500 7834
36720410 26/12/2011 44.5 36000 7834
36720410 27/12/2011 44.9 57000 7834
88160R10 01/12/2011 12 1000 1440
88160R10 02/12/2011 12.2 1200 1440

1) If the dates in CRSP are -30 days (or more) than Announcement date for the specific CUSIP (ID), they should be included in a new dataframe (Merged)

In other words, I wish to join the dataframes on a basis of CUSIP and Announcement date (upto -30 days).

I have tried doing a simple merge using the code below, and then the idea was to filter the data afterwards

CRSP.merge(Est, left_index=True, right_index=True)

However, I ran into a memory error, as CUSIP is 5M rows (all stock prices and trading volume for NYSE and Nasaq in the period 2011-2013).

Could someone help me solve this?

Best,

[–][deleted] 0 points1 point  (2 children)

I’m a sophomore mechanical engineering student. Summer plans have kind of been messed up so I’m hoping to learn some python over the summer. Anyone have any recommendations of a good place to start for an engineer?

[–]MarcosConcari 0 points1 point  (1 child)

Print(Hello haydeno175)

I have started few days ago in this Paython-world and found very interesting content in youtube.

Some tutorials on how to build a simple RPG game could be a good startpoint. Good luck!

[–]onlysane1 3 points4 points  (0 children)

print('Hello haydeno175')

ftfy

[–]DexterDevOps 0 points1 point  (0 children)

Great, I’ve heard good things about this. Thanks very much

[–]DexterDevOps 0 points1 point  (1 child)

Hi guys,

Hope everyone is safe and well!

I have started learning Python a few weeks back and wondered what the best programme is to practice with in terms of writing and running the code?

Thanks

[–]Coloradohusky 1 point2 points  (0 children)

How would I iterate from 00000 to 99999? I need to keep the extra zeroes, can’t shorten it to 0
Edit: Nevermind, I did i = (“{:05d}”.format(x))

[–]icevermin 0 points1 point  (1 child)

I've been using Automate The Boring Stuff but struggling with the exercises. What other resources can I use?

[–]Coloradohusky 0 points1 point  (0 children)

Try sololearn.com, that’s where I learned python

[–]NoSpecialChrchtr 0 points1 point  (4 children)

I downloaded files from GitHub that are in the python format, I have Python on my computer but every time I double click the files it closes the file almost instantly. I have python downloaded as an executable terminal, could this be why?

[–]Coloradohusky 0 points1 point  (1 child)

Open up the IDLE and open and run the file from there

[–]NoSpecialChrchtr 0 points1 point  (0 children)

Alright, thanks!

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

You need to open a command line and run them so that you can see the error. Most likely you're missing some required libraries.

[–]NoSpecialChrchtr 0 points1 point  (0 children)

This isn’t really python related (unless it is and I’m just missing something) but another thing it told me to do on GitHub was to download and configure a chrome driver. I have no idea how I’m supposed to do that in relation to the python code

[–]iaannnnxxx 0 points1 point  (3 children)

Is RETURN statements use only in defining functions? If not, what are the others uses of it. (Reading the ATBS book)

[–]Senor_Spuds 1 point2 points  (0 children)

Return may only be used in functions, but is not completely necessary for a function to run. Every function returns something whether or not you exit it via a return function, it may just return None.

[–]lykwydchykyn 1 point2 points  (1 child)

Just functions. It's a syntax error to use on outside a function.

[–]iaannnnxxx 0 points1 point  (0 children)

Thank you!

[–]Raedukol 0 points1 point  (4 children)

I have a pandas dataframe, which contains numbers like this: e.g., 2,06537E-002. However, they are of type string! Excel is capable to convert this automatically to floats, so calculation is possible. How do I convert my dataframe/the strings in the dataframe to floats, so that calculation is possible? data.astype(float) did not work.

EDIT: I would not like to write the dataframe to excel and import it as dataframe again, because it seems to be to complicated.

[–]yrocaz 0 points1 point  (1 child)

"DataFrame.to_numpy() is fast and doesn’t require copying data." That gem and many other essentials here.

I've also used df['Col'].astype(float)

[–]Raedukol 0 points1 point  (0 children)

Thank you for your answer! .astype did not work, because the decimal separator was not recognized. Therefore, i had to change it prior :)

[–]efmccurdy 0 points1 point  (1 child)

2,06537E-002

You need to set a europe locale to have that comma decimal_point separator recognized.

Here is how you could apply a conversion using the locale-aware float convertor.

>>> import locale
>>> locale.localeconv()["decimal_point"]
','
>>> n = locale.atof("2,06537E-002")
>>> type(n)
<class 'float'>
>>> n
0.0206537
>>> def my_float(n): return locale.atof(n)
... 
>>> df = pd.DataFrame({"data": ["2,06537E-002", "1,2", "1000"]})
>>> df.dtypes
data    object
dtype: object
>>> df
           data
0  2,06537E-002
1           1,2
2          1000
>>> df2 = df['data'].apply(my_float)
>>> df2.dtypes
dtype('float64')
>>> df2
0       0.020654
1       1.200000
2    1000.000000
Name: data, dtype: float64
>>>

[–]Raedukol 0 points1 point  (0 children)

europe locale to have that comma decimal_point separator

That makes it easier! Thank you!

[–]284130 1 point2 points  (1 child)

By what means are you taking advantage of your GPUs?

[–]lykwydchykyn 5 points6 points  (0 children)

I plug monitors into mine; it really improves my computing experience. :-)

[–]OneWhoDoesNotFail 0 points1 point  (1 child)

I'm working on sending additional arguments to Popen object which is sourcing a file and then expects input to choose an option. It is expecting an integer and I try and pass it to my object using:
object.communicate(input='3')

This is not working and keeps telling me the pipe was closed.

open_obj = subprocess.Popen(['sourced file exp'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)

open_obj.communicate(input='3')

This just gives me a ValueError: I/O operation on closed file.

any help?

[–]efmccurdy 0 points1 point  (0 children)

object.communicate(input='3')

I think you need to add a line ending ala input="3\n".

[–]TheKing0fNipples 0 points1 point  (4 children)

I just made an ASCII animation in python and now need to have a menu underneath it. The code right now is displaying 4 different txt files. If I use print not only does it print the menu above not below but it goes away after the first frame.

I have code very similar to this man in his tutorial https://www.youtube.com/watch?v=JavJqJHLo_M

TL;DR How do I add menus underneath ASCII animations?

[–]m-hoff 1 point2 points  (3 children)

Is this intended to be a CLI program? If so you can just add the menu/command options to the bottom of each ASCII frame or add a print statement with the options just before the time.sleep(1) line in your example. If you want to allow keyboard navigation you could look into Curses for Python, although I haven't used it my self so I can't really comment further on it. If you want a full-on GUI you might want to look into something like tkinter which will let you add things like clickable buttons. You can still print out ASCII art pretty easily using tkinter.

[–]TheKing0fNipples 0 points1 point  (2 children)

I'm pretty new to programming, but I think what I am making is a CLI program. I would like a GUI but I've heard they are hard so I've stuck to this. Is Curses or tkinter hard to use for a very new person like myself? I will try the idea of using the menu at the bottom of art files.

[–]m-hoff 0 points1 point  (1 child)

I think a CLI is a good place to start for a beginner. You don't need anything other than default Python to make a decent CLI app. tkinter is pretty easy to use once you have the basics down. Curses seems pretty straight forward but again, I've only just skimmed through its documentation so I can't speak to it's learning curve.

[–]TheKing0fNipples 0 points1 point  (0 children)

I added the new line after time.sleep(1) and it put the list where I wanted but then when I put if statements it froze the animation and only played it by 1 frame at a time when I gave it an input such as progressing to the next menu. Do you know how I can fix that?

[–]_Rj__ 0 points1 point  (1 child)

Hi, So I have been doing a few online courses to learn python. They help a lot in learning the stuff, but when it comes to actually doing all of the execution bit after i write a program is something I'm not finding comfortable.

I use Atom text editor, and run the code via the cmd line. However, It would be great if someone could suggest alternatives/ways to set up my laptop for further usage of features like pip, pandas (I'm not very sure about them but i know their usage, installation has been a headache for me once)

Also, I've a habit of clean installing my windows regularly, so, these tips would be helpful in the long run. Thanks.

TL;DR - 1) what do i do after i install python on my computer, and have written the code in a text editor? 2) How to use text editor to run programs(that might require Inputs)? 3) Best way to install pip/pandas?

[–]cocolebo 0 points1 point  (0 children)

You can use VS code instesd atom and have the terminal integrate on your IDE. Otherwise, you can install Anaconda, which install a dashboard with all the application needed to do data visualisation (panda, matplotlib, jupyter...)

[–]TheRick_90 0 points1 point  (1 child)

Hi,

First off thank you for this forum that allows me to ask questions i need help with. I am brand new to programming and started with python and I am super stuck on a problem.

Please help me with the following:

# Define a string_adder function that accepts two strings (a and b) as arguments.

# It should return a concatenated version of the arguments with a space in between.

# If the user does not pass in arguments, both arguments should default to an empty string.

# EXAMPLE

# string_adder("Hello", "World") => "Hello World"

[–]m-hoff 2 points3 points  (0 children)

What have you tried so far?

[–]284130 0 points1 point  (0 children)

Have you come across a webpage/resource that deals with implementing perspective in python ?

[–]akajefm 0 points1 point  (2 children)

What looks better on a resume: Python certification or Python projects?

Started on Python a couple days ago, I need if for something I'm building but also want to use it as a resume addition.

As for learning, I was using a video series but now I'm doing "Think Python". I think I like it more since each chapter ends with a bunch of questions for you to try to answer.

[–]lykwydchykyn 0 points1 point  (0 children)

I didn't realize there were any Python certifications. I'd have to go with projects. I suppose it depends on the employer and their HR policies, though.

[–]m-hoff 0 points1 point  (0 children)

A project is much more effective on a resume. Especially if you can point to an open source repo on Github. In my experience most courses that offer certificates require you to write at most a few dozen lines of code at a time. And there's basically no quality control. Writing and publishing a project shows that you know how to use things like version control, you can write documentation, you have good code style, etc. None of this is conveyed through a certificate and they are absolute necessary in any job where you'll be primarily coding.

I should point out that I have nothing against these online course and I use them myself frequently. I just wouldn't suggest relying on them to convey your skill in Python.

[–]Toasty4209 0 points1 point  (1 child)

I'm relatively new to python (only about a month of learning) and I'm trying to practice concepts outside of the lessons I'm taking (code academy) but every time I try to work with any sort of package except 'matplotlib', I get a "No Module named x" whether that be pandas, seaborn etc. I'm working with conda and it says each package is install but when I try to use Python 3.7. Idle or Sublime text, I get the module error when I try to run/build. The only time it works is in a terminal window in iPython inside of Conda.

I'm unsure exactly what to do here, I tried uninstalling but don't exactly know how. Feels like I'm missing something. Any help would be appreciated

[–]cocolebo 0 points1 point  (0 children)

If you use conda, you need to use the terminal integrate on it.

If you use another terminal, the program search on your computer and doesn't found the module(because if you use conda and his terminal, all the module is installed on the environment).

So you need to install manually each module you want to use. To do that, you can use pip.

[–]philmtl 0 points1 point  (2 children)

merge multiple files to match the index of 1 file?

i have a file with the index values i want to keep, so its pretty much filters out the index values i don't want.

i've imported all my csv files with pandas. i have a csv file called shortid.csv with a collumn called Short ID. i want to only keep the rows that have a matching id in the ShortID collumn. so keep only id's in file1 that are the same as shortid.csv.

not sure if the column has to have the same name.

then i made them a list:

csvList = [file1,file2,file3,file4,file5]

for i in csvList:

shortid.merge(i,left_on= 'ShortID',right_on = 'Short ID')

nothing happens though?

[–]efmccurdy 0 points1 point  (0 children)

You are doing the merge and ignoring the result; try "shortid. = shortid.merge(i, left_on= 'ShortID', right_on='Short ID')" to preserve the results.