Click here to Skip to main content
15,881,172 members
Everything / Programming Languages / Python2.7

Python2.7

Python2.7

Great Reads

by Patrick P. Frey
This tutorial based on a docker image will guide through the development of a search engine service based on Strus and its Python Bindings within the Tornado web-framework.
by Dhruv Singh
Follow the tips below to write more beautiful and idiomatic Python code!
by Dhruv Singh
Detailed usage of the newer python format() method for strings
by Dhruv Singh
Python dictionary supports a get() method that helps to look up a key and perform assignment operation in one line of code!

Latest Articles

by Noman BD
Power of Naive Bayes Classification
by Patrick P. Frey
This tutorial based on a docker image will guide through the development of a search engine service based on Strus and its Python Bindings within the Tornado web-framework.
by MaulikJoshi
Here's how you can get started with Azure IoT edge. Learn how you can integrated SensorTag with IoT edge running on a Raspberry Pi
by Shao Voon Wong
Python Script to fill FIX Protocol Message Logs with information

All Articles

Sort by Score

Python2.7 

20 Oct 2017 by Patrick P. Frey
This tutorial based on a docker image will guide through the development of a search engine service based on Strus and its Python Bindings within the Tornado web-framework.
25 Nov 2015 by Dhruv Singh
Follow the tips below to write more beautiful and idiomatic Python code!
30 Sep 2014 by Dhruv Singh
Detailed usage of the newer python format() method for strings
16 Sep 2014 by Dhruv Singh
Python dictionary supports a get() method that helps to look up a key and perform assignment operation in one line of code!
8 Dec 2016 by rerhart585
Using SQLite, leverage the create_aggregate(), and SQL's Between Operator to create a Normal Probability Distribution Histogram, or what is more commonly referred to as a Bell Curve.
29 Jan 2019 by Richard MacCutchan
I just ran your code and got the following result: {'item_0': 'apples'} {'item_0': 'apples', 'item_1': 'banana'} {'item_0': 'apples', 'item_1': 'banana', 'item_2': 'oranges'} {'item_0': 'apples', 'item_1': 'banana', 'item_2': 'oranges', 'item_3': 'peaches'} {'item_0': 'apples', 'item_1':...
25 Jan 2020 by Richard MacCutchan
Think about the question and what you need to do: 1. Get the word in a, and the key letter in b 2. Set the flag to false 3. Create a loop that will iterate through all the letters of a 3.1. For each letter, compare it to b, and if it is lower, set the flag to true. 3.2. If the flag is now true,...
7 Aug 2020 by OriginalGriff
It's pretty simple: 1) Create a function which takes an integer parameter called limit 2) Inside the function: 2.1) Create a variable called sum and set it to zero. 2.2) Run a loop from 0 to limit inclusively. 2.3) Inside the loop: 2.3.1) If...
15 Mar 2021 by Richard MacCutchan
The Python Tutorial — Python 3.7.10 documentation[^]
16 Dec 2015 by JinWenQiang
Just a brief introduction of a simulator to build wireless environment
19 Apr 2016 by AnvilRanger
The answer is No. We will not do your homework for you. That would be a complete disservice to you and your future. Small assignments like this are intended to gauge what you have learned so far. You need to try coding yourself. Once you have done that come back here with any problems and people...
31 Oct 2016 by Jochen Arndt
These are not errors but warnings. They tell you that the result of the operation x + y might overflow. Your parameters are of type uint8 (range 0 to 255). When adding two such values the result may be greater than 255 which can't be stored as uint8. Then the result is truncated to 8...
6 May 2018 by Thomas Daniels
def prune(tree): result = [] for branch in tree: if branch != []: result.append(prune(branch)) return result You were almost there; the only step you missed, was adding the elements to a result list.
15 Nov 2018 by CPallini
x='abcdefghijklmnopqrstuvwx' xlist=[] for i in range(0,len(x),3): xlist.append(x[i:i+3]) print(xlist)
5 Dec 2019 by CPallini
the string.decode('hex') method goes in the opposite direction. You should use the hex function[^] instead. There is one caveat, though, to zero-fill it, you have to remove (and restore it afterwards) the leading '0x'. Try length=10; s = '0x' + hex(length)[2:].zfill(2) print(s) [update] Both...
19 Jun 2020 by Richard MacCutchan
This is the same issue as your previous question at Why the multilevel inheritance doest work ?[^]. You must pass the correct number of parameters to the super class, as clearly stated in the error message. If you do not understand how classes...
6 Oct 2020 by CPallini
Try [ x.split('.')[-1] for x in slist]
6 Oct 2020 by Patrice T
Quote: I have written the code of my question, but there are still some bugs You forgot to explain/describe what are the bugs. When you ask for help, it is a good idea to tell what is your problem. Quote: I can't figure out how to solve them. ...
13 Apr 2021 by CPallini
The following program (Python 3) s = input() lnum = list(map(int, s.split())) print("Unsorted:", lnum) print("Sorted Ascending Order:") print (sorted(lnum)) print("Sorted Descending Order:") print(sorted(lnum, reverse=True)) executes this...
6 Oct 2021 by OriginalGriff
If your code ran at all, it would be more believable, but since it has two syntax errors on the same line ... Change it to this: print (list [element].title()) And it'll actually do something. Not what your teacher wants, but something. ...
19 Jul 2022 by OriginalGriff
If you need to use the same numbers - and you do - then generate the randoms numbers and store them in an array: Python Arrays[^] You them modify both the mean and standard deviation code to use the data from the array instead of fetching a new...
22 Jul 2022 by Patrice T
Quote: apparently the program works well, but I needed to consider the value 0 also in the for result Try this: for i in range(0,np+1): print("%.1f" % a) a+=(l/np)
24 Jul 2022 by Richard MacCutchan
list = [3,0,1,-2] for i in range(1, len(list)): list[i] += list[i - 1] print(list) Produces: python atest.py [3, 3, 4, 2] Python test result: 0
19 Jan 2024 by OriginalGriff
I'm feeling generous tonight, so I'll give you a solution: ,>++++++[-],[-]
20 Sep 2012 by BobJanova
Either the task scheduler is running it as a user which doesn't have the permissions it needs, or it is running it without setting the environment variables that Python needs to execute correctly.If you have your batch script runpython script.py >log.txt... then you should get a log...
12 Jul 2013 by Prasad Khandekar
Hello Jyothi,Please have a look at this[^] link. My personal favorite is Balsamiq Mockups.Regards,
10 Mar 2014 by Matt T Heffron
Like Sergey said, you'll have to read all of the lines, at least until you've read what you wanted.However, you can use Linq to make it pretty easy:List myLineNumbers = new List{26, 30}; // 0-based line numbers!!!IEnumerable justMyLines =...
28 Nov 2014 by DamithSL
you may need space after script2.pyp.StartInfo.Arguments = "script2.py " + digitTb.text;// start the python program with two parametersand also add few validations string[] words = q.Split('.');if(words.Length>0) pTb.Text = words[0];if(words.Length>1) qTb.Text =...
10 Mar 2015 by Richard MacCutchan
The issue is down to the hidden return value from a Python function. If a function does not include a return statement, then it automatically adds one, and returns the value None, as described in https://docs.python.org/3.3/reference/simple_stmts.html#index-21[^]. So your print statement calls...
9 Sep 2015 by Sergey Alexandrovich Kryukov
It would be Iron Python: https://en.wikipedia.org/wiki/IronPython[^],http://ironpython.net/[^].Of course, "like the same" is wrong formulation, but what you are looking for is really Iron Python. The idea that you have to look at some "framework" is also wrong, because you are really...
11 Jan 2016 by Patrice T
We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.Try it yourself, you may find it...
18 Jan 2016 by Richard MacCutchan
You should not treat XML in this way, use a proper XML parser such as 20.6. xml.dom — The Document Object Model API — Python 3.3.6 documentation[^].
29 Jan 2016 by OriginalGriff
We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.Try it yourself, you may find it...
3 Feb 2016 by Richard MacCutchan
If HTTPConnection does not have a defined method to write to a file, then you would need to redirect stdout, as described in Redirecting all kinds of stdout in Python - Eli Bendersky's website[^].
13 Feb 2016 by Richard MacCutchan
You searched far and wide, so how is it you did not manage grib2 python - Google Search[^]?
15 Feb 2016 by Richard Deeming
You're missing a multiplication operator:s = ((n * (n + 1)) / 2) ** 2
20 May 2016 by Richard MacCutchan
See binascii.Error: Incorrect padding - Google Search[^].
28 Jul 2016 by Richard MacCutchan
You mention Java, Python and Android studio, so it is unclear what platform or language you are trying to use. If it is Java then see Creating a GUI With JFC/Swing[^]. Google will find you similar pages for other languages.
6 Sep 2016 by Richard MacCutchan
You declare X (upper case) in line 1, but you later refer to x (lower case), which does not exist.The lineFact = Fact*1does not do anything useful.I also suspect the last line of your code should be indented the same as the previous line.
26 Sep 2016 by ZurdoDev
No one is going to translate it all for you. I am also not aware of a translator that could do it which means you have to understand how it works and then re-write it. There is no magic bullet that will do the work for you.Once you understand how it works in Python then you can google for...
1 Jan 2017 by OriginalGriff
Google is your friend: Be nice and visit him often. He can answer questions a lot more quickly than posting them here...A very quick search using your subject as the search term gave nearly seven million hits: How to embedd Python in a C application - Google Search[^] In future, please...
1 Jan 2017 by Afzaal Ahmad Zeeshan
For any startup code you need to at least Google your problem once. If you had, you could have found this detailed article on CodeProject, Embedding Python program in a C/C++ code[^]. Even a simple code would be, to write a Python script and then execute that using Python interpreter,...
25 Jan 2017 by Jochen Arndt
You should try to optimise the Java code.The best optimisation can be achieved by avoiding dynamic object creation inside loops.An example:# PHPif w: if w[0] == ''// Javaif(w.length()>0){ if(w.substring(0, 1).equals("
6 Apr 2017 by CHill60
"How do I can solve the problem coins on a star" ... Firstly you do some research: Google[^] From the 2nd link on that search I learn that the problem can be solved using the "greedy strategy" or the "buttons and strings" method. Then I can find all sorts of information on the Greedy Strategy...
4 Aug 2017 by Thomas Daniels
There is no "better", because they have different purposes: .append adds a single element to the list. .extend is like append but for multiple elements: it takes a list as argument. a += [3, 5] is short-hand for a = a + [3, 5] and this does the same as extend, but the difference is that the +...
9 Aug 2017 by Richard MacCutchan
Try: def iptest(element): a = element.split('.') if len(a) != 4: return False for x in a: if not x.isdigit() or x == '': return False i = int(x) if i 255: return False return True
16 Sep 2017 by OriginalGriff
Read your homework question again. You need to read in lines of text, and store them until you get the blank line to end the input. After that, you need to have two loops to print that output back: first print the last N / 2 lines, then print the first N / 2 lines. This isn't complicated if you...
29 Dec 2017 by Patrice T
General answer: when you think performance; optimization, speed up ... The first thing to do is to think profiler. 26.4. The Python Profilers — Python 2.7.14 documentation[^] python - How can you profile a script? - Stack Overflow[^] The profiler is a tool that will show you the time spend in...
23 Jan 2018 by Jochen Arndt
Check some job advertisements. They usually list the requirements. Here in Germany diploma are required for governmental jobs but companies often have a term like "... or similar qualification" which can be references from previous employers or published code. If an ad provides direct...
27 Jan 2018 by Thomas Daniels
Both newjoke and the code in the while loop will ask "Did you find that funny?". So, what you see is the question getting repeated because after newjoke get called, you'll go back to the beginning of the while loop. This gives the impression of displaying a blank joke, but you just didn't hit...
27 Jan 2018 by Thomas Daniels
print("\nWell what about this:\n\n",joke) print("a", "b") will print a b with a space in-between. That's what's happening here too: it prints the "What about this" with the newlines, then a space, then the joke. Try this instead: print("\nWell what about this:\n\n" + joke)
1 Feb 2018 by Thomas Daniels
Add a staticmethod decorator: class Dice: @staticmethod def die(num): die=randint(1,num) return die The reason for the error: Python 2 requires the first argument to be an instance of the class itself; in Python 3 it can be anything. [Edit] Changing that alone won't...
11 Feb 2018 by Patrice T
No shorter, but may be debugged: if guess4== code[0]: wronPlace= (wronPlace+1) if guess3== code[1]: wronPlace= (wronPlace+1) if guess3== code[2]: wronPlace= (wronPlace+1) Are you sure about the guess3 in this part? [Update] Quote: Guess1 Guess2 Guess3 and Guess4 are the four...
12 Feb 2018 by Patrice T
Your first problem is that if guess1== code[1] or code[2] or code[3]: is not python. correction is if guess1== code[1] or guess1== code[2] or guess1== code[3]: Your problem is that an element of code can match a guess more than once. You have to device an algorithm that prevent it to from...
20 Feb 2018 by Patrice T
Looks like you have donne a step in right direction, but it is still more complicated. When a guess match a code in correct position, you have to make sure the same guess will not be checked for wrong position and that same code will not be checked for wrong position either. And when a guess...
16 Feb 2018 by Richard MacCutchan
Create a list that contains the answer. Loop1: Compare each digit of the guess with each digit of the list. For each point in the answer where the digits match do: Remove the digit from the list, and the guess, or replace them with some other character Add 1 to the "right...
7 Mar 2018 by Jochen Arndt
The pySerial port property is a Python string but the PyQt QLineEdit text() functions returns a QString object. So you have to use a conversion method or function. I don't know for sure which conversion must or can be used here because I don't know Python well. But you can try the QString...
18 Mar 2018 by Richard MacCutchan
Your formatting leaves much to be desired. However, you can simplify things by checking the values as you go through the initial loop, like this: flavours = ["Vanilla", "Chocolate", "Mint Choc Chip", "Rosewater", "Strawberry", "Mango", "Frutti Tutti", "Fudge Brownie", "Bubblegum",...
3 Apr 2018 by Auro.brze
You don't really need 2 for loops. Try this: from collections import Counter def main(): answers = [3, 3, 4, 4] guesses = [3, 5, 6, 4] answers_counter = Counter(answers) guesses_counter = Counter(guesses) diff_counter = answers_counter - guesses_counter ...
13 Jul 2018 by OriginalGriff
We all are: 1) Overview 2) Sepecification 3) Design 4) Implementation 5) Test 6) Release With looping back to any previous stage as a result at any time. But ... it's a big project, akin to saying "does anyone know how to build a bridge across the Bering Strait?" If you have to ask "do do I...
17 Sep 2018 by Richard MacCutchan
counter = 0 while 1: passwd = ''.join(random.sample(sbc,passlen)) if passwd == 'abc': print('password matched') break print(passwd, "does not match") counter += 1 print(counter, "iterations")
23 Sep 2018 by CPallini
Try a=list(input("enter a string ")) b=list(input("enter another string ")) c=a+b print(c) d=0 for i in range (0,len(c)): ch = c[i] if ch >='0' and ch
17 Oct 2018 by CPallini
C++ is quite expressive: #include #include #include using namespace std; vector readinput() { size_t n; cin >> n; vector v(n); for (auto & x : v) cin >> x; return v; } vector solve(const vector & inseq) { auto size =...
20 Nov 2018 by Richard MacCutchan
You only have 1 item in your array, as noted in the error message. Array elements are addressed starting at zero.
17 Dec 2018 by CPallini
You know, a recursive function calls itself until a stop condition is met. so, in your case you need a function that: Checks the stop condition (all numbers printed out) and returns if it is met. Prints the current number. Calls itself with an incremented argument in order to print the next...
6 Nov 2019 by OriginalGriff
We are more than willing to help those that are stuck: but that doesn't mean that we are here to do it all for you! We can't do all the work, you are either getting paid for this, or it's part of your grades and it wouldn't be at all fair for us to do it all for you. So we need you to do the...
6 Jan 2020 by Christian Graus
It doesn't work this way. You'd have to do print("x"). no language tracks which variable another variable was set with, unless it's a reference variable and they are both the same object
7 Jan 2020 by Richard MacCutchan
Short answer: you don't. In the code what actually happens is: x = 5 # variable x now contains the value 5 y = x # variable y now contains a copy of variable x, that is the value 5 print(y) # prints whatever value is in y
28 Feb 2020 by Richard MacCutchan
First suggestion is that you should please explain what the problem is. My second is that you go to The Python Tutorial — Python 3.7.6 documentation[^] and work through it a few times. Some actual solid study now will pay dividends in the future.
18 Apr 2020 by MadMyche
2 very common problems are here. The first is that your code is vulnerable to SQL Injection. You should NEVER EVER create an SQL query by piecing command strings and user data together. If you slip in a few special characters you can easily open...
8 May 2020 by Richard MacCutchan
Quote: I'm not getting it how to proceed it can u plz help to code full programme Sorry, no. This site is not here to do your homework for you. We do not do it as it would be no help in furthering your education or career. If you rely on other...
8 May 2020 by Patrice T
It is a good idea to give link when refering to a chalenge: https://www.codechef.com/MAY20A/problems/TWOSTRS[^] Quote: I'm not getting it how to proceed it can u plz help to code full programme Solve the example by hand, using brute force, see...
19 Jun 2020 by markkuk
I think you don't really understand what "inheritance" in object-oriented programming means (it's not a way to describe family trees). Inheritance describes an "is-a" relationship between the subclass and parent class. In your code the class...
22 Jun 2020 by OriginalGriff
When this question was posted - by you - yesterday, you were told that we don;t do your homework: A C/C++ (or other language) program that takes as inputs the file 3d.txt and the file 2d.txt[^] That hasn't changed: We are more than willing to...
9 Jul 2020 by Richard MacCutchan
Of course it does, as you are passing parameters by position and not by name. So if you reverse the order in line 12 then they will be reversed when they are received by c1's constructor. If you want the values to be referred to by name then your...
11 Jul 2020 by OriginalGriff
Apart for not compiling as is, so the code sample you show won't work, give it a try: replace the "if" with a print statement and show the values of i and j. Whichever goes up first is the inner loop.
11 Jul 2020 by Richard MacCutchan
Using a simple example we get the equivalent shown here: x = [ 2, 3, 4, 7, 11 ] z = [j for i in x for j in range(len(x)) if i == x[j]] print(z) # which is the same as zzz = [] for i in x: for j in range(len(x)): ...
13 Jul 2020 by Member 14888563
hi I would change your if statement to: if scapy.Raw in scapy_packet and scapy.TCP in scapy_packet: instead of: if scapy_packet.haslayer(scapy.Raw):
23 Jul 2020 by Sandeep Mewara
Output of above: ('before calling rohan', 20) ('after calling rohan', 20) 88 Execution sequence: 1. harry() called 2. print("before calling rohan",x) => x=local x value that is not modified so far => 20 3. rohan() called => updates global x...
30 Jul 2020 by CPallini
You find the target in picture, at {i,j} (with i and j in the [0..5] range) if (and only if) target[k][l] == picture[i+k][j+l] is True for every k=0,..,2 and l=0,..,2 It is not a difficult algorithm to implement.
8 Aug 2020 by Sandeep Mewara
Okay, so if read the requirement here: Quote: Given schedule of trains and their stoppage time at a Railway Station, find minimum number of platforms needed what is expected or would help here is to find maximum trains present at a given point...
8 Aug 2020 by Patrice T
When posting a question about a challenge from a site, it is a good idea to post a link to the page, as every word in requirement can matters. Quote: i want full solution And I want to win lottery grand price. Quote: well i try to write some...
11 Aug 2020 by OriginalGriff
Spacing is important! Change: if__name__ == '__main__': To if __name__ == '__main__':
6 Oct 2020 by Richard MacCutchan
What is this supposed to be for: char = 'extra'? All you need is def remove_chars(word, char_list): # returns str with characters in same order as in word # except the ones in char_list for char in word: if char in...
6 Oct 2020 by Patrice T
Quote: as I am writing its function it is not working. I can't figure out why. I would start by simplifying the code to: def remove_chars(word, char_list): # returns str with characters in same order as in word # except the ones in...
29 Oct 2020 by CPallini
The above code finds the maximum value in the container: In the loop, each time x is found less then an item, its value is set equal to the one of the item itself.
27 Mar 2021 by Richard MacCutchan
var={'rank':[2,4,1,3]} var['rank']=sorted(var['rank']) See 5. Data Structures — Python 2.7.18 documentation[^].
29 Mar 2021 by Richard MacCutchan
di={'name':['a','b','c'],'sex'...
22 Apr 2021 by OriginalGriff
We don't know - we can't run your code in isolation, and we have no access to your data. So, it's going to be up to you. Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. How you use it...
20 Jul 2021 by Richard MacCutchan
You need to ensure that the main thread of your program does not terminate while child threads are active. See threading — Thread-based parallelism — Python 3.9.6 documentation[^]. [edit] Note also that trying to run 400 threads together will...
5 Oct 2021 by Afzaal Ahmad Zeeshan
I guess you have used a template file and it is trying to load the Bootstrap from your local machine, that's why it has the following error: 1.Failed to load resource: the server responded with a status of 404 (Not Found) popper.min.js:1 To fix...
8 Dec 2021 by Richard MacCutchan
You need to use the string replace function to replace the newline with nothing: soup_ExeName = soup_ExeName.replace("\n", "")
5 Apr 2022 by Richard MacCutchan
Quote: i tried getting a solution to it after working through www.w3schools.com How about doing what you are supposed to do, and actually think about the problem. If the current number is greater than the existing maximum then how would you...
5 Apr 2022 by CPallini
With 4 possible answers even an experimental brute force approach would work. The function should return the maximum number. Now, if the current maximum max_num is smaller than num is it still the maximum? Should it be updated? Which is a good...
19 Jul 2022 by CPallini
Note: your computation of the average is NOT correct: for i in range(0, 6): soma += sorteio() extracts (and sums up) 6 values, while media = soma / 5 divides by 5. Anyway, as already suggested by Griff, consider rearranging your code for...
26 Jul 2022 by OriginalGriff
Use the zip function[^]: final_list = [sum(value) for value in zip(lst, lst1)]
26 Sep 2022 by CPallini
Quote: img = cv2.cvColor(img, cv2.COLOR_BGR2RGB) Mistyping error ('t' missing): The method name is cvtColor, see Python OpenCV | cv2.cvtColor() method - GeeksforGeeks[^].
18 Oct 2022 by OriginalGriff
Simple: if the condition is true, the continue statement is executed, and The rest of the loop body is not executed - the loop immediately goes round for another iteration on the next item in the collection.
16 Feb 2023 by Richard MacCutchan
You get date and time information via datetime — Basic date and time types — Python 3.11.2 documentation[^].
6 Aug 2023 by Richard MacCutchan
Similar issues to your previous question on this subject. The object named root belongs to the AplicacionInventario class. When you call Login(self) the login object is created, but the attribute named root is not passed over to it, hence the...