We’re rewarding the question askers & reputations are being recalculated! Read more.

Questions tagged [python-3.x]

For questions about Python programming that are specific to version 3+ of the language. Use the more generic [python] tag if your question is not version-specific. Use the [python-2.x] tags for Python 2 questions.

Filter by
Sorted by
Tagged with
522
votes
18answers
410k views

Asking the user for input until they give a valid response

I am writing a program that must accept input from the user. #note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input` age = int(input("Please enter your age: ")) if age >= ...
261
votes
10answers
759k views

How can I read inputs as numbers?

Why are x and y strings instead of ints in the below code? (Note: in Python 2.x use raw_input(). In Python 3.x use input(). raw_input() was renamed to input() in Python 3.x) play = True while play: ...
260
votes
3answers
222k views

Syntax error on print with Python 3 [duplicate]

Why do I receive a syntax error when printing a string in Python 3? >>> print "hello World" File "<stdin>", line 1 print "hello World" ^ SyntaxError: ...
247
votes
16answers
75k views

Does Python have a built in function for string natural sort?

Using Python 3.x, I have a list of strings for which I would like to perform a natural alphabetical sort. Natural sort: The order by which files in Windows are sorted. For instance, the following ...
382
votes
4answers
82k views

Are dictionaries ordered in Python 3.6+?

Dictionaries are ordered in Python 3.6 (under the CPython implementation at least) unlike in previous incarnations. This seems like a substantial change, but it's only a short paragraph in the ...
78
votes
3answers
110k views

Switch between two frames in tkinter

I have built my first few scripts with a nice little GUI on them, as the tutorials have shown me, but none of them address what to do for a more complex program. If you have something with a 'start ...
342
votes
6answers
303k views

What's the difference between raw_input() and input() in python3.x?

What is the difference between raw_input() and input() in python3.x ?
1105
votes
13answers
713k views

How to flush output of print function?

How do I force Python's print function to output to the screen? This is not a duplicate of Disable output buffering - the linked question is attempting unbuffered output, while this is more general. ...
151
votes
5answers
16k views

Accessing class variables from a list comprehension in the class definition

How do you access other class variables from a list comprehension within the class definition? The following works in Python 2 but fails in Python 3: class Foo: x = 5 y = [x for i in range(1)...
1146
votes
43answers
798k views

How can I represent an 'Enum' in Python?

I'm mainly a C# developer, but I'm currently working on a project in Python. How can I represent the equivalent of an Enum in Python?
1936
votes
18answers
2.0m views

Convert bytes to a string

I'm using this code to get standard output from an external program: >>> from subprocess import * >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] The ...
728
votes
18answers
518k views

How to copy a dictionary and only edit the copy

Can someone please explain this to me? This doesn't make any sense to me. I copy a dictionary into another and edit the second and both are changed. Why is this happening? >>> dict1 = {"...
376
votes
7answers
697k views

What does “SyntaxError: Missing parentheses in call to 'print'” mean in Python?

When I try to use a print statement in Python, it gives me this error: >>> print "Hello, World!" File "<stdin>", line 1 print "Hello, World!" ^ ...
459
votes
8answers
230k views

What is the best way to remove accents in a Python unicode string?

I have a Unicode string in Python, and I would like to remove all the accents (diacritics). I found on the Web an elegant way to do this in Java: convert the Unicode string to its long normalized ...
9
votes
3answers
6k views

How can I reconnect to the browser opened by webdriver with selenium?

For some unknown reasons ,my browser open test pages of my remote server very slowly. So I am thinking if I can reconnect to the browser after quitting the script but don't execute webdriver.quit() ...
142
votes
14answers
218k views

How to pass arguments to a Button command in Tkinter?

Suppose I have the following Button made with Tkinter in Python: import Tkinter as Tk win = Tk.Toplevel() frame = Tk.Frame(master=win).grid(row=1, column=1) button = Tk.Button(master=frame, text='...
579
votes
9answers
373k views

Relative imports in Python 3

I want to import a function from another file in the same directory. Sometimes it works for me with from .mymodule import myfunction but sometimes I get a: SystemError: Parent module '' not loaded, ...
216
votes
3answers
91k views

What are type hints in Python 3.5?

One of the most talked about features in Python 3.5 is type hints. An example of type hints is mentioned in this article and this one while also mentioning to use type hints responsibly. Can someone ...
101
votes
10answers
75k views

Understanding Python's “is” operator

The is operator does not match the values of the variables, but the instances themselves. What does it really mean? I declared two variables named x and y assigning the same values in both ...
477
votes
8answers
370k views

Getting a map() to return a list in Python 3.x

I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy: A: Python 2.6: >>> map(chr, [66, 53, 0, 94]) ['B', '5', '\x00', '^'] However, in Python 3....
176
votes
13answers
518k views

How to search and replace text in a file?

How do I search and replace text in a file using Python 3? Here is my code: import os import sys import fileinput print ("Text to search for:") textToSearch = input( "> " ) print ("Text to ...
507
votes
21answers
1.2m views

How to install pip with Python 3?

I want to install pip. It should support Python 3, but it requires setuptools, which is available only for Python 2. How can I install pip with Python 3?
723
votes
3answers
1.1m views

Best way to convert string to bytes in Python 3?

There appears to be two different ways to convert a string to bytes, as seen in the answers to TypeError: 'str' does not support the buffer interface Which of these methods would be better or ...
178
votes
22answers
548k views

Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

I've installed Python 3.5 and while running pip install mysql-python it gives me the following error error: Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat) I have added the ...
325
votes
11answers
236k views

What is an alternative to execfile in Python 3?

It seems they canceled in Python 3 all the easy way to quickly load a script by removing execfile() Is there an obvious alternative I'm missing?
519
votes
7answers
821k views

How do I use raw_input in Python 3

import sys print(sys.platform) print(2**100) raw_input() I am using Python 3.1 and can't get the raw_input to "freeze" the dos pop-up. The book I'm reading is for Python 2.5 and I'm using Python 3.1 ...
444
votes
6answers
501k views

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

I'm trying to get a Python 3 program to do some manipulations with a text file filled with information. However, when trying to read the file I get the following error: Traceback (most recent call ...
157
votes
8answers
46k views

Python 3.x rounding behavior

I was just re-reading What’s New In Python 3.0 and it states: The round() function rounding strategy and return type have changed. Exact halfway cases are now rounded to the nearest even result ...
242
votes
11answers
274k views

Using both Python 2.x and Python 3.x in IPython Notebook

I use IPython notebooks and would like to be able to select to create a 2.x or 3.x python notebook in IPython. I initially had Anaconda. With Anaconda a global environment variable had to be changed ...
737
votes
11answers
436k views

Should I put #! (shebang) in Python scripts, and what form should it take?

Should I put the shebang in my Python scripts? In what form? #!/usr/bin/env python or #!/usr/local/bin/python Are these equally portable? Which form is used most? Note: the tornado project uses ...
60
votes
4answers
76k views

How can I concatenate str and int objects?

If I try to do the following: things = 5 print("You have " + things + " things.") I get the following error in Python 3.x: Traceback (most recent call last): File "<stdin>", line 1, in <...
223
votes
10answers
468k views

“Unicode Error ”unicodeescape" codec can't decode bytes… Cannot open text files in Python 3

I am using python 3.1, on a windows 7 machines. Russian is the default system language, and utf-8 is the default encoding. Looking at the answer to a previous question, I have attempting using the "...
268
votes
4answers
35k views

How do I specify that the return type of a method is the same as the class itself?

I have the following code in python 3: class Position: def __init__(self, x: int, y: int): self.x = x self.y = y def __add__(self, other: Position) -> Position: ...
1872
votes
9answers
173k views

Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?

It is my understanding that the range() function, which is actually an object type in Python 3, generates its contents on the fly, similar to a generator. This being the case, I would have expected ...
210
votes
4answers
151k views

Python integer division yields float

Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 2/2 1.0 Is this intended? I ...
10
votes
1answer
3k views

Replace values in a pandas series via dictionary efficiently

How to replace values in a Pandas series s via a dictionary d has been asked and re-asked many times. The recommended method (1, 2, 3, 4) is to either use s.replace(d) or, occasionally, use s.map(d) ...
13
votes
3answers
40k views

error in python d not defined. [duplicate]

I am learning python and have this error . I can figure out where\what the error is in the code. File "<string>", line 1, in <module>. Name = "" Desc = "" Gender = "" Race = "" # Prompt ...
156
votes
4answers
103k views

Changes in import statement python3

I don't understand the following from pep-0404 In Python 3, implicit relative imports within packages are no longer available - only absolute imports and explicit relative imports are supported....
11
votes
2answers
4k views

Nested List Indices [duplicate]

I have experienced some problem by using a nested list in Python in the code shown bleow. Basically, I have a 2D list contains all 0 values, I want to update the list value in a loop. However, ...
97
votes
6answers
287k views

How can I convert a .py to .exe for Python?

I'm trying to convert a fairly simple Python program to an executable and couldn't find what I was looking for, so I have a few questions (I'm running Python3.6): The methods of doing this that I ...
21
votes
6answers
8k views

How to change a variable after it is already defined?

I'm trying to add or subtract from a defined variable, but I can't figure out how to overwrite the old value with the new one. a = 15 def test(): a = a +10 print ( a ) test() Error message:...
4
votes
2answers
323 views

Provide a reproducible copy of the DataFrame with to_clipboard() [duplicate]

2018-09-18_reproducible_dataframe.ipynb This was marked as a duplicate, however, the other question and answer(s) do not cover to_clipboard, while this question specifically covers .to_clipboard and ...
491
votes
8answers
890k views

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

I've very recently migrated to Py 3.5. This code was working properly in Python 2.7: with open(fname, 'rb') as f: lines = [x.strip() for x in f.readlines()] for line in lines: tmp = line....
281
votes
17answers
417k views

How to set Python's default version to 3.x on OS X?

I'm running Mountain Lion and the basic default Python version is 2.7. I downloaded Python 3.3 and want to set it as default. Currently: $ python version 2.7.5 $ python3.3 version 3.3 How ...
189
votes
6answers
15k views

What do ellipsis […] mean in a list?

I was playing around in python. I used the following code in IDLE: p = [1, 2] p[1:1] = [p] print p The output was: [1, [...], 2] What is this […]? Interestingly I could now use this as a list of ...
166
votes
5answers
567k views

TypeError: Missing 1 required positional argument: 'self'

I am new to python and have hit a wall. I followed several tutorials but cant get past the error: Traceback (most recent call last): File "C:\Users\Dom\Desktop\test\test.py", line 7, in <module&...
100
votes
8answers
72k views

How to replace NaNs by preceding values in pandas DataFrame?

Suppose I have a DataFrame with some NaNs: >>> import pandas as pd >>> df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]]) >>> df 0 1 2 0 1 2 3 1 ...
37
votes
4answers
29k views

Behavior of exec function in Python 2 and Python 3

Following code gives different output in Python2 and in Python3: from sys import version print(version) def execute(a, st): b = 42 exec("b = {}\nprint('b:', b)".format(st)) print(b) a = ...
3
votes
2answers
1k views

Pandas groupby with delimiter join

I tried to use groupby to group rows with multiple values. col val A Cat A Tiger B Ball B Bat import pandas as pd df = pd.read_csv("Inputfile.txt", sep='\t') group = df.groupby(['col'])['val']....
426
votes
16answers
392k views

How to install python3 version of package via pip on Ubuntu?

I have both python2.7 and python3.2 installed in Ubuntu 12.04. The symbolic link python links to python2.7. When I type: sudo pip install package-name It will default install python2 version of ...