Most voted "python" questions
Python is a dynamic and heavily typed programming language whose design philosophy emphasizes usability. Two similar but incompatible versions of Python are in use (2 and 3). Please mention the version you are using when asking a question about Python.
Learn more…8,642 questions
Sort by count of
-
2
votes2
answers487
viewsHow to use the return of a function in another Python function
I’m new in Python and I’m not being able to use a return of a function in another function in the sequence: I’m putting a fictional example just to describe my doubt: def…
-
2
votes2
answers96
viewsWhy does readlines display an empty list even with the file having data?
f = open("grades.txt", "r") for record in f.readlines(): print(f"grade : {record} ") print(f"readlines: {f.readlines()}") f.close() The.txt grid file exists and has the following content: 10 9.8 .6…
-
2
votes2
answers103
viewsWhy is this loop infinite?
I wanted to stop the loop when t is at 5. So I counted -1, but it does not go back to while to check the condition and turns a loop infinite. text = 'abcdefghij' t = 10 while t != 5: for i in text:…
-
2
votes1
answer331
viewsTop 3 the biggest numbers in the list and their indexes
I have the list [5, 7, 2]. I need to create another list containing the indexes in this list, ordered so that the first index corresponds to the largest element in the list, the second corresponds…
-
2
votes1
answer2189
viewsPython: SOAP requests, how to request a wsdl
Hello, I have a wsdl (https://ws1.bmgconsig.com.br/webservices/SaqueComplementar?wsdl) and need to make requisitions, but do not know how to do the treatment of headers and body based on wsdl. the…
-
2
votes1
answer45
viewsCreate a range within a for in range() loop?
In a tuple of items, for example: for x in range(2,numero+1): 1) Suppose the variable numero has been defined before as 7. Thus, how do I not include the 7 in this tuple, wanting to go through all…
-
2
votes2
answers742
viewsPython draw on the screen
Does anyone know if there’s any method I can draw on a pure canvas? Without the use of a graphical interface window, I will give an example to better understand (Ignore where you’re pointing) the…
-
2
votes2
answers684
viewsTransform object to Dict in python
Good team, blz ? So, I started to study python now and wanted a help from you on the following question: I need a class that receives two distinct arrays (words and key) and relates all elements of…
-
2
votes1
answer149
viewsRegular expression case insensitive in a dataframe
I have a dataframe with some tweets that were collected according to the keyword. How do for example to extract at once only the lines with #flamengo and all its variations, such as #Flamengo,…
-
2
votes1
answer140
viewsstore the data received from a sensor in a python list
How can I save 100 values received from a sensor in a python list, to later calculate their average? This is the code I have so far: #biblioteca para chamar ficheiros de outra extensão from…
-
2
votes2
answers103
viewsNegative print, it only prints the postives
Write a program that reads whole numbers from the standard input until a negative number is reported. At each reading the number read should be written in the standard output. n1 = int(input())…
-
2
votes1
answer49
viewsDoubt with print and with for
for l in arquivo: Print(l) In this file are the name information, IP and Hostname. I need to print the name, IP and Hostname, however in this format: Name space of 10 characters Ip space of 10…
-
2
votes1
answer534
viewsCatch string inside a text file using regex in Python
I would like to know how to get a string in this ' XXXX ' format inside a text file, using regex. I have tried several methods but without success: import re f = open('infos', 'r') padrao =…
-
2
votes1
answer89
viewsPrint even numbers in a list
I’m trying to get the code to print only as many even numbers as it finds and not list all the numbers it found. What I’m trying to make it appear on the screen: 5 números pares What is appearing on…
-
2
votes2
answers58
viewsWhy do you think the higher value?
x=0 quantos=0 valor=int(input()) while valor>0: if valor>x: x=valor #Se aqui ele define o X pro valor inserido, por que ele armazena o maior número? #não deveria armazenar o último? quantos=1…
-
2
votes1
answer352
viewsHow to save a function, with predefined parameters, in a python variable?
Currently I can save functions in variables as follows: def somar_iguais(lista, referencia): resultado = 0 for x in lista: if lista[x] == referencia: resultado += referencia return resultado SOMAR =…
-
2
votes2
answers61
viewsRelation __dir__ method and __getattribute__method
Guys, I wanted to ask you a question: class Frob(object): ... def __init__(self, bamf): ... self.bamf=bamf ... def __getattribute__(self,atr): ... return object.__getattribute__(self,'teste') When I…
pythonasked 4 years, 6 months ago Erick Kokubum 136 -
2
votes1
answer49
viewsWhat is the lifetime of a class instance and a "module instance"?
An object instance exists until its father is destroyed, i.e.: class AnyClass: def __init__(self): self.any_date = datetime.date.today() (any_date)It will exist until the moment that its "parent…
pythonasked 5 years, 7 months ago Matheus Saraiva 2,157 -
2
votes2
answers773
viewsHow to subtract several elements from a list?
I am making a calculator and would like to subtract several elements from a list, this because the list can have as many elements as the user wants. See my code: lista = [10, 5] subt = lista[0] for…
-
2
votes1
answer69
viewsI’m trying to use the . split() in a def and I don’t know why it’s not working someone can help me?
I’m trying to build a simple raffle script using the Tkinter library. from tkinter import * def sorteio(): from random import choice nomes = (ed1.get) splitn = nomes.split(" ") sort = choice(splitn)…
-
2
votes3
answers99
viewsReplace all arguments (of all strings) that exist in a Dict with . format
I wonder if there is any pythonica way to replace all the arguments (of all strings) that exist in dictionary with . format . For example: dicionario = {"nome": "{nome_usuario}", "idade": 26,…
-
2
votes1
answer160
viewsHow does operator overload work?
How this code works? class MyClass: def __init__(self, *args): self.Input = args def __add__(self, Other): Output = MyClass() Output.Input = self.Input + Other.Input return Output def __str__(self):…
-
2
votes1
answer41
viewsIt’s not stacking graphic
Follow the code below: import csv import matplotlib.pyplot as pl #RECEBENDO OS DADOS EM FORMA DE LISTA recebe = open("Exemplo.csv") dados = csv.reader(recebe,delimiter=';') for i in dados: print(i)…
pythonasked 5 years, 7 months ago user114629 -
2
votes0
answers280
viewsFlask not creating Sqlite database via Slqalchemy
Good afternoon to all! No way my code is creating the database via SQL Alchemy, follow the code snippet. from flask_sqlalchemy import SQLAlchemy app = Flask(__name__)…
-
2
votes3
answers1730
viewsRemove quotes in lines from csv file
Given a particular file iris.csv: "sepal_length,sepal_width,petal_length,petal_width,species" "5.1,3.5,1.4,0.2,setosa" "4.9,3,1.4,0.2,setosa" "4.7,3.2,1.3,0.2,setosa" "4.6,3.1,1.5,0.2,setosa" I try…
pythonasked 5 years, 7 months ago Costa.Gustavo 249 -
2
votes2
answers427
viewspython 3, exercise with prime numbers
The smallest m such that n · m + 1 don’t be a cousin. Example: For the first example, 3 · 1 + 1 = 4, the exit will be 1. For the second example, 4 · 1 + 1 = 5, we can’t print 1 because 5 is cousin.…
-
2
votes1
answer44
viewsDjango model mapping problem
The relationship between the classes in the Models.py file does not work because of the order of the classes (I think it has more to do with the interpreter) follows the problem: class…
-
2
votes1
answer888
viewsThe sum of the N first prime numbers
Write a program that reads a non-negative integer and print the sum of the N first prime numbers. I am not able to add the N first prime numbers but add up to the prime number typed. If I type 5 for…
-
2
votes1
answer109
viewsChange configuration file by configparser remove_section
How to save the configuration file (.ini) after deleting an option or section? I’m doing it this way: test ini. [LOCAL] url = 'http://localhost:8080/' username = 'usuario' password = 'SECRET'…
-
2
votes1
answer989
viewsHow to quickly calculate the sum of dividers in Python?
I would like to know how to quickly calculate the sum of the divisors of a natural number n, where 2 <= n < 109. For small numbers, I perform this operation quietly with the following code: n…
-
2
votes3
answers227
viewsAdd a string before a given word using Regex
I’m reading a file with a C code and turning it into another. I would like to replace the name of a variable that comes before or after an operation character by replacing it with "x" +…
-
2
votes1
answer256
viewsScroll through a list inside another List
Hello I’m a beginner in Python and I wonder if there is how to scroll through a list within another list, I tried to make an example, but is giving this error: "Typeerror: 'int' Object is not…
-
2
votes2
answers505
viewsCount in recursive function
I need to count how many times a comparison is true within a recursive function, but I don’t know how to do it, because any counting variable will be reset when starting the code. def…
-
2
votes1
answer1308
viewspython game of checkers
i have an array of a checkers game state, how can I know which pieces are threatened on the board? X5 is the threatened black parts and X6 is the threatened red parts, ie I want to know how to…
-
2
votes0
answers186
viewsRemove titlebar from Tkinter window
Good evening, the question is: how to shoot the title bar from the Tk window without making it background, which is what overrideredirect(True) does? With various researches, I saw that this line…
-
2
votes2
answers377
viewsMultiply elements of the first matrix by 3 and decrease elements of the second matrix by 3 in Python
My code must have two matrices each with 5 elements and the first matrix needs to multiply its elements by 3 whereas the elements of the second matrix need to decrease their elements by 3, but it…
pythonasked 5 years, 6 months ago user141036 -
2
votes1
answer235
viewsCapture typed key using Python 3
Below I have a code in Python that capture typed key, only I need to get the name of the program where he typed such key. How can I do that? from pynput.keyboard import Key, Listener import logging…
-
2
votes1
answer389
viewsRead and write binary files using STRUCT
I have an array valores = [16, -25, 34, 2, 199, 45, 67, 90]and need to save them in a binary file using struct. Then I need to read the binary file with struct. To read, I’m using the following…
-
2
votes5
answers135
viewsProblems with arrays in a Python password generator
I’m making a generator of passwords and I’m not able to join letters that are separated into one array. from random import choice minusculas = ['a','b','c','d','f','g','h'] maiusculas =…
-
2
votes2
answers238
viewsmanipulating csv file
good people. I need to use a csv file, which has more than ten columns and two thousand lines. I’m not sure how to get a single column. this program below, I took on the internet. separador = ','…
-
2
votes2
answers98
viewsHow to pass a Dict within a function, to be used in any case if necessary?
Good afternoon, I have a big keyError problem, because in my program that makes use of Dict will perform several processes, and if at some point he does not find an item in which he looks, will…
-
2
votes1
answer81
viewsHow do I print the name of an instance in Python?
class Panzer(): def __init__(self): self.life = 100 self.blin = 100 drogo = Panzer() cabal = Panzer() sirius = Panzer() group = [drogo, cabal, sirius] for i in group: print() What should I put on…
-
2
votes3
answers75
viewsAdd Character at the end of the line
Greetings, when I add a ";" to the end of the file, even if I specify that it is not to add if I am done with it, it is still added: newf="" with open('teste.txt','r') as f: for line in f: lastchar…
-
2
votes2
answers74
viewsHow do I know if a Shader is working?
Is my code right? I’m using Python and Pyglet, as I know if Shader is running, why did I get Shader’s code on the internet: import pyglet from pyglet.gl import * import pyshaders as ps t =…
-
2
votes1
answer89
viewsBase conversion
In a college job we were required to simulate the functioning of a RAM memory. The user can read or write in the cells of this memory or all Zera, and each one stores 8 bits. That part’s already…
-
2
votes1
answer62
viewsWhat exactly does this Python statement do?
I am studying the sklearn module of Python, and I came across this statement: data = pd.read_csv('car.data') X = data[[ 'buying', 'maint', 'safety' ]].values What exactly is stored in X? Because the…
-
2
votes1
answer971
viewsError "Indexerror: list assignment index out of range" when setting "l[0] ="
I’m having a problem in my class in function __init__() class Lutador(): __nome = "null" __nacionalidade = 'null' __idade = 0 __altura = 0.0 __peso = 0.0 __categoria = 'null' __vitorias = 0…
-
2
votes1
answer310
viewsHow to change numbers on the same Python line of execution?
Hello, I’m new to programming and I was doing a python countdown program. I did the code and it worked, but then I looked at the running program and the same using several lines just to change the…
-
2
votes1
answer670
viewsHow does the module operator work (%)?
I have a question about module operation. Why 10 % 8 returns 2? I couldn’t find it in the documentation.
-
2
votes3
answers233
viewsError using append after merging two lists into one
My teacher passed the following problem to be solved and translated to Python: Consider that we have two lists of people names, sedo that these lists are already in lexicographic (alphabetical)…