You can usually easily and safely do copy-pasting with IPython, through the commands %cpaste (manually ending code with --) and %paste (execute code immediately). This is very handy for testing code that you copy from web pages, for instance, or from your editor: these commands even strip leading prompts (like In[1] and ...) for you.

IPython also has a %run command that runs a program and leaves you in a Python shell with all the variables that were defined in the program, so that you can play with them.

In order to get help on these functions: %cpaste?, etc.

Answer from Eric O. Lebigot on Stack Overflow
🌐
Python
wiki.python.org › moin › SimplePrograms
SimplePrograms - Python Wiki
>>> median([2, 9, 9, 7, 9, 2, 4, 5, 8]) 6 #change to 7 in order to pass the test ''' copy = sorted(pool) size = len(copy) if size % 2 == 1: return copy[int((size - 1) / 2)] else: return (copy[int(size/2 - 1)] + copy[int(size/2)]) / 2 if __name__ == '__main__': import doctest doctest.testmod() ...
🌐
GitHub
gist.github.com › yohanesgultom › 630a831eff1fbdcd84b3cfec6feabe02
Random python scripts · GitHub
I just was bored and I feel inspired by this https://craft.js.org/docs/overview#extensible ... from __future__ import annotations import copy import ctypes import uuid from typing import Any, Callable # ============================== # react.py ...
Discussions

Copying and pasting code directly into the Python interpreter - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Save this question. Show activity on this post. There is a snippet of code that I would like to copy and paste into my Python interpreter. Unfortunately due to Python's sensitivity to whitespace ... More on stackoverflow.com
🌐 stackoverflow.com
Share the code you're most proud of!
It's not my most favourite but it can be handy now and again from __future__ import print_function import time class timer(object): def __init__(self, func=print): self.func = func def __enter__(self): self.time = time.time() def __exit__(self, type, value, traceback): total_time = time.time() - self.time self.func(total_time) If you want to know how long some code takes to run just use with timer(): # do something and it will print out how long it took to finish whatever it was that you wanted to do. It can also take in a function as an argument time_taken = [] for i in range(1000000): with timer(time_taken.append) # do something this will add the amount of time taken each time to a list and the average time can be obtained in a similar fashion to timeit. EDIT: Added time and print_function imports as suggested below. Also this should really only be used for rough timings or where what is being timed takes milliseconds and longer to compute to account for the extra overheads involved More on reddit.com
🌐 r/Python
264
181
March 20, 2014
image - "copy and paste" python program - Stack Overflow
I'm currently trying to write a program that reads a GIF file, displays its image on the screen, then allows the user to select a rectangular portion of the image to "copy and paste", AKA to then c... More on stackoverflow.com
🌐 stackoverflow.com
Copy and Paste Files - Command
Good night people, I have a problem, I used the following code to copy and paste files from one folder to another import os import time import shutil origem = r"C:\Program Files\Corel\CorelDRAW Graphics Suite 2022\Programs64\Pasta2" destino = r"C:\Program Files\Corel\CorelDRAW Graphics Suite ... More on discuss.python.org
🌐 discuss.python.org
3
0
June 24, 2024
🌐
GitHub
gist.github.com › sanchitgangwar › 2158089
Snakes Game using Python · GitHub
Snakes Game using Python. GitHub Gist: instantly share code, notes, and snippets.
🌐
Reddit
reddit.com › r/python › share the code you're most proud of!
r/Python on Reddit: Share the code you're most proud of!
March 20, 2014 -

Well all know that sense of awesome when you write a neat, concise chunk of code that does something really cool. Take the code in the sidebar for example:

def fibonacci():
    a, b = 0, 1
    while 1:
        yield a
        a, b = b, a + b

It's just a thought, but if you have a moment why not share your favorite snippet of code, along with a brief explanation? It must be under 10 lines, but anything else goes. Post away!

Top answer
1 of 5
96
It's not my most favourite but it can be handy now and again from __future__ import print_function import time class timer(object): def __init__(self, func=print): self.func = func def __enter__(self): self.time = time.time() def __exit__(self, type, value, traceback): total_time = time.time() - self.time self.func(total_time) If you want to know how long some code takes to run just use with timer(): # do something and it will print out how long it took to finish whatever it was that you wanted to do. It can also take in a function as an argument time_taken = [] for i in range(1000000): with timer(time_taken.append) # do something this will add the amount of time taken each time to a list and the average time can be obtained in a similar fashion to timeit. EDIT: Added time and print_function imports as suggested below. Also this should really only be used for rough timings or where what is being timed takes milliseconds and longer to compute to account for the extra overheads involved
2 of 5
68
Generating all valid clauses of a CFG specified as BNF from itertools import chain, product from re import match, findall GRAMMAR = ''' ::= ::= "boy " | "troll " | "moon " | "telescope " ::= "hits " | "sees " ::= "runs " | "sleeps " ::= "big " | "red " ::= "quickly " | "quietly " ::= "a " | "that " | "each " | "every " ::= "he " | "she " | "it " ::= | ::= | ''' def parse(g): return dict([(w.strip(), [findall(r'(<.+?>|".+?")', s) for s in m.split('|')]) for w, m in [d.split('::=') for d in g.strip().splitlines()]]) def generate(term): return findall(r'"(.*?)"', term) if match('".*', term) else chain(*[map(''.join, product(*map(generate, p))) for p in syntax[term]]) syntax = parse(GRAMMAR) print list(generate(''))
🌐
Java Code Geeks
javacodegeeks.com › home › web development › python
Explore These 20 Cool Python Scripts for Fun and Productivity! - Java Code Geeks
January 17, 2024 - Explore a collection of versatile Cool Python scripts, from web scraping to machine learning and web development.
Top answer
1 of 2
2

The main problem with your code is that you create a new PhotoImage for each pixel! Instead, create the PhotoImage once and just add the pixels in the double-for-loop.

def box(event):
    yaxis(event)
    canvas.create_rectangle(x1, y1, x2, y2)

    picture = PhotoImage(width=(x2-x1), height=(y2-y1))
    for x in range(x1, x2):
        for y in range(y1, y2):
            r, g, b = photo.get(x, y)
            picture.put("#%02x%02x%02x" % (r, g, b), (x-x1, y-y1))
    picture.write('new_image.gif', format='gif')

Also, the line tuple(map(int, value.split(" "))) in your getRGB function is wrong, as value is already the tuple you want to create, not a string.1) As you can see, I just 'inlined' that part directly into the box function. Another problem was that you wrote the copied pixels to x and y, but you have to write them to x-x1 and y-y1 instead.

Update 1: 1) It seems like the return value of PhotoImage.get depends on the version of Python/Tkinter you are using. In some versions, it returns a tuple, like (41, 68, 151), and in others, a string, like u'41 68 151'.

Update 2: As pointed out by @Oblivion, you can in fact just use the from_coords parameter of PhotoImage.write to specify the region of the picture to be saved to file. With this, the box function can be simplified as

def box(event):
    yaxis(event)
    canvas.create_rectangle(x1, y1, x2, y2)
    photo.write('new_image.gif', format='gif', from_coords=[x1, y1, x2, y2])
2 of 2
0
import tkinter
from tkinter import *
import base64

root = Tk()

def action(canvas):
    canvas.bind("<Button-1>", xaxis)
    canvas.bind("<ButtonRelease-1>", yaxis)
    canvas.bind("<ButtonRelease-1>", box)

def xaxis(event):
    global x1, y1
    x1, y1 = (event.x - 1), (event.y - 1)
    print (x1, y1)

def yaxis(event):
    global x2, y2
    x2, y2 = (event.x + 1), (event.y + 1)
    print (x2, y2)

def box(event, photo):
    x1, y1 = (event.x - 1), (event.y - 1)
    x2, y2 = (event.x + 1), (event.y + 1)
    canvas.create_rectangle(x1, y1, x2, y2)
    new_photo = copy_photo(photo, x1, y1, x2, y2)
    new_photo.write('new_image.gif', format='gif')

def copy_photo(photo, x1, y1, x2, y2):
    new_photo = PhotoImage(width=photo.width(), height=photo.height())
    for x in range(photo.width()):
        for y in range(photo.height()):
            if x1 <= x < x2 and y1 <= y < y2:
                r,g,b = getRGB(photo, x, y)
                new_photo.put("#%02x%02x%02x" % (r,g,b), (x,y))
            else:
                new_photo.put(photo.get(x, y), (x,y))
    return new_photo

def getRGB(photo, x, y):
    value = photo.get(x, y)
    return tuple(map(int, value.split(" ")))

canvas = Canvas(width=500, height=250)
canvas.pack(expand=YES, fill=BOTH)
photo = PhotoImage(file="picture.gif")
canvas.create_image(0, 0, image=photo, anchor=NW)
canvas.config(cursor='cross')
action(canvas)

enter code here

canvas.mainloop()
Find elsewhere
🌐
CodeRivers
coderivers.org › blog › text-code-to-copy-and-paste-into-python
Working with Text Code to Copy and Paste into Python - CodeRivers
February 22, 2026 - Just open the relevant Python file, place the cursor where you want to insert the code, and paste it. IDEs often have features to help with code formatting and error detection. Indentation: Python uses indentation to define code blocks. When copying and pasting code, make sure the indentation is correct.
🌐
King Ice Apps
apps.kingice.com › home › new › text code to copy and paste into python
Text Code To Copy And Paste Into Python - All In One
May 5, 2026 - Explore the Text Code To Copy And Paste Into Python—ready‑to‑use snippets you can drop straight into your IDE. Each example explains its purpose, shows integration steps, and boosts efficiency for beginners and seasoned developers alike.
🌐
Backlinkworks
blogs.backlinkworks.com › home › 10 insanely cool python codes you’ll want to copy and paste right away!
10 Insanely Cool Python Codes You'll Want to Copy and Paste Right Away! - Topics on SEO & Backlinks
February 6, 2024 - Python is an incredibly versatile ... among both new and experienced developers. In this article, we’ll explore 10 insanely cool Python codes that you’ll want to copy and paste right away to enhance your projects....
🌐
Medium
medium.com › @zhongwei2049 › 8-delightful-python-scripts-to-brighten-your-day-5908c1761905
8 Delightful Python Scripts to Brighten Your Day | by Zhongwei | Medium
July 30, 2023 - This fun script helps you test internet speed using Python. Just install the speedtest module and run the code. # pip install pyspeedtest # pip install speedtest # pip install speedtest-cli #method 1 import speedtest speedTest = speedtest.Speedtest() print(speedTest.get_best_server()) #Check download speed print(speedTest.download()) #Check upload speed print(speedTest.upload()) # Method 2 import pyspeedtest st = pyspeedtest.SpeedTest() st.ping() st.download() st.upload()
🌐
Python.org
discuss.python.org › python help
Copy and Paste Files - Command - Python Help - Discussions on Python.org
June 24, 2024 - Good night people, I have a problem, I used the following code to copy and paste files from one folder to another import os import time import shutil origem = r"C:\Program Files\Corel\CorelDRAW Graphics Suite 2022\Programs64\Pasta2" destino = r"C:\Program Files\Corel\CorelDRAW Graphics Suite 2022\Programs64\Pasta1" def copy_files(origem, destino): os.makedirs(destino, exist_ok=True) for item in os.listdir(origem): origem_arquivo = os.path.join(origem, item) destino_ar...
🌐
Anirudh Jayaraman
pythonandr.com › 2015 › 05 › 16 › code-for-my-first-text-based-game
Code for my First Text-Based Game – Anirudh Jayaraman
July 6, 2015 - You shall be lost forever into the infinite abyss of the tree of the undead." exit(0) def start(): print "You are walking through an enchanted forest with gigantic trees as tall as mountains and as thick as large lakes." print "You got here magically teleported into a distant planet in a distant galaxy in the future." print "You see one such tree with a cave-like structure at its base. What do you do?" do_what = raw_input("> ") while True: if "cave" in do_what or "cave-like" in do_what or "enter" in do_what: print "You enter the dark hollow of an ancient tree that has had earthlings like you in the past." print "This tree is called the tree of the undying, where death won't touch you." print "On the other hand, pain can - if you don't make the right moves.
🌐
W3Schools
w3schools.com › python › python_lists_copy.asp
Python - Copy Lists
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.
🌐
OneCompiler
onecompiler.com › python › 3wsj7ajyg
Python Online Compiler & Interpreter
Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast.
🌐
Python Morsels
pythonmorsels.com › paste
Share Python Code – a runnable Pastebin
Scripts only show what they print; unlike a REPL, bare expressions aren't echoed. Ctrl+Enter runs; Ctrl+S saves. Both work while typing in the editor (use ⌘ on a Mac). curl gets just the code. Using curl -L to access a paste's URL returns the raw Python file, not a web page.
🌐
Grant Jenks
grantjenks.com › docs › freegames
Free Python Games — Free Python Games 2.5.3 documentation
$ python3 -m freegames copy snake $ python3 snake.py · Python includes a built-in text editor named IDLE which can also execute Python code. To launch the editor and make changes to the “snake” game run:
🌐
Backlinkworks
blogs.backlinkworks.com › home › copy and paste your way to a fun python game with this simple code!
Copy and Paste Your Way to a Fun Python Game with This Simple Code! - Topics on SEO & Backlinks
November 8, 2023 - Simply copy and paste the above code into a Python IDE or text editor, and you’ll have a working Rock, Paper, Scissors game ready to go!
🌐
Hackr
hackr.io › home › articles › projects
Top 40 Python Projects for Programmers (Beginner to Advanced)
February 19, 2026 - A Python URL shortener project combines functionality with a polished GUI. Using PyQt5 for the interface and pyshorteners for URL generation, you’ll create an app that shortens long URLs and copies them to the clipboard.