r/pythonhelp • • Oct 25 '20

Simple Variable Defining Question

3 Upvotes

How can I input variable CF properly into total_cashflows to yield

[-40000, 5000, 8000, 12000, 30000].

Code:

import numpy as np

rate = .08

Initial_investment = -40000

CF = [5000, 8000, 12000, 30000]

total_cashflows = [int(Initial_investment), int(CF)]

np.npv(rate, total_cashflows).round(5)


r/pythonhelp • • Oct 21 '20

Coding Help

3 Upvotes

I need help creating a code. The prompt is: Write a function showChar to display the character at a certain index in a given string. And an example of the execution is:

Enter a string: New York

Enter an index: 2

The character at index 2 in New York is w

>>>

Enter a string: New York

Enter an index: 8

Invalid index!


r/pythonhelp • • Oct 16 '20

Selenium returning element not found error for for find_element_by_xpath

3 Upvotes

Hey all,

I'm new to Python, and I'm trying to use Selenium to automate downloading. My intention is to click the download button on this website (or the equivalent for different datasets). I've tried various methods of selecting the element, but none work. Currently I'm using the xpath, copied from Firefox's inspector. The path syntax appears valid (finding by id and using the * to search all xpaths), so I don't know what's causing the issue. Since other methods don't work either, I suspect I'm making some basic error using the driver.

Code:

browser.get("https://data.census.gov/cedsci/table?q=ACSDT1Y2018&tid=ACSDT1Y2018.B00001&tp=true&hidePreview=true")
browser.find_element_by_xpath('//*[@id="toolbar-download"]').click()

Any suggestions?


r/pythonhelp • • Oct 14 '20

Among Us Help

3 Upvotes

it is a among us imposter detector but only the final response is actually counting.

https://repl.it/@zandernew/GargantuanCompetitiveInitializationfile#AMong


r/pythonhelp • • Oct 13 '20

TypeError: '<' not supported between instances of 'function' and 'int' (PLEASE HELP)

3 Upvotes

I'm new to Python and keep getting this error. Can some please help me? Thanks in advance.

def main ():

intro()

get_income()

get_number()

compute_assistance(get_income, get_number)

def intro():

print("\nWelcome to our financial assistance program. ")

print("In order for us to assist you, we'll need some information. ")

print("Your eligibility and amount of assistance will depend on a couple of factors. ")

def get_income():

income = float(input("\nPlease enter annual household income: $"))

while income < 0:

print("Error! Income must exceed zero ")

print("Re-enter Income ", end='')

income = float(input(": "))

return 'income'

def get_number():

number = int(input("Please enter number of children: "))

while number < 0:

print("Error! Cannot have negative children ")

print("Re-enter number of children ", end='')

number = int(input(": "))

return 'number'

def compute_assistance(income, number):

if income in range (30000, 40000) and number >= 3:

total_assistance = float(1000 * number)

print("You qualify for $", format(total_assistance,',.2f'), "in financial assistance! ")

print("You are eligible to receive $1000.00 per child based on your income. ")

elif income in range (20000, 30000) and number >=2:

total_assistance = float(1500 * number)

print("You qualify for $", format(total_assistance,',.2f'), "in financial assistance! ")

print("You are eligible to receive $1500.00 per child based on your income. ")

elif income < 20000:

total_assistance = float(1500 * number)

print("You qualify for $", format(total_assistance,',.2f'), "in financial assistance! ")

print("You are eligible to receive $2000.00 per child based on your income. ")

else:

print("You do not qualify for financial assistance. ")

return 'total_assistance'

main()


r/pythonhelp • • Oct 10 '20

Python Poetry

3 Upvotes

For the Python poetry lovers with good heart, willing to give me a hint with this poem ;) Let me know if you got BTC wallet or Patreon and I will be happy to compensate you :)

“We have developed speed, but we have shut ourselves in. Machinery that gives abundance has left us in want. Our knowledge has made us cynical. Our cleverness, hard and unkind. We think too much and feel too little. More than machinery we need humanity. More than cleverness we need kindness and gentleness.”

  1. Order all the sentences of the text according to their length (number of words per sentence) and it should be presented in the following order: the longest sentence first, the second longest thereafter and so on (e.g., ‘The longest sentence in this text contains “X” words”; The second longest sentence in this text contains “Y” words, ...., and the shortest sentence in this text contains “Z” words’).

  2. Extract five longest words in the entire text, create a List with those items and order them alphabetically. Print out these results on the screen (e.g., ‘Five longest words in this text ordered alphabetically are: “word1”, “word2”, “word3”, “word4”, “word5”’).


r/pythonhelp • • Oct 03 '20

It gives me this output no matter what I change, I’m looking for it to just display the equation with x^-3 in place of x. Why? How to fix???

Thumbnail
gallery
3 Upvotes

r/pythonhelp • • Sep 04 '20

Does anyone know how to remove auto-complete from spyder (Python 3.8)

Post image
3 Upvotes

r/pythonhelp • • Aug 17 '20

Loops and tkinter act strange

3 Upvotes

I have made a bit of a program that tells you some prices with a tkinter window and then asks you how many of a commodity you want to buy. But after the first loop(you play several rounds) it stops waiting for an input. Let me know if you need code beyond this.

```

https://github.com/randomairborne/test/tree/master

```


r/pythonhelp • • Aug 08 '20

Pygame help

3 Upvotes

Hi there,

Hope everyone is doing well, for my A level Comp Sci project i have decided to make a "Logic Gate Simulator", where it will displays pictures of logic gates and I cant seem to add a AND gate on this screen, when i run the code, a picture of the AND gate appears and then it goes to the menu. I dont want that to happen i want it to display the image in the logic gates section.

I dont know if i posted this on the right subreddit or not but if anyone can please help me it will be greatly appreciated.

For the menu i found some code and tweaked it to fit my project.

I want the AND logic Gate to appear here, but i cant seem to find a solution and how to make it appear

I want make an AND gate appear when i click on logic gates.

This is my menu


r/pythonhelp • • Jul 15 '20

I'm new but why is it not saying 'a is bigger than b by a lot'

3 Upvotes

r/pythonhelp • • May 30 '20

How to use python/kivy to record and play audio on iOS and Android?

3 Upvotes

Trying to create cross platform kivy app that records and plays audio as part of the functionality. I used pyaudio to handle everything and recording and playing audio works fine on my laptop running Linux. Tried uploading what I have so far to my Android phone using buildozer and the app immediately quit, looking at the logs showed that it couldn't install pyaudio.Did some research and apparently as of now there is no way to run pyaudio on Android. Tried using the module sounddevice instead, got the same problem. I found another module available on PyPI, called sound, documentation is here: http://omz-software.com/pythonista/docs/ios/sound.html#module-sound.

Looking at the documentation says it works on iOS, but looking at the package on PyPI shows that it's still early in development, and trying it out in the python shell shows that most of the functions are missing still. For Android, I know I could use pyjnius to record and play audio with Android's Java functions and use plyer too, but I don't know if there is an equivalent to pyjnius for calling Swift instead of Java for iOS. Plyer also can't use audio i/o on iOS. I did find, however pyobjus for calling Objective-C, and something here, which I don't understand. I really don't want to have to maintain multiple code bases, that's why I used kivy in in the first place. Worst case scenario, I have multiple code bases and I learn Swift for iOS and Dart for Android. Does anyone happen to know the best way to record and play audio with python on Android and iOS?

Edit:

Did a little more research on plyer/pyobjus capabilities on this repository. This person added an iOS audio implementation that's very similar to the android counterpart that was included before in plyer, which is good. Specific to my project, I need to use recording and playing audio for mic streaming on mobile. For example, someone speaks into their phone and their voice plays somewhere else. I also found this?


r/pythonhelp • • May 05 '20

FIX for pygame not working on MacOS

3 Upvotes

I spent a lot of time looking around the internet for a solution to pygame's display not initializing on mac os.

Here is the solution if anyone else ends up needing it, just uninstall pygame if already installed and run this command:

pip3 install pygame==2.0.0.dev6


r/pythonhelp • • Apr 27 '20

Help me out, why does this only print the last line of text in my csv file (there are 4 lines)

Post image
3 Upvotes

r/pythonhelp • • Mar 09 '20

my cousin sent me this question...Please help, thanks!

3 Upvotes

How to calculate this by using python? (question stated there is a total of 2020 minus signs existed)

Thanks for the help!


r/pythonhelp • • Mar 07 '20

tkinter Frame object destroyed after place_forget() - how to conserve?

3 Upvotes

TLDR: I want to show/hide frame objects, that are dictionary elements, without them being destroyed. Defining the dict as a global doesn't work. Please help.

Code: https://pastebin.com/nJRVSVSV

Hi guys,

I have a tkinter program to input some user data, I want to be able to show either 2 or 4 frames at a time, with a 'Name' input box, and for the names to be conserved when the number of frames is updated.

My tkinter objects are stored in a dictionary and I'm using place() and place_forget() to show and hide the frames.

My problem is that when I show/hide the frames, the data inside them is lost.

I have already solved a similar problem with an image, in that case I put the image object/tk canvas as globals variables so that it wasn't deleted in the garbage collection when I hid the image.

I can't seem to make this approach work this time.

I have set the frames_dict as a global variable, but I feel like the frame objects that are the individual elements of the dictionary are not globals, so are being destroyed by garbage collection. This is confirmed print the frame object IDs as they are shown/hidden.

How can I set the individual frames as global variables so that they are not destroyed?

Is there another approach? If possible I would like to avoid the use of globals.

Thanks!


r/pythonhelp • • Dec 26 '19

Beginner help with print command with multiple variables

3 Upvotes

What is the proper way for print(message0, message1, message2, message3,) to have each variable on the next line?

I have tried doing '\n' before and after each variable and only get a syntax error. I have also tried doing ,'\n\n\n\n', as I saw on another forum, and that did not work out.


r/pythonhelp • • Dec 13 '19

Help me please! I’m trying to modify files, but when i run it, it wipes the file clean??

Post image
3 Upvotes

r/pythonhelp • • Feb 25 '19

Can't figure out how to solve this for my online class

3 Upvotes

Create a list consisting of the negative values in the list numbers. Associate the new list with the variable negatives.


r/pythonhelp • • Jan 19 '19

Struggling to "fire" some python code from GitHub

3 Upvotes

I'm struggling to run some python code from GitHub. I've been writing my own very simple code but I'm nowhere near competent enough to see what I'm doing wrong with someone else's code.

I use the Spyder IDE through Anaconda and don't run code from the command prompt in Windows.

I'm trying to convert Charities Commission BCP files (contained within a Zip file) to CSV. There is Python code on Github to do exactly that here: https://github.com/ncvo/charity-commission-extract

The guide to the code says to run the command "python /path/to/script/import.py /path/to/download/zip/RegPlusExtract_February_2015.zip" at the command prompt (which I've tried and failed to do - assume as I only have the Anaconda / Spyder install).

I've opened import.py in the Spyder IDE and have import.py, bcp.py and the current, December extract all in the same folder. I assume that I can amend a line in import.py to point to the December extract but I can't see which one and now I'm stuck.

Any help very gratefully received.


r/pythonhelp • • Jan 01 '19

schedule module

3 Upvotes

I'm a beginner. Thanks in advance. This doesn't work. There doesn't seem to be a way to pass arguments to the def logData using schedule.every

It gives the error.

main()

File "/home/pi/Sensors_Database/logDHT11schedule.py", line 45, in main

schedule.every(6).seconds.do(logData, temp, hum)

NameError: name 'temp' is not defined

>>>

I could find no examples of how to execute this, I'm not sure the schedule.every should go into def main():

#!/usr/bin/env python

# -*- coding: utf-8 -*-

#

# logDHT11.py

# edited for DHT11, tk

# Developed by Marcelo Rovai, MJRoBot.org @ 10Jan18

#

# Capture data from a DHT11 sensor and save it on a database

import time

import schedule

import sqlite3

import Adafruit_DHT

dbname='sensorsData.db'

# sampleFreq = 60 # time in seconds

# get data from DHT sensor

def getDHTdata():

DHT11Sensor = Adafruit_DHT.DHT11

DHTpin = 16

hum, temp = Adafruit_DHT.read_retry(DHT11Sensor, DHTpin)

if hum is not None and temp is not None:

hum = round(hum)

temp = round(temp, 1)

return temp, hum

# log sensor data on database

def logData (temp, hum):

conn=sqlite3.connect(dbname)

curs=conn.cursor()

curs.execute("INSERT INTO DHT_data values(datetime('now'), (?), (?))", (temp, hum))

conn.commit()

conn.close()

return

# main function

def main():

schedule.every(5).seconds.do(getDHTdata)

schedule.every(6).seconds.do(logData, temp, hum)

print("I'm working...")

while True:

schedule.run_pending()

time.sleep(1)

# ------------ Execute program

main()


r/pythonhelp • • Jan 01 '19

character encoding for argv

3 Upvotes

Hello, I do not program in Python often. Working on a CLI utility for generating DKIM key pairs, one of the optional arguments is for the mailbox domain the key pair is to be used for. I am allowing unicode domain names and converting them to IDNA but when I do that I assume UTF-8 for the input encoding. Is there a (Python 2.7 compatible) way to detect the actual character encoding that is being used for the arguments?

https://gitlab.com/Pipfrosch/gnutls-for-librelamp/blob/master/PYTHON/dkim-keygen.py is my program, the two lines I use to handle non ASCII domain names are at line 311 currently (where the script handles the -d switch)


r/pythonhelp • • Dec 14 '17

Merging 2 lists of same length

3 Upvotes

list1 = ["a","b"] list2 = ["c","d"]

<some magic here>

out:

["ac","bd"]


r/pythonhelp • • 5d ago

python socks5 proxy server lib

2 Upvotes

is there library wich handless socks5 protocol for me and allows me to decide tru wich socks5 proxy to route each connection and to wich ip wich domain to resolve by giving it functions wich it calls when need to connect/resolve domain tru my proxy

example function that it gives(its not fully python syntax since python typing system is hard to read):

    run(
      ip,port,user,pass,
      resolve(domain)->ip, #called when client tryes to resolve domain and return ip it will get 
      connect(ip)->(ip,port,user,pass) #called when client wants to connect to specific ip and returns ip,port,user,pass of socks5 proxy tru wich it will connect,if user and pass is None connects without them
    )