🌐
Annedawson
annedawson.net › pythonprograms.html
Example Python 2 Programs - Dr Anne Dawson
November 6, 2024 - mber to search for: ")) print search found = False for i in range(n): if mylist[i] == search: found = True index = i print if found == True: print str(search) + " found at index " + str(index) else: print str(search) + " not found" # File: bubblesort.py # Purpose: Example: a program which demonstrates a bubble sort on # a list of 10 random integers # Programmer: Anne Dawson import random # define the bubble sort function def sort(values): length = len(values) for time in range(0, length-1): for position in range(0, (length-time-1)): if values[position] > values[position+1]: temp = values[posit
🌐
CodeSandbox
codesandbox.io › examples › package › python2
python2 examples - CodeSandbox
Use this online python2 playground to view and fork python2 example apps and templates on CodeSandbox.
🌐
Learn Python
learnpython.org › en › Hello,_World!
Hello, World! - Learn Python - Free Interactive Python Tutorial
In Python 2, the "print" statement is not a function, and therefore it is invoked without parentheses. However, in Python 3, it is a function, and must be invoked with parentheses. ... Python uses indentation for blocks, instead of curly braces. Both tabs and spaces are supported, but the standard indentation requires standard Python code to use four spaces. For example:
🌐
Python documentation
docs.python.org › 3 › tutorial › introduction.html
3. An Informal Introduction to Python — Python 3.14.3 documentation
In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example: >>> tax = 12.5 / 100 >>> price = 100.50 >>> price * tax 12.5625 >>> price + _ 113.0625 >>> round(_, 2) 113.06
🌐
Instructables
instructables.com › design › software
Python Programming Tutorial (Python 2.7) : 17 Steps - Instructables
October 18, 2017 - It is also possible to have some piece of code executed only if the condition was false, take the following example: number =int(raw_input("Please enter a number:")) if number <10: print"Your number was less than 10!"else: print"Your number was 10 or greater!" Ok, now you might think "Slow down Sorunome, why did you write 10 or greater?". Well, that's pretty simple. Let's say you entered 10 as your number, Python ...
🌐
Programiz
programiz.com › python-programming › examples
Python Examples | Programiz
This page contains examples of basic concepts of Python programming like loops, functions, native datatypes and so on.
🌐
Python
wiki.python.org › moin › SimplePrograms
SimplePrograms - Python Wiki
prices = {'apple': 0.40, 'banana': 0.50} my_purchase = { 'apple': 1, 'banana': 6} grocery_bill = sum(prices[fruit] * my_purchase[fruit] for fruit in my_purchase) print (f'I owe the grocer ${grocery_bill:.2f}') 8 lines: Command line arguments, exception handling · # This program adds up integers ...
🌐
PythonForBeginners
pythonforbeginners.com › home › python 2 vs python 3 with examples
Python 2 Vs Python 3 with Examples - PythonForBeginners.com
June 6, 2020 - In the console screenshot below, raising error does not work in Python 3 as it was in Python 2. With exception handlers, the syntax has changed slightly in Python 3. In the console screenshot below, we specify a try block with an exception handler. We purposely cause an error by specifying an undefined name in the ‘try’. In the console screenshot below, we specify the same code as the previous example in Python 2.
🌐
IPython
ipython.readthedocs.io › en › 4.x › development › pycompat.html
Writing code for Python 2 and 3 — IPython 4.2.1 documentation
Return the current working directory as unicode, like os.getcwdu() on Python 2. ... Constructor for types.MethodType that takes two arguments, like the real constructor on Python 3.
Find elsewhere
Top answer
1 of 6
16

There is official documentation suggesting ways to do this. That documentation has changed over time as the situation has changed, so it's worth going directly to the source (especially if you're reading this answer a year or two after it was written).

It's also worth reading the Conservative Python 3 Porting Guide and skimming Nick Coghlan's Python 3 Q&A, especially this section.

Going back in time from the early 2018:

futurize

The current official suggestions are:

  • Only worry about supporting Python 2.7
  • Make sure you have good test coverage (coverage.py can help; pip install coverage)
  • Learn the differences between Python 2 & 3
  • Use Futurize (or Modernize) to update your code (e.g. pip install future)
  • Use Pylint to help make sure you don’t regress on your Python 3 support (pip install pylint)
  • Use caniusepython3 to find out which of your dependencies are blocking your use of Python 3 (pip install caniusepython3)
  • Once your dependencies are no longer blocking you, use continuous integration to make sure you stay compatible with Python 2 & 3 (tox can help test against multiple versions of Python; pip install tox)
  • Consider using optional static type checking to make sure your type usage works in both Python 2 & 3 (e.g. use mypy to check your typing under both Python 2 & Python 3).

Notice the last suggestion. Guido and another of the core devs have both been heavily involved in leading large teams to port large 2.7 codebases to 3.x, and found mypy to be very helpful (especially in dealing with bytes-vs.-unicode issues). In fact, that's a large part of the reason gradual static typing is now an official part of the language.

You also almost certainly want to use all of the future statements available in 2.7. This is so obvious that they seem to have forgotten to leave it out of the docs, but, besides making your life easier (e.g., you can write print function calls), futurize and modernize (and six and sixer) require it.

six

The documentation is aimed at people making an irreversible transition to Python 3 in the near future. If you're planning to stick with dual-version code for a long time, you might be better off following the previous recommendations, which largely revolved around using six instead of futurize. Six covers more of the differences between the two languages, and also makes you write code that's explicit about being dual-version instead of being as close to Python 3 as possible while still running in 2.7. But the downside is that you're effectively doing two ports—one from 2.7 to six-based dual-version code, and then, later, from 3.x-only six code to 3.x-only "native" code.

2to3

The original recommended answer was to use 2to3, a tool that can automatically convert Python 2 code to Python 3 code, or guide you in doing so. If you want your code to work in both, you need to deliver Python 2 code, then run 2to3 at installation time to port it to Python 3. Which means you need to test your code both ways, and usually modify it so that it still works in 2.7 but also works in 3.x after 2to3, which isn't always easy to work out. This turns out to not be feasible for most non-trivial projects, so it's no longer recommended by the core devs—but it is still built in with Python 2.7 and 3.x, and getting updates.

There are also two variations on 2to3: sixer auto-ports your Python 2.7 code to dual-version code that uses six, and 3to2 lets you write your code for Python 3 and auto-port back to 2.7 at install time. Both of these were popular for a time, but don't seem to be used much anymore; modernize and futurize, respectively, are their main successors.


For your specific question,

  • kwargs.items() will work on both, if you don't mind a minor performance cost in 2.7.
  • 2to3 can automatically change that iteritems to items at install time on 3.x.
  • futurize can be used to do either of the above.
  • six will allow you to write six.iteritems(kwargs), which will do iteritems in 2.7 and items in 3.x.
  • six will also allow you to write six.viewitems(kwargs), which will do viewitems in 2.7 (which is identical to what items does in 3.x, rather than just similar).
  • modernize and sixer will automatically change that kwargs.iteritems() to six.iteritems(kwargs).
  • 3to2 will let you write kwargs.items() and autmatically convert it to viewitems at install time on 2.x.
  • mypy can verify that you're just using the result as a general iterable (rather than specifically as an iterator), so changing to viewitems or items leaves your code still correctly typed.
2 of 6
3

you can import the future package

from future import ....

nested_scopes 2.1.0b1 2.2 PEP 227: Statically Nested Scopes

generators 2.2.0a1 2.3 PEP 255: Simple Generators

division 2.2.0a2 3.0 PEP 238: Changing the Division Operator

absolute_import 2.5.0a1 3.0 PEP 328: Imports: Multi-Line and Absolute/Relative

with_statement 2.5.0a1 2.6 PEP 343: The “with” Statement

print_function 2.6.0a2 3.0 PEP 3105: Make print a function

unicode_literals 2.6.0a2 3.0 PEP 3112: Bytes literals in Python 3000

🌐
Memphis
ceri.memphis.edu › people › egdaub › datanotes › _build › html › python2.html
Basic Programming with Python 2 — Course Notes for Data Analysis in Geophysics 1.0 documentation
def square(x): 'returns the square of input number x' return x*x def doTwice(x, f): 'applies a function f taking a single argument to input x twice' return f(f(x)) print doTwice(2, square) # prints 16 = (2**2)**2 · This is a very powerful tool, as you can create functions where the functions ...
🌐
freeCodeCamp
freecodecamp.org › news › python-code-examples-sample-script-coding-tutorial-for-beginners
Python Code Example Handbook – Sample Script Coding Tutorial for Beginners
April 27, 2021 - They are associated to the character at that position. ... >>> my_string = "Hello" >>> my_string[0] 'H' >>> my_string[1] 'e' >>> my_string[2] 'l' >>> my_string[3] 'l' >>> my_string[4] 'o'
🌐
Majdarbash
majdarbash.github.io › python-2.7 › 3-python-built-in-functions-examples
Python 2.7: Built-in Functions, Examples :: My New Hugo Site
from random import randint random_number = randint(0, 12) # output: a random number between 0 and 12 print rand_number ### Sum of digits in a number def digit_sum(n): total = 0 while n != 0: number = n % 10 n = int(n / 10) total = total + number return total # output: 10 = 1+2+3+4 print ...
🌐
Python
docs.python.org › 2 › tutorial
The Python Tutorial — Python 2.7.18 documentation
This tutorial introduces the reader informally to the basic concepts and features of the Python language and system. It helps to have a Python interpreter handy for hands-on experience, but all examples are self-contained, so the tutorial can be read off-line as well.
🌐
Python documentation
docs.python.org › 3 › tutorial › index.html
The Python Tutorial — Python 3.14.3 documentation
This tutorial introduces the reader informally to the basic concepts and features of the Python language and system. Be aware that it expects you to have a basic understanding of programming in general. It helps to have a Python interpreter handy for hands-on experience, but all examples are self-contained, so the tutorial can be read off-line as well.
🌐
Python-future
python-future.org › compatible_idioms.html
Cheat Sheet: Writing Python 2-3 compatible code — Python-Future documentation
# Python 2 only s1 = 'The Zen of Python' s2 = u'きたないのよりきれいな方がいい\n' # Python 2 and 3 s1 = u'The Zen of Python' s2 = u'きたないのよりきれいな方がいい\n' The futurize and python-modernize tools do not currently offer an option to do this automatically. If you are writing code for a new project or new codebase, you can use this idiom to make all string literals in a module unicode strings:
🌐
Tomroelandts
tomroelandts.com › articles › one-code-to-run-them-all-python-2-and-python-3
One Code to Run Them All (Python 2 and Python 3) | TomRoelandts.com
January 26, 2019 - # Executed in Python 3: >>> print(1 / 2, 3 / 4) 0.5 0.75 · Personally, I think that the best way to write “unified code” is the “borrow from the future” approach.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-programming-examples
Python Programs - Python Programming Example - GeeksforGeeks
September 25, 2025 - The below Python section contains a wide collection of Python programming examples. These Python code examples cover a wide range of basic concepts in the Python language, including List, Strings, Dictionary, Tuple, sets, and many more.
🌐
Python
python.org › download › releases › 2.0
Python 2.0 | Python.org
The readline section of the library reference manual contains an example. ... SimpleHTTPServer, CGIHTTPServer - Fix problems with buffering in the HTTP server. ... None. However note that 1.6 made a whole slew of modules obsolete: stdwin, soundex, cml, cmpcache, dircache, dump, find, grep, packmail, poly, zmod, strop, util, whatsound. ... Several cleanup jobs were carried out throughout the source code.
🌐
Codecademy
codecademy.com › learn › learn-python
Learn Python 2 | Codecademy
I love how Codecademy uses learning by practice and gives great challenges to help the learner to understand a new concept and subject. ... Brilliant learning experience. Very interactive. Literally a game changer if you're learning on your own. ... Learn Python syntax with this beginner-friendly guide. Understand Python indentation, print statements, variables, comments, user input, and more with examples...
Rating: 4.3 ​ - ​ 7.62K votes