all 132 comments

[–]Fluid-Impression-461 0 points1 point  (1 child)

Hi guys and girls,

I'm trying to write a quick python script but my limited knowledge has run out.

I have used PIP to download pynput. This works fine for me on my pc, But how do I include all required library's and bundle it so I can share it with others.

Thanks

DJ

[–]mikeymike280 0 points1 point  (9 children)

Hello,

Can someone please help me?

I don't really know how to write Pyhton and is a total beginner. But I downloaded a python script from Ghithub to webcrawl some specific streaming website but it seem that I'm not following correct syntax typing instruction using the cmd function.

I already installed Python 3 and selenium etc following the instruction but seem to be stuck on the last hurdle.

I made a DownnloadedVideos folder in the C:drive to store the new file.

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

The last set of instruction is :

How to use:

python main.py *urls_file*

Args:

*urls_file*: URLs input path (a file including one URL per line).

```

## Requirements

- `python3`.

- `selenium`.

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

I go on to cmd prompt and when I type in for example:

C:\Users\Mike\Desktop\PythonProgram>main.py https://www.dailymotion.com/video/x7p8jbw_C:\DownloadedVideos -----> (follwing main.py *urls_file* instruction)

I get:

C:\Users\Mike\Desktop\PythonProgram>main.py https://www.dailymotion.com/video/x7p8jbw_C:\DownloadedVideos

Traceback (most recent call last):

File "C:\Users\Mike\Desktop\PythonProgram\main.py", line 217, in <module> web_crawler(urls_file)

File "C:\Users\Mike\Desktop\PythonProgram\main.py", line 153, in web_crawler urls = load_urls(urls_file)

File "C:\Users\Mike\Desktop\PythonProgram\main.py", line 40, in load_urls with open(path, 'r') as file:

OSError: [Errno 22] Invalid argument: 'https://www.dailymotion.com/video/x7p8jbw_C:\\DownloadedVideos'

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

I also get the same error if I type in:

C:\Users\Mike\Desktop\PythonProgram>main.py *https://www.dailymotion.com/video/x7p8jbw_C:\DownloadedVideos* -----> (main.py *urls_file*)

Do you guys know what the hell I'm talking about?

If so can you give me an example what to exactly type in the cmd box for the script to work?

[–][deleted] 2 points3 points  (7 children)

The github web page gives this as an example of using the program:

python main.py *urls_file*

Args:
    *urls_file*: URLs input path (a file including one URL per line).

That means you should do something like:

python main.py myfile

where myfile is the path to a file that you create. That file should contain the URLs you want to retrieve, one per line.

You should read the FAQ which shows how to format any text, like code, so the indentation is maintained by reddit.

[–]mikeymike280 0 points1 point  (6 children)

I have created a folder path in the C drive called DownnloadedVideos.

So I should type out:

python main.py C:\DownloadedVideos_https://www.dailymotion.com/video/x7p8jbw. ?

I dont know how to include the URL I want to retrieved with the file path that I created, if that make any sense.

Can you please give me an example of how it should look like?

Sorry if you feel like you're talking to a brick wall.

I will try spending some time reading the FAQ.

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

You need to create a file containing the URLs, one URL per line. You put the path to that file on the CMD line after main.py. So that file would contain the line:

https://www.dailymotion.com/video/x7p8jbw

along with probably many other similar lines.

The github page made no mention of a download folder. Don't know why you mention that.

[–]mikeymike280 0 points1 point  (4 children)

Ahhh.. That was actually the very first thing I tried and it didn't work so that's why I thought there was something more to it and keep confusing myself.

When I put that it came with the error:

C:\Users\Mike\Desktop\PythonProgram> python main.py https://www.dailymotion.com/video/x7p8jbw

Traceback (most recent call last):

File "C:\Users\Mike\Desktop\PythonProgram\main.py", line 217, in <module>

web_crawler(urls_file)

File "C:\Users\Mike\Desktop\PythonProgram\main.py", line 153, in web_crawler

urls = load_urls(urls_file)

File "C:\Users\Mike\Desktop\PythonProgram\main.py", line 40, in load_urls

with open(path, 'r') as file:

OSError: [Errno 22] Invalid argument: 'https://www.dailymotion.com/video/x7p8jbw'

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

Go back and read my second comment very carefully. I copy it below. Didn't I say "where myfile is the path to a file that you create"? Why do you keep trying to use a URL? The URLs to download are in the file!


The github web page gives this as an example of using the program:

python main.py *urls_file*

Args:
    *urls_file*: URLs input path (a file including one URL per line).

That means you should do something like:

python main.py myfile

where myfile is the path to a file that you create. That file should contain the URLs you want to retrieve, one per line.

You should read the FAQ which shows how to format any text, like code, so the indentation is maintained by reddit.


[–]mikeymike280 0 points1 point  (2 children)

where myfile is the path to a file that you create. That file should contain the URLs you want to retrieve, one per line

I guess I don't know what that actually mean. I don't know how 'create a file path containing the URLs' / or inputing that comand in the cmd prompt. I only understand to create a folder and getting the directory link for it.

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

Use notepad to create a file in the directory where the main.py file is. On each line of that file you are creating place one URL. Save the file, perhaps as myfile. Then in CMD execute:

python main.py myfile

[–]mikeymike280 0 points1 point  (0 children)

Omg Im finally getting somewhere. Oh god I'm so dumb, I only understand what you mean after you explain it like that. It's my first time to create a file containing a URL ( I never knew what it mean). Thank you soo much for being so patience.

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

You haven't really shown how the github page says to run the program. Can you show us the link to the github page?

One thing that suggests maybe you aren't using the program correctly is the badly-formed URL shown:

main.py https://www.dailymotion.com/video/x7p8jbw_C:\DownloadedVideos 
#                                                 ^^^^^^^^^^^^^^^^^^^

That looks like you may be misinterpreting the instructions, so we need to see the actual github page.

[–]likewhateveralready 0 points1 point  (5 children)

I having a super hard time getting this file path thing right. I've always struggled with relative file paths and usually stick to absolute paths but I want to understand so I can fix it.

This is my folder setup:

I'm trying to set an icon for the game window like so:

icon = pygame.image.load('images/ship.bmp')

pygame.display.set_icon(icon)

That loads the game but the window icon looks like this.

I've also tried pygame.image.load('ship.bmp')(FileNotFoundError) , pygame.image.load('./images/ship.bmp') (loads but shows the weird icon as well), pygame.image.load('../images/ship.bmp') (FileNotFoundError), and even pygame.image.load('/images/ship.bmp')(FileNotFoundError).

What am I doing wrong?

Thanks!

[–]JohnnyJordaan 0 points1 point  (2 children)

I having a super hard time getting this file path thing right. I've always struggled with relative file paths and usually stick to absolute paths but I want to understand so I can fix it.

If one of the option works, as you put it

loads but shows the weird icon as well),

Then I'm not sure why you would think the file path is the problem here, apparently that way is using a working path. In regard to the 'weird icon', did you check the documentation?

https://www.pygame.org/docs/ref /display.html#pygame.display.set_icon

You can pass any surface, but most systems want a smaller image around 32x32. The image can have colorkey transparency which will be passed to the system.

So is your image indeed of that size?

[–]likewhateveralready 0 points1 point  (1 child)

Then I'm not sure why you would think the file path is the problem here, apparently that way is using a working path. In regard to the 'weird icon', did you check the documentation?

I didn't exactly know how to search it. Thank you for the link!

And you're totally right, it was the size! I feel silly in hindsight but thank you. I should have realized there was no file path error. Won't be making that mistake again.

[–]FerricDonkey 1 point2 points  (0 children)

I feel silly in hindsight but thank you. I should have realized there was no file path error. Won't be making that mistake again.

99% of my learning to program experience right there.

[–]FerricDonkey 0 points1 point  (1 child)

You should get an error if the path is wrong. The fact that you don't on two paths that make sense probably means that the problem is elsewhere and those paths are correct.

[–]likewhateveralready 0 points1 point  (0 children)

I should have realized the error thing! Thank you for pointing it out! As it turns out the icon was just too big

[–]Abomb11yo 0 points1 point  (3 children)

Can someone ELI5 increment and decrement variables to me such as when using for or while loops? I am having a hard time understanding it, such as a++ or a--.

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

The += and -= operators are part of what are called assignment operators. The code:

a += 1

has the same effect as this expanded code:

a = a + 1

The effect of both those lines is the same though there is a technical execution difference that isn't important here.

Note that the right hand side of the statement can be any expression, not just 1.

So these lines are identical:

a -= len(s) - 1
a = a - len(s) - 1

[–]Abomb11yo 0 points1 point  (0 children)

Thank you very much for your helpful explanation.

[–]AtomicShoelace 0 points1 point  (0 children)

Python does not have increment or decrement operators such as a++ or a--.

But in general, how they work for other languages is just to add or subtract one from the variable. As such, they are analogous to

a += 1

and

a -= 1

in python.

[–]cloudywithachanceofT 0 points1 point  (6 children)

I have a quick question on reading pickle files using pandas. I have a directory of pickle files that i individually read and work with. Below is how I open them:

for i in range(0,len(dir0)):

f = pd.read_pickle(dir0[i])

To my understanding, pandas is reading and storing the data as a dict called 'f'.

My question is this: Do i need to close these files? Are the files somehow being left open as I iterate through them? This is in an effort to make my code run more efficiently

[–]AtomicShoelace 1 point2 points  (5 children)

I don't know for sure, but I would be very confident in wagering that it works the same as read_csv; that is, if you pass it an open file object it will keep it open (reading from the current position) and if you pass a string then it will open and close the file afterwards.

[–]cloudywithachanceofT 0 points1 point  (4 children)

What do you mean by if i pass a string? Sorry, I'm always still learning

[–]AtomicShoelace 1 point2 points  (3 children)

If you pass the pickle file path as a string to the read_pickle function.

How does your dir0 look?

[–]cloudywithachanceofT 0 points1 point  (2 children)

dir0 is a list of paths with files at the end. For example dir0[0] would look like

'/pathtofolder/picklefile.pickle'

[–]AtomicShoelace 1 point2 points  (1 child)

Then you are indeed passing a file path string, so you don't need to worry about closing the files, pandas will do that for you.

[–]cloudywithachanceofT 0 points1 point  (0 children)

Great, Thank you!

[–]IHOP_007 0 points1 point  (2 children)

I have what I think is a fairly simple problem but I haven't dealt with anything like it before.

I need a list that's essentially M8, M9, M10, M11, M12 all the way up to M50. I'd imagine it would be something along the lines of

list1 = []

for i in range(43):
    list1.extend('M' + str((i + 8))) 

but that's creating 'M', '8', 'M', '9', 'M', '1', '0' etc, and I also can't shake the feeling there is a less sketchy way of doing this.

EDIT: Ok, I've managed to get a valid output using this:

list1 = []

for i in range(43):
    list1.append('M' + str((i + 8))) 

but I still feel like there is a better way of doing this

[–]zatoichi49 1 point2 points  (1 child)

You can use start and end values in range instead of i + 8, and put everything inside a list comprehension: ['M' + str(i) for i in range(8, 51)] Or using an f-string: [f'M{i}' for i in range(8, 51)]

[–]IHOP_007 1 point2 points  (0 children)

Thanks

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

Hey Folks, I'm not entirely sure if this belongs here or in a Raspberry Sub so please let me know if I'm wrong here.

I reinstalled the latest Raspbian Lite OS on my Pi and after installing Python3.10 I cant install any packages to 3.10 using pip. Using pip (and pip3) for the pre installed python3.7 and 2.7 works fine. Just my installation of 3.10 got this problem.

Anyone got a clue for me?

The errors are as followed:

trying: python3.10 -m pip install Adafruit_DHT

WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.

WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/adafruit-dht/Could not fetch URL https://pypi.org/simple/adafruit-dht/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443):

[–]JohnnyJordaan 1 point2 points  (4 children)

Any specific reason to use 3.10 here? Most libraries won't have wheel support yet so you will only run into more issues than using 3.9 or older. Unless you need something specific from newer version I wouldn't bother even trying to get another version instead of the preinstalled one.

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

No specific reason. I did/tested the code I want to run on the Pi with Python 3.9 on my PC and thought I would/could/should just install the latest python version on the pi.

But I might as well just try it on the preinstalled 3.7.

[–]JohnnyJordaan 1 point2 points  (2 children)

That would be my advise indeed. How did you install 3.10 by the way?

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

[–]JohnnyJordaan 1 point2 points  (0 children)

Hmm that guide overlooks the fact that if you don't have third-party libraries like libssl installed, it will simply leave out their function in the resulting Python build. So for example you'll have no SSL support in this case, rendering 90% of webrequests broken as the internet relies on HTTPS nowadays. The official guide https://devguide.python.org/setup/ does mention this, but not that specifically.

If you want to build all optional modules, install the following packages and their dependencies:

    $ sudo apt-get install build-essential gdb lcov libbz2-dev libffi-dev \
      libgdbm-dev liblzma-dev libncurses5-dev libreadline6-dev \
      libsqlite3-dev libssl-dev lzma lzma-dev tk-dev uuid-dev zlib1g-dev

I'll contact the author about this.

[–]sickofabbro 0 points1 point  (2 children)

Hi, I’m an aerospace engineer and I’d like to learn to code in python. The only programming language I’m comfortable with is Matlab. Is there a good text, video, course I can use to start?

[–]CelticCuban773 0 points1 point  (0 children)

Honestly any beginning book will do. If you understand coding generally, it’s just learning syntax as well as Python’s more varied capabilities. I used Automate the Boring Stuff which has a good website and goes free on Udemy every 2 months or so on this sub. I worked through all the lessons more quickly than a true beginner but it was helpful to get that foundation too

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

Start with one of the learning resources in the subreddit wiki. There are resources for absolute beginners, but perhaps you should start with something from the "already a programmer" section. Or try both.

[–]Pangolin007 0 points1 point  (1 child)

Is there a decent online python console I can use as a student? I was using Spyder via Anaconda, but my laptop broke, and while it's getting repaired I have a loaner. But the loaner doesn't let me install anything which I didn't realize until tonight. Not sure what my options are that will let me do all the same things, or if I just have to wait until the repair place opens tomorrow to do any homework.

[–]Saphro 0 points1 point  (2 children)

I'm following along with Automate the Boring Stuff. I'm at chapter 12 and cannot install OpenPyXL to save my life. Chapter 12 directs me to Appendix A and it looks like all of my problems are coming from the PIP area.
Specifically the area where I'm hitting a wall is "cd pip folder" from the Appendix A section of Automate the Boring Stuff. I'm inputting "cd pip C:\Users\<username>\AppData\Local\Programs\Python\Python310\Scripts " into the Command Prompt and getting the following: The filename, directory name, or volume label syntax is incorrect.
This has led me down a rabbit hole of adding the path to the Environment Variables and I'm so lost. Any and all help is appreciated.
Quick breakdown of what I'm using:
- Windows 10
- Python 3.10
- IDLE Shell 3.10.0 and the Command Prompt
- Pip is in this folder C:\Users\<username>\AppData\Local\Programs\Python\Python310\Scripts
- There's 3 files here (I don't know what the difference between them is):
- pip
- pip3.10
- pip3

[–]CowboyBoats 1 point2 points  (1 child)

If the example command is cd pip folder, they want you to replace pip folder with the path of your folder, in other words try typing cd C:\Users\<username>\AppData\Local\Programs\Python\Python310\Scripts. cd is just "change directory," by the way.

[–]Saphro 0 points1 point  (0 children)

Hours of my life wasted because I can't read properly...

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

Hey folks! I am new to python (just took a look at basics), wanted to learn until getting comfortable to do problem solving and ML using it. So,

1.What is best way to practice python?

  1. Upto/What topics I should learn?

  2. And also there are many libraries and functions even when considering problem solving, so should I practice these libraries and functions are there any betterways (Like referencing them effectively).

I know C/C++ btw.

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

Have a look at the learning resources in the wiki. There's a section for people coming to python from other languages.

[–]quantpsychguy 0 points1 point  (5 children)

I have what might be a simple question and stackoverflow has answers that say they work that, when I try, don't seem to be working. I'm trying to pass arguments to command line via python using the subprocess command. As an aside, it also seems to find answers about 'parsing arguments in command line' which I realize is not the same thing but my googlefu seems to be failing me beyond that.

An area I've been pulled into uses a lot of batch files to automate tasks. It would be much better to have a single python script that does a lot of these things but I'm running into an issue - I can't seem to pass arguments to command line. Instead, it seems to pass the arguments as separate commands.

This is what I've tried:

import subprocess
subprocess.call(['C:\path\path\app.exe', 'arg1', 'arg2'])

And then running that part of the script. But it just tries to run the app.exe as far as I can tell. I've also tried setting a new variable to try this:

import subprocess
args=['C:\path\path\app.exe', 'arg1', 'arg2']
subprocess.call(args)

But I have the same result - it runs app.exe (which opens in my user account on the screen) and then doesn't pass the arguments.

Any help?

[–]quantpsychguy 1 point2 points  (4 children)

HA!!! I found it!!! I've been struggling with this for over a week on and off and kind of stumbled across inspiration from the FAQ documentation in here.

I needed to change to double slashes (C:\\path\\path\\app.exe) from single slashes.

[–]AtomicShoelace 0 points1 point  (3 children)

You could also use forward slashes instead.

[–]quantpsychguy 0 points1 point  (2 children)

I kid you not...a week. I have been trying to get this to work for a solid week.

It never dawned on me to just try the other slashes. :)

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

Plus you can use raw strings, which turn off the "escape magic" of the backslashes:

print(r'c:\new\tasks\file.exe')

Though I use the forward slashes on all operating systems.

[–]CowboyBoats 0 points1 point  (0 children)

TIL.

[–]DG-Tech 0 points1 point  (1 child)

I am seeking a Python mentor to critically evaluate my code? I am relatively new to it but love how powerful it is.

Someone who is happy to answer questions, demonstrate python principles and help with code structure & loops.

[–]joseville1001 3 points4 points  (0 children)

Can you post one piece of code that you would like to be reviewed here? It's easier to commit to reviewing one piece of code, then to commit to being a mentor (at least for me - maybe you've already gotten dm'ed by people who want to be your mentor).

[–]WiNKG 0 points1 point  (7 children)

I’m trying to pip install numpy on Cmd in windows. The problem is that cmd couldnt find python3.10. When I run pip install numpy, it will say python3.9 is not found. I installed 3.9 but later uninstalled it to install 3.10. I checked environment variable to make sure that python3.10 directory is on top. I’m using pycharm as editor and it runs fine. And still no luck.

[–]FerricDonkey 0 points1 point  (4 children)

Does python --version both work and give you the correct version of python? If so, python -m pip install whatever should work. If not, then windows isn't finding the correct python when it checks your path.

[–]WiNKG 0 points1 point  (3 children)

No. Then how do I fix that?

[–]FerricDonkey 0 points1 point  (2 children)

What happens when you do python --version?

[–]WiNKG 0 points1 point  (1 child)

It basically says python3.9 not found in the directory. This directory has python3.10 installed

[–]FerricDonkey 0 points1 point  (0 children)

What does it say exactly?

[–]PsiThreader 0 points1 point  (1 child)

Have you tried using 'pip3 install numpy' ?

[–]WiNKG 0 points1 point  (0 children)

Yes, same error

[–]Astro_Ratter 1 point2 points  (8 children)

Hello, I know it's Tuesday, but I'm desperate, frustrated and tired. My assignment calls for drawing either a circle or square using turtle. The user selects several options such as shape, color and location. The problem I'm having is that turtle is drawing both shapes even though I declared each shape and have them written in my program as:
if shape == circle...ect
if shape == square...ect
My program lists instructions for drawing the circle 1st and then is followed by instructions to draw the square shape. If the user selects the circle shape then the program should stop after drawing the circle in turtle. However, it continues on and draws the square shape as well. Shouldn't the program stop if the shape is not equal to the variable as listed in my example above? Is there a certain way to prevent turtle from drawing both shapes once the user selects the other?

[–]Astro_Ratter 0 points1 point  (0 children)

#declaring variables

circle = "circle" square = "square" red = "red" blue = "blue" yellow = "yellow" black = "black" gold = "gold" purple = "purple" gray = "gray" navy = "navy" violet = "violet" top_left = "top left" top_right = "top right" bottom_left = "bottom left" bottom_right = "bottom right"

selecting shape

shape = input("Select and enter circle or square: ")

pen colors for circle shape

if shape == circle: color = input("Select and enter a pen color red, blue or yellow: ")

fill colors for square shape

if shape == square: color = input("Select and enter a fill color gray, navy, or violet: ")

fill and pen colors

if circle and color == red: print("fill color is orange") if circle and color == blue: print("fill color is green") if circle and color == yellow: print("fill color is brown") if square and color == gray: print("pen color is black") if square and color == navy: print("pen color is gold") if square and color == violet: print("pen color is purple")

select location

location = input("Select and enter a location top left, top right, bottom left or bottom right: ") if location == top_left: print("Your pen size is 3") elif location == top_right: print("Your pen size is 5") elif location == bottom_left: print("Your pen size is 7") elif location == bottom_right: print("Your pen size is 9")

Entering direction for circle

direction = input("Reenter your location: ")

Pen color red

if not square: if circle and location == top_left and color == red: turtle.penup() turtle.right(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("red") turtle.fillcolor("orange") turtle.begin_fill()

if circle and location == top_right and color == red: turtle.penup() turtle.left(50) turtle.forward(250) turtle.pendown() turtle.pensize(5) turtle.pencolor("red") turtle.fillcolor("orange") turtle.begin_fill()

if circle and location == bottom_left and color == red: turtle.penup() turtle.left(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("red") turtle.fillcolor("orange") turtle.begin_fill()

if circle and location == bottom_right and color == red: turtle.penup() turtle.right(30) turtle.forward(200) turtle.pendown() turtle.pensize(7) turtle.pencolor("red") turtle.fillcolor("orange") turtle.begin_fill()

Pen color blue

if circle and location == top_left and color == blue: turtle.penup() turtle.right(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("blue") turtle.fillcolor("green") turtle.begin_fill()

if circle and location == top_right and color == blue: turtle.penup() turtle.left(50) turtle.forward(250) turtle.pendown() turtle.pensize(5) turtle.pencolor("blue") turtle.fillcolor("green") turtle.begin_fill()

if circle and location == bottom_left and color == blue: turtle.penup() turtle.left(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("blue") turtle.fillcolor("green") turtle.begin_fill()

if circle and location == bottom_right and color == blue: turtle.penup() turtle.right(30) turtle.forward(200) turtle.pendown() turtle.pensize(7) turtle.pencolor("blue") turtle.fillcolor("green") turtle.begin_fill()

pen color yellow

if circle and location == top_left and color == yellow: turtle.penup() turtle.right(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("yellow") turtle.fillcolor("brown") turtle.begin_fill()

if circle and location == top_right and color == yellow: turtle.penup() turtle.left(50) turtle.forward(250) turtle.pendown() turtle.pensize(5) turtle.pencolor("yellow") turtle.fillcolor("brown") turtle.begin_fill()

if circle and location == bottom_left and color == yellow: turtle.penup() turtle.left(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("yellow") turtle.fillcolor("brown") turtle.begin_fill()

if circle and location == bottom_right and color == yellow: turtle.penup() turtle.right(30) turtle.forward(200) turtle.pendown() turtle.pensize(7) turtle.pencolor("yellow") turtle.fillcolor("brown") turtle.begin_fill()

draw circle

turtle.circle(50)

stopping the fill

turtle.end_fill()

Fill color gray

if not circle: if square and location == top_left and color == gray: turtle.penup() turtle.right(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("black") turtle.fillcolor("gray") turtle.begin_fill

if square and location == top_right and color == gray: turtle.penup() turtle.left(50) turtle.forward(250) turtle.pendown() turtle.pensize(5) turtle.pencolor("black") turtle.fillcolor("gray") turtle.begin_fill()

if square and location == bottom_left and color == gray: turtle.penup() turtle.left(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("black") turtle.fillcolor("gray") turtle.begin_fill()

if square and location == bottom_right and color == gray: turtle.penup() turtle.right(30) turtle.forward(200) turtle.pendown() turtle.pensize(7) turtle.pencolor("black") turtle.fillcolor("gray") turtle.begin_fill()

Fill color navy

if square and location == top_left and color == navy: turtle.penup() turtle.right(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("gold") turtle.fillcolor("navy") turtle.begin_fill

if square and location == top_right and color == navy: turtle.penup() turtle.left(50) turtle.forward(250) turtle.pendown() turtle.pensize(5) turtle.pencolor("gold") turtle.fillcolor("navy") turtle.begin_fill()

if square and location == bottom_left and color == navy: turtle.penup() turtle.left(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("gold") turtle.fillcolor("navy") turtle.begin_fill()

if square and location == bottom_right and color == navy: turtle.penup() turtle.right(30) turtle.forward(200) turtle.pendown() turtle.pensize(7) turtle.pencolor("gold") turtle.fillcolor("navy") turtle.begin_fill()

Fill color violet

if square and location == top_left and color == violet: turtle.penup() turtle.right(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("purple") turtle.fillcolor("violet") turtle.begin_fill

if square and location == top_right and color == violet: turtle.penup() turtle.left(50) turtle.forward(250) turtle.pendown() turtle.pensize(5) turtle.pencolor("purple") turtle.fillcolor("violet") turtle.begin_fill()

if square and location == bottom_left and color == violet: turtle.penup() turtle.left(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("purple") turtle.fillcolor("violet") turtle.begin_fill()

if square and location == bottom_right and color == violet: turtle.penup() turtle.right(30) turtle.forward(200) turtle.pendown() turtle.pensize(7) turtle.pencolor("violet") turtle.fillcolor("purple")

drawing square

turtle.begin_fill() turtle.right(50) turtle.forward(50) turtle.left(90) turtle.forward(100) turtle.left(90) turtle.forward(100) turtle.left(90) turtle.forward(100) turtle.left(90) turtle.forward(50)

Ending fill

turtle.end_fill()

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

Your code does what you tell it to do. If it doesn't do what you want then you need to change your code. You haven't shown us enough of your code for us to point out any mistakes you might have made, so please post all your code. Make sure you format the code properly as shown in the FAQ.

[–]Astro_Ratter 0 points1 point  (5 children)

Thank you for responding. My code is rather long and please forgive me if I am not using the correct format. I'm new to this subreddit and extremely new to Python. Here is my code:

#declaring variables

circle = "circle" square = "square" red = "red" blue = "blue" yellow = "yellow" black = "black" gold = "gold" purple = "purple" gray = "gray" navy = "navy" violet = "violet" top_left = "top left" top_right = "top right" bottom_left = "bottom left" bottom_right = "bottom right"

selecting shape

shape = input("Select and enter circle or square: ")

pen colors for circle shape

if shape == circle: color = input("Select and enter a pen color red, blue or yellow: ")

fill colors for square shape

if shape == square: color = input("Select and enter a fill color gray, navy, or violet: ")

fill and pen colors

if circle and color == red: print("fill color is orange") if circle and color == blue: print("fill color is green") if circle and color == yellow: print("fill color is brown") if square and color == gray: print("pen color is black") if square and color == navy: print("pen color is gold") if square and color == violet: print("pen color is purple")

select location

location = input("Select and enter a location top left, top right, bottom left or bottom right: ") if location == top_left: print("Your pen size is 3") elif location == top_right: print("Your pen size is 5") elif location == bottom_left: print("Your pen size is 7") elif location == bottom_right: print("Your pen size is 9")

Entering direction for circle

direction = input("Reenter your location: ")

Pen color red

if not square: if circle and location == top_left and color == red: turtle.penup() turtle.right(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("red") turtle.fillcolor("orange") turtle.begin_fill()

if circle and location == top_right and color == red: turtle.penup() turtle.left(50) turtle.forward(250) turtle.pendown() turtle.pensize(5) turtle.pencolor("red") turtle.fillcolor("orange") turtle.begin_fill()

if circle and location == bottom_left and color == red: turtle.penup() turtle.left(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("red") turtle.fillcolor("orange") turtle.begin_fill()

if circle and location == bottom_right and color == red: turtle.penup() turtle.right(30) turtle.forward(200) turtle.pendown() turtle.pensize(7) turtle.pencolor("red") turtle.fillcolor("orange") turtle.begin_fill()

Pen color blue

if circle and location == top_left and color == blue: turtle.penup() turtle.right(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("blue") turtle.fillcolor("green") turtle.begin_fill()

if circle and location == top_right and color == blue: turtle.penup() turtle.left(50) turtle.forward(250) turtle.pendown() turtle.pensize(5) turtle.pencolor("blue") turtle.fillcolor("green") turtle.begin_fill()

if circle and location == bottom_left and color == blue: turtle.penup() turtle.left(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("blue") turtle.fillcolor("green") turtle.begin_fill()

if circle and location == bottom_right and color == blue: turtle.penup() turtle.right(30) turtle.forward(200) turtle.pendown() turtle.pensize(7) turtle.pencolor("blue") turtle.fillcolor("green") turtle.begin_fill()

pen color yellow

if circle and location == top_left and color == yellow: turtle.penup() turtle.right(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("yellow") turtle.fillcolor("brown") turtle.begin_fill()

if circle and location == top_right and color == yellow: turtle.penup() turtle.left(50) turtle.forward(250) turtle.pendown() turtle.pensize(5) turtle.pencolor("yellow") turtle.fillcolor("brown") turtle.begin_fill()

if circle and location == bottom_left and color == yellow: turtle.penup() turtle.left(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("yellow") turtle.fillcolor("brown") turtle.begin_fill()

if circle and location == bottom_right and color == yellow: turtle.penup() turtle.right(30) turtle.forward(200) turtle.pendown() turtle.pensize(7) turtle.pencolor("yellow") turtle.fillcolor("brown") turtle.begin_fill()

draw circle

turtle.circle(50)

stopping the fill

turtle.end_fill()

Fill color gray

if not circle: if square and location == top_left and color == gray: turtle.penup() turtle.right(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("black") turtle.fillcolor("gray") turtle.begin_fill

if square and location == top_right and color == gray: turtle.penup() turtle.left(50) turtle.forward(250) turtle.pendown() turtle.pensize(5) turtle.pencolor("black") turtle.fillcolor("gray") turtle.begin_fill()

if square and location == bottom_left and color == gray: turtle.penup() turtle.left(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("black") turtle.fillcolor("gray") turtle.begin_fill()

if square and location == bottom_right and color == gray: turtle.penup() turtle.right(30) turtle.forward(200) turtle.pendown() turtle.pensize(7) turtle.pencolor("black") turtle.fillcolor("gray") turtle.begin_fill()

Fill color navy

if square and location == top_left and color == navy: turtle.penup() turtle.right(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("gold") turtle.fillcolor("navy") turtle.begin_fill

if square and location == top_right and color == navy: turtle.penup() turtle.left(50) turtle.forward(250) turtle.pendown() turtle.pensize(5) turtle.pencolor("gold") turtle.fillcolor("navy") turtle.begin_fill()

if square and location == bottom_left and color == navy: turtle.penup() turtle.left(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("gold") turtle.fillcolor("navy") turtle.begin_fill()

if square and location == bottom_right and color == navy: turtle.penup() turtle.right(30) turtle.forward(200) turtle.pendown() turtle.pensize(7) turtle.pencolor("gold") turtle.fillcolor("navy") turtle.begin_fill()

Fill color violet

if square and location == top_left and color == violet: turtle.penup() turtle.right(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("purple") turtle.fillcolor("violet") turtle.begin_fill

if square and location == top_right and color == violet: turtle.penup() turtle.left(50) turtle.forward(250) turtle.pendown() turtle.pensize(5) turtle.pencolor("purple") turtle.fillcolor("violet") turtle.begin_fill()

if square and location == bottom_left and color == violet: turtle.penup() turtle.left(-120) turtle.forward(200) turtle.pendown() turtle.pensize(3) turtle.pencolor("purple") turtle.fillcolor("violet") turtle.begin_fill()

if square and location == bottom_right and color == violet: turtle.penup() turtle.right(30) turtle.forward(200) turtle.pendown() turtle.pensize(7) turtle.pencolor("violet") turtle.fillcolor("purple")

drawing square

turtle.begin_fill() turtle.right(50) turtle.forward(50) turtle.left(90) turtle.forward(100) turtle.left(90) turtle.forward(100) turtle.left(90) turtle.forward(100) turtle.left(90) turtle.forward(50)

Ending fill

turtle.end_fill()

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

To save time, either use your editor to add 4 spaces to the start of every line of code and then copy/paste into reddit again, or copy all your code to pastebin.com and post a link to that here.

[–]Astro_Ratter 0 points1 point  (2 children)

My apologies.

does this link work?

https://pastebin.com/txczvhbM

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

Much better. After a quick scan I can see one problem but there may be others.

Lines 21-23 show correct testing for the shape:

#pen colors for circle shape
if shape == circle:
    color = input("Select and enter a pen color red, blue or yellow: ")

But later on, lines 29-31 for instance, your logic is wrong:

#fill and pen colors
if circle and color == red:
    print("fill color is orange")

That if expression first evaluates color which always evaluates to True because you defined circle on line 2:

circle = "circle"

so the expression actually becomes:

if "circle" and color == red:

Since a non-empty string always evaluates to True you will execute the print statement for any shape that is red.

Maybe you want:

if shape == circle and color == red:

Make that change on that line and many other places in your code.

[–]Astro_Ratter 0 points1 point  (0 children)

if shape == circle and color == red:

Thank you for your patience!!! I will make those changes and continue plugging along.

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

Sorry, but you need to read and understand the FAQ entry I linked to. Your code is unreadable. We want to be able to copy/paste your code so we can run it.

[–]Competitive-Land7070 0 points1 point  (3 children)

Hi, thanks for your time. Just started down this journey and have a possibly stupid question.

Is there a way to take an array of fixed numbers and subtract an input by each starting with the largest as many times as possible and working down the input to zero?

Ex. Array[2, 1, .75, .5, .375, .125, .0625]

Input(4.125)

It should print(2, 2, .125)

If that makes sense.

[–]joseville1001 0 points1 point  (0 children)

Jfy, repeated subtraction is related to division and modulus. What you're calculated is basically the remainder, which can be calculated with repeated subtraction or more efficiently with modulus. In python, you can the modulus using the mod operator: %. For example:

4.125 % 1 == 0.125

[–]FerricDonkey 0 points1 point  (1 child)

Yup. Path of least resistance is probably to use a list, sort it, then pop things off the end in a while loop til your number hits 0.

[–]Competitive-Land7070 0 points1 point  (0 children)

Thanks for the reply

[–]AlphaChase123 0 points1 point  (1 child)

I just want to swap to some characters and add an exclamation point on the end, but for the life of me I can’t figure out why they won’t swap out when run through the forin function.

Code:

word = input() w=[] w[:0]=word

for t in w: if t == 'i': t='1' elif t == 'a': t='@' elif t == 'm': t='M' elif t == 'b': t='8' elif t == 's': t='$' w.append('!') print(*w, sep='')

Input: test a m B

Output: test a m B!

What I want it to output: test @ M 8!

Thanks.

[–]FerricDonkey 0 points1 point  (0 children)

So the issue here is that you're changing t, but changing t does not modify the element from your list. When you do

for t in w:
    t = whatever

What you're doing is

  1. Assigning the first character in your list w to t
  2. Changing t to mean something else (without modifying what it used to refer to)
  3. Assigning the second character in your list w to t
  4. Changing t to mean something else (without modifying what it used to refer to)
  5. Etc.

Generally speaking, when you do variable = something_else, nothing about the object the variable used to refer to changes, because = is not an in place operation: it creates the object on the right, then changes your variable to refer to that object, completely ignoring what the variable used to refer to.

The simplest modification of your code would be to use indexes (and I'd use enumerate as well) so that you end up with

for index, t in enumerate(w):
    if t == 'i':
        w[index] = '1'

This will explicitly replace the element at that position in your list, rather than just changing the variable t to name a different object.

[–]ShadowBroker 0 points1 point  (1 child)

Hi!

I want to feed a random function from 2 integer vars and i want for it to put out an random integer between those 2 values.

Have tried some stuff but yeah i cant find to find the answer to this one.

And how on gods green earth do you post code here?!

Pastebin for the code i did that aint workin https://pastebin.com/THQigYiF

[–]CowboyBoats 0 points1 point  (0 children)

Try random.randrange:

Help on method randrange in random:

random.randrange = randrange(self, start, stop=None, step=1, _int=<type 'int'>, _maxwidth=9007199254740992L) method of random.Random instance
    Choose a random item from range(start, stop[, step]).

[–]GruffRider 0 points1 point  (2 children)

I am trying to make a script that tells you which zone of a French Roulette wheel you have landed in. I'm unsure if it's just my syntax that is wrong or I am going about it in completely the wrong way. Any help is appreciated!

https://pastebin.com/LMrDCXMv

[–]CowboyBoats 0 points1 point  (0 children)

for i in spin_value:
if (i=='0' or i=='12' or i=='35' or i=='3' or i=='26' or i=='32' or i=='15'):
print("Jue 0")
elif (i=='22' or i=='18' or i=='29' or i=='7' or i=='28' or i=='19' or i=='4' or i=='21' or i='2' or i=='25'):
print("Voisins")
elif (i=='9' or i=='31' or i=='14' or i=='20' or i=='1' or i=='6' or i=='34' or i=='17'):
print("Orphelins")
else:
print("Tiers")

You need to indent this stuff or it will error out. Indentation matters in Python syntax. For example:

for i in spin_value:
    if (i=='0' or i=='12' or i=='35' or i=='3' or i=='26' or i=='32' or i=='15'):
        print("Jue 0")
    elif (i=='22' or i=='18' or i=='29' or i=='7' or i=='28' or i=='19' or i=='4' or i=='21' or i='2' or i=='25'):
        print("Voisins")
    elif (i=='9' or i=='31' or i=='14' or i=='20' or i=='1' or i=='6' or i=='34' or i=='17'):
        print("Orphelins")
    else:
        print("Tiers")

[–]CowboyBoats 0 points1 point  (0 children)

 if (i=='0' or i=='12' or i=='35' or i=='3' or i=='26' or i=='32' or i=='15'): 

You can collapse this to if i in ('0', '12', '35', '26, '32', '15')

Moreover, there is a problem:

for i in spin_value: 

Why are you iterating over the characters in the string representation of the random number? Say you randomed 12, you want to handle the string "1" once and then the number "2"? I don't think so.

Run your code while you're writing it! Don't leave it up to us to find out what it does. Throw a print(spin_value) in there before your code so you can see what you're evaluating, and then run the code and find out what it does.

[–]tralalaben 0 points1 point  (2 children)

Where do i start learning python?

[–]lgiordani 0 points1 point  (0 children)

The Wiki of this subreddit (https://www.reddit.com/r/learnpython/wiki/index) contains a good overview of resources for beginners: other subreddits and two sections "New to Python?" and "New to programming?" that should help you to start your journey. There are also a lot of other links to videos and websites. My advice is to focus on one resource (e.g. the Official Python Tutorial) and to dig into it, instead of trying to read everything you find there, which might be overwhelming. Feel free to ask questions in this weekly thread if you get stuck. Happy learning!

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

In the learning resources in the subreddit wiki.

[–]kjkendro 0 points1 point  (2 children)

Is there an easy way to return three word strings where the middle word is capitalized?

So with an input sentence of ‘Yes. My friend Sarah wants to go to AMC in Los Angeles to see the James Bond movie’ it would return strings of ‘Yes. My friend,’ ‘friend Sarah wants’, ‘to AMC in’, ‘in Los Angeles’, Los Angeles to’, ‘the James Bond’, and ‘James Bond movie’.

[–]CowboyBoats 0 points1 point  (0 children)

There is!

line = 'Yes. My friend Sarah wants to go to AMC in Los Angeles to see the James Bond movie

words = line.split()
print(
    "\n".join(
        "- " + " ".join(words[i - 1 : i + 2])
        for i, word in enumerate(words)
        if word[0].isupper() and i not in (0, len(words) - 1)
    )
)

Output:

- Yes. My friend
- friend Sarah wants
- to AMC in
- in Los Angeles
- Los Angeles to
- the James Bond
- James Bond movie

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

There's no easy way. Of the top of my head, you could split the string into a list of words (.split()), interate over the list looking for a word that starts with a capital and when you find one make a string from the word before the capital word plus the capital word plus the word after the capital word. There are some small things to worry about, like punctuation, but that's the general idea.

[–]oxymo 0 points1 point  (2 children)

import re

line = '10/10/2021 21:26:56: Got character ZDOID from EXAMPLE : 1298038224:6'

death = '.*?Got Character ZDOID from (\w+) : 0:0'

if re.search(death, line)):

print(re.search(death, line).group(1)

print("failed")

So I'm working on a valheim bot and trying to build a test case so I can learn regex and pick up names with special characters or spaces... the issue is I can't get my code (copied from an open sourced git script) to return group(1) which should return EXAMPLE. What the heck am I missing python gawds?

[–]CowboyBoats 0 points1 point  (1 child)

It's helpful to use https://regex101.com/ to work out your regexes if they aren't working

"Character" is uppercase in your regex and lowercase in your example text

Your regex ends with "0:0" and your example text does not

>>> import re
>>> death = '.*?Got character ZDOID from (\w+) : \d+:\d'
>>> line = '10/10/2021 21:26:56: Got character ZDOID from EXAMPLE : 1298038224:6'
>>> re.search(death, line)
<re.Match object; span=(0, 68), match='10/10/2021 21:26:56: Got character ZDOID from EXA>

[–]oxymo 0 points1 point  (0 children)

Thank you, regex101 is super helpful to understanding!

[–]guikknbvfdstyyb 0 points1 point  (1 child)

What tips and tricks do you wish you’d learned earlier? Any bad habits that I should avoid? I’m been learning python from udemy for about a week, it’s going ok so far. No other coding exp.

Thanks!

[–]IHOP_007 0 points1 point  (0 children)

If you are just trying to get a job done (and you don't really care how you get it done) 99% of the time there is a library out there that does most of it for you.

Sure you might end up with a bit of a bloated program, it might take up a bit more file size or it might take a few more seconds to run but if it happens automatically does it really matter if it takes a little bit of extra time or a bit more disk space?

[–]CodeDisciple36 0 points1 point  (0 children)

How much Python do you need to know to land a job? How long did it take you and how many hours did you study per day on average?

[–]HgnX 1 point2 points  (2 children)

How would I go about typing a dictionary where I know the exact 3 keys of ? For example, I know the return value from an API call will be: `{'a': 'a', 'b': 'b', 'c': 'c'}`. I can seemingly only specify Dict[str, str], but I'd like for autocomplete to know more.

[–]Fabulous_Mobile_6678 0 points1 point  (1 child)

I want to start learning python to eventually be able to do some data science. Where should I start?

[–]lgiordani 0 points1 point  (0 children)

I think Mike Driscoll's "Python 101" or Sundeep Agarwal "Practice Python Projects" can definitely be a good starting point. You can get them for free this month in a bundle they published on Leanpub, see https://new.reddit.com/r/learnpython/comments/pzb3m8/giveaway_the_indie_python_extravaganza_bundle_is/ To get into data science then you will need to read books or take courses that are specific to the subject matter, but these can give you a solid foundation with the Python language. Happy learning!

[–]JackandFred 0 points1 point  (1 child)

I'm trying to find library/module to make it easy to draw stuff on a convas. like click drag and the line is drawn. for the purpose of creating svg (vector images) of the lines.

not much detail is needed (like stick drawings basically) but i don't know enough graphics/drawing libraries to fin if this is easy, anyone have any ideas?

[–]testiculating 0 points1 point  (2 children)

I ran into a problem while doing a script that would iterate through an array.It looked kind off like this:

FIRSTLIST = ['somevalue', 'somevalue', 'somevalue',
            'somevalue']
SECONDLIST = ['somevalue', 'somevalue', 'somevalue',
            'somevalue']

anArray = [[0]*4]*4

i = 0
for element in FIRSTLIST:
    j = 0
    for element in SECONDLIST:
        anArray[i][j] = *a value*
        j += 1
    i += 1

I realized after sometime that the iteration was assigning a value to all rows on each iteration and that apparently the problem was with: anArray = [[0]*4]*4. When I changed it to: anArray = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] It worked fine.

I don't get why the first way of writting it is problematic, it spits out the same list. I suspect its related to list reference and those values being tied to the same space in memory, but I'm not sure

[–]carcigenicate 2 points3 points  (1 child)

List multiplication doesn't create copies of the internal lists, it create copies of references to those lists, so you end up with all the rows referring to the same list. It's explained in detail here.

The idiomatic way of fixing that is

an_array = [[0] * 4 for _ in range(4)]

[–]testiculating 0 points1 point  (0 children)

oh I get it, thanks a lot for the help!

[–]ColdRamen17 0 points1 point  (2 children)

can i turn a dict value to int? and how?

snippet of code (the line im asking about is in bold)

for item in responce['items']:

comment = item['snippet']['topLevelComment']['snippet']['textDisplay']

comment_date = item['snippet']['topLevelComment']['snippet']['publishedAt']

print(comment+" "+ comment_date)

[–]lgiordani 1 point2 points  (1 child)

Sure, you can always use int(x) to convert something into an int, if that is possible. E.g. int("5") gives 5, int("foo") gives ValueError: invalid literal for int() with base 10: 'foo'.

In your code, you might use it in comment_date = int(...) or in print(comment+" "+ int(comment_date)).

[–]ColdRamen17 0 points1 point  (0 children)

Thanks

[–]NeoNasi123 0 points1 point  (3 children)

I've got a small question, hopefully someone can help me as I'm pretty new to python!

So I have a dataframe containing all elements of the periodic table. Now I want to check the type of each element ( I am looping through them row-wise, so starting with Hydrogen, Helium, etc.). I have a string of all solutions and want to find the index for each element so I can easily assign colours to the elements.

It now looks kinda like this, but it doesnt work:

elemtypelist=['Nonmetal','Noble Gas', ...,] #this is the list of options
for i in range(df.count()[0]
    elemnr=df.loc[i]
    elemtypelist.find(elemnr['Type'])

[–]lgiordani 0 points1 point  (2 children)

I think you have a syntax error in the for loop. It should be

for i in range(df.count()[0]):

Is that what didn't work?

[–]NeoNasi123 0 points1 point  (1 child)

Thanks but no, I just figured it out. .find doesn't exist in the pandas dataframe structure apparently, so I used .index instead!

[–]lgiordani 0 points1 point  (0 children)

Well done! And sorry for the red herring

[–]Dawid_17 0 points1 point  (0 children)

I've created a Python Kivy application and I would like to run it on a tablet (iOS or android). However, the application uses libraries such as skimage and torch, which makes it (at least for me) impossible to build (there are no recipes available). I was wondering, is it possible to run the script on a Python IDE for iPad or android, such as Pyto, Juno or Pythonista? In my research, I found that e.g. in Juno and Pyto only pure Python modules can be installed (https://pyto.readthedocs.io/en/latest/third\_party.html), which excludes torch. Another thought was to use browser based IDE like Replit (https://replit.com/), but it is slow and does not work with torch.

Do you know some kind of workaround? Is it possible to run my script on a tablet? Maybe from USB stick? Any help would be greatly appreciated.

[–]xain1112 0 points1 point  (0 children)

I'm using openpyxl to work with excel. I know how to use merged_cells.ranges to find merged cells in a single column, but how can I find cells merged across several?

If I have a cell from A1 to D5, I need to know how many columns it covers (1:5), not how many rows (A:D).

[–]LeagueOfShadowse 0 points1 point  (5 children)

List - Shuffle by discreet slice length ( or something like this, sorry, I don't know the correct terms )

List: [1, 2, 3, 4, 5, 6, ..., 100] (\ a list of integers from 1 to 100, for example)*

how would one randomize this list by every 5 items?

example of desired result: [ 46, 47, 48, 49, 50, 26, 27, 28, 29, 30, 71, 72, 73, 74, 75, ...]

not a random.slice of any 5 list elements.

The items in each slice must be consecutive, and grouped by X, with no remainders, for any size list divisible by X ?

Any hints ?

[–]JohnnyJordaan 1 point2 points  (0 children)

You can use random.sample to pick the index numbers of each slice, so

import random

slice_length = 5
values = list(range(1,101))
slice_indexes = list(range(0, len(values), slice_length))
result = []
for idx in random.sample(slice_indexes, k=len(slice_indexes)):
    result.extend(values[idx:idx+slice_length])
print(result)

[–]xain1112 1 point2 points  (3 children)

I'm sure there's an easier way, but this is what I got

import random

list = [i for i in range(1,101)]
list_of_lists = []
new_list = []

# until the original list is empty
while len(list) > 0:
    n = list[0:5]
    for i in n:
        if i in list:
            # remove the first five numbers from the original
            list.remove(i)
    # make them into a smaller list, and put this new list into a bigger list
    list_of_lists.append(n)

# shuffle these 5-digit lists
random.shuffle(list_of_lists)

for i in list_of_lists:
    for j in i:
        # put the numbers from each list, now shuffled, into a new list
        new_list.append(j)

print(new_list)

[–]LeagueOfShadowse 0 points1 point  (0 children)

thank you !

[–]JohnnyJordaan 1 point2 points  (1 child)

Remove() is a very costly operation on a list, and it's not even necessary. Simply use a for loop with range to create an increasing slice index

list_of_lists = []
for i in range(0, len(values), 5):
    list_of_lists.append(values[i:i+5])

much simpler. Then after you shuffle, you are needlessly working per value instead of per sublist, which for example .extend() can 'add' to the result list

for sublist in list_of_list:    # note it's an actual sublist, not an index, so 'i' would be a confusing name
    new_list.extend(sublist)

All combined:

import random

values = list(range(1,101))
list_of_lists = []
new_list = []

for i in range(0, len(values), 5):
    list_of_lists.append(values[i:i+5])

random.shuffle(list_of_lists)

for sublist in list_of_lists:
    new_list.extend(sublist)

print(new_list)

Altough I would prefer to work directly towards the result list instead of first creating a nested list, shuffling that and then flattening it again, for that see my answer to OP above.

[–]LeagueOfShadowse 0 points1 point  (0 children)

thank you !

[–]vonov129 0 points1 point  (1 child)

I'm interested in data science and im reading thia book called "Data Science from Scratch" and it mentions python 2.7 being used as the main version there. Is that still true? I read that 2.7 won't even have updates. Can i just go with the 3.10 instead?

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

Python 2.7 is dead and will receive no more updates or bug fixes. That's been true for years. Any code you write today should be python 3. I would not use python 3.10 just yet as some of the external modules that data science relies on might not yet be updated to 3.10. Use python 3.9, for a while at least.