r/pythonhelp • • Feb 01 '24

Code stopped working

1 Upvotes

Why has my code all of a sudden stopped working? It normally did and now it doesnt im gonna send my code but its the “loan” part that isnt working I will send the point which im struggling.

loanconfirm=input('wouldyouliketotakeoutaloan?youmustpayitback')ifloan.lower()=='yes':loan=int(input('howmuchmoneydoyouwanttotakeout?')) balance=balance+loanprint(f'{loan}+{balance}={int(loan+balance)}')


r/pythonhelp • • Feb 01 '24

Need advice in python programm

1 Upvotes

Hello,

this is my python script

command = "ps ax | grep 'openvpn --daemon' | awk '{print $1}'"
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
if out:
print ("standard output of subprocess:")
if err:
print ("standard error of subprocess:")
print ("returncode of subprocess:")

But I get this error

standard error of subprocess:
returncode of subprocess:

why do i get an error ? normally it should display me the pid of the programm openvpn


r/pythonhelp • • Feb 01 '24

setting up a text editor to recognize python on a chromebook

1 Upvotes

Hello I am brand new to programming. I have a chromebook and the Python Crash Course book. I am having trouble understanding how to set up text editor to recognize python. I tried to follow a youtube video for Virtual Studio and got lost when the directions didn't match what I had in front of me. Visual studio has so many options and bells and whistles that I have option paralysis. Are there simple instructions for really stupid people out there. I want to learn this, but I'm so new that really don't understand it.


r/pythonhelp • • Jan 31 '24

SOLVED Game of life code needs fixing

3 Upvotes

Got a List index out of range error on line 29, don't know why. Here's the code:

cells = [[0,0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0,0],
		[0,0,0,0,1,0,0,0,0],
		[0,0,0,0,1,0,0,0,0],
		[0,0,0,0,1,0,0,0,0],
		[0,0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0,0]]

cells = [[0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,1,0,0,0,0],
       [0,0,0,0,1,0,0,0,0],
       [0,0,0,0,1,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0]]
new_cells = [[0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0]]
def neighbors(x, y):
   return [[(x-1)%10, (y-1)%10], [(x-1)%10, y%10], [(x-1)%10, (y+1)%10],
     [x%10, (y-1)%10], [x%10, (y+1)%10],
   [(x+1)%10, (y-1)%10], [(x+1)%10, y%10], [(x+1)%10, (y+1)%10]]
def alivenb(x, y):
   res = 0
   for i in neighbors(x, y):
     if cells[i[0]][i[1]] == 1:
       res += 1
   return res

for i in range(10):
   for j in range(10):
     if cells[i][j] == 1:
       if alivenb(i, j) not in [2, 3]:
         new_cells[i][j] = 0
       else:
         new_cells[i][j] = 1
     elif cells[i][j] == 0:
       if alivenb(i, j) == 3:
         new_cells[i][j] = 1
       else:
         new_cells[i][j] = 0
for i in range(10):
   for j in range(10):
     if cells[i][j] == 0:
       print('  ', end='')
     else:
       print('##', end='')
   print('\n')

r/pythonhelp • • Jan 31 '24

MPL not interpolating (contouring/contouringf) between all the data points.

1 Upvotes

Hi, I have Lat, Long and Temp data that I want to plot and contour using mpl. The Lat, Long data is not evenly spaced so that makes it a little harder. But my issue is that there are a few data points on the edge of the domain that are not being including in the contouring and I dont know why. Here is my source code:

import matplotlib as mpl
import matplotlib.pyplot as plt 
import numpy as np 
scipy from scipy.interpolate 
import griddata 
cmap = mpl.colormaps['viridis']

#Data: X, Y, Data
Long = [-110.157307803176, -110.157455469296, -110.157689404594, -110.157970751725, -110.158252212875, -110.158640307497, -110.159020237575, -110.159974339910, -110.160380856369, -110.157295657432, -110.157432801353, -110.157665962420, -110.157948368689, -110.158242940459, -110.158635611101, -110.159007448107, -110.159950808939, -110.160352429119]; 

Lat = [31.5909061542193, 31.5908347703798, 31.5907388930841, 31.5906671056475, 31.5905476732063, 31.5903211324519, 31.5901249028367, 31.5902391101446, 31.5901626619502, 31.5909757506254, 31.5908927635994, 31.5907852920129, 31.5907239327354, 31.5906104728768, 31.5903799609025, 31.5901963406308, 31.5903013305906, 31.5902095314044]; 

data = [88, 59, 24, 34, 69, 25, 61, 79, 139, 72, 46, 25, 13.4, 30.6, 70, 101, 121, 88]

#use linspace to fill the data between points
xi = np.linspace(min(Long),max(Long),200) 
yi = np.linspace(min(Lat),max(Lat),20)

#grid the data
zi = griddata((Long, Lat), data, (xi[None,:], yi[:,None]), method='linear')
fig, ax = plt.subplots(figsize=(10,6))

#contour the gridded data
CS = plt.contourf(xi,yi,zi,25)

#plot the data points
ax.set_ylabel('temp') 
ax.set_title('Survey') 
ax.set_xlabel('Longitude') 
ax.set_ylabel('Latitude') 
ax.tick_params(axis = 'both') 
cbar = fig.colorbar(CS, location = 'bottom') 
cbar.ax.set_ylabel('Temp') 
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') 
plt.xticks() 
plt.yticks() 
plt.scatter(Long, Lat, data, marker = '.', color='k') 
plt.show()

This is my first week with python.


r/pythonhelp • • Jan 31 '24

why is the plot streched?

2 Upvotes
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=plt.figaspect(1.)) 
ax = fig.gca(projection='3d') 
data = [np.linspace(0, 0, 40), np.linspace(0, 2*np.pi, 40)] 
theta = np.array(data[0]) 
phi = np.array(data[1]) 
sphere_x = np.sin(phi)*np.cos(theta) 
sphere_y = np.sin(phi)*np.sin(theta) 
sphere_z = np.cos(phi) 
ax.plot(sphere_x, sphere_y, sphere_z, '.') 
ax.axes.set_xlim3d(-1,1)
ax.axes.set_ylim3d(-1,1) 
ax.axes.set_zlim3d(-1,1) 
plt.show()

although it is a circle it doenst look like it, how can i fix this?


r/pythonhelp • • Jan 31 '24

Newbie on Python need asistance!

1 Upvotes

hello! how do I make this in python? I am struggling on the first part as I need to input an integer to make it come out as the programming language. How do I do that?

Needed to code: https://ibb.co/qgvGQDz

expected output: https://ibb.co/2ZCKfkc


r/pythonhelp • • Jan 30 '24

Creating a JSON in a particular format dynamically on csv name/column headings

1 Upvotes

I have the following data from a csv (dummy data)world.information.csv

refcountry/person/heightfood/type
1180burger
2165pizza

I am trying to get this into the following JSON format. The name of the csv is the main structure (separated by a .) and the column headings are the structure inside. Each ref is a separate JSON

{
"world":{
    "information": {
        "country": {
            "person": {
                "height": 180
            }
        },
        "food": {
            "type": "burger"
        }
    }
},

{
"world":{
    "information": {
        "country": {
            "person": {
                "height": 165
            }
        },
        "food": {
            "type": "pizza"
        }
    }
},

I would really like it to be dynamic (so it reads the name of the csv and also then the column headings to build the structure. Whenever I do this I get everything within information with a [ instead of {.

Thank you in advance, have been trying this for a solid week now


r/pythonhelp • • Jan 30 '24

New to Python, getting invalid syntax...

1 Upvotes

Hello! I'm writing a simple code for school and continue to get an invalid syntax error saying I may be missing a comma... It is right after the "Print("\nAwesome! Because you're spending more than $75 on Food Concessions...." line. Can anybody tell me what I'm doing wrong here?

#Prompt user to input number of food concessions being purchased

numFoodConcession = eval(input("\nPlease enter the amount of Food Concessions you will be purchasing. \n"))

#Calculate cost of Food Concessions

foodConcessionCost = numFoodConcession * foodConcessionPrice

#If statement to determine if the user will receive a free drink based on total Food Concession price, and display total Food Concession Cost

if foodConcessionCost > 75:

print("\nAwesome! Because you're spending more than $75 on Food Concessions, you get a free drink! \nThe Total cost of Food Concessions is $," foodConcessionCost)

else:

print("\nTo qualify for a free drink, spent more than $75 on Food Concessions. \nThe Total cost of Food Concessions is $," foodConcessionCost)


r/pythonhelp • • Jan 29 '24

how do i get the authorizing url for my discord bot?

1 Upvotes

i'm trying to add my bot to my discord server. but i don't know how to add it. when i ask chatgpt for the authorizing link it gives me a link. But it doesn't work. first time my bot don't have enough access. second time the link just doesn't work, the discord authorizing website said something like ' integration requires code grant '. how should i add my bot to my discord server????

thank you very much for viewing this post


r/pythonhelp • • Jan 29 '24

SQLi script using Visual 2020 - getting errors

1 Upvotes

I am attempting to follow along with This SQLi video and create the script the teacher writes. When I do an exact copy and paste into my VSC, I get this runtime error:

Exception has occurred: SystemExit

-1

File "C:\Users\<myname>\lab1.py", line 18, in <module>

url = sys.argv[1].strip()

IndexError: list index out of range

During handling of the above exception, another exception occurred:

File "C:\Users\<myname>\lab1.py", line 23, in <module>

sys.exit(-1)

SystemExit: -1

Have I saved my python script in the wrong place? All the libraries are correctly imported. I notice that the teacher does not press F5 to run this script, but rather types out the name of the script in the terminal then presses enter.


r/pythonhelp • • Jan 28 '24

Python Client-Server communication (RMI, RPC)

1 Upvotes

Hello,

I have a task to create a simple client-server distributed system.
Basically, the client side is required to take in an input (like an ID), validate it and then send it to the server where it will be check against a list of data (like ID number, Name, DOB) and if the ID is available the server sends back the Name and DOB to the client.
I haven't done something like this, and they want us to use RMI (but this is java based isnt it?) or RPC for communication, and no third party python packages can be used.
I only have basic knowledge on python, so I have no idea how to do a communication.

Any help or tutorials would be great!


r/pythonhelp • • Jan 27 '24

How would I change variable values in a for loop

1 Upvotes

I have got a bunch of variables called team1, team2, team3 and so on. I want do just do a for loop to change the value of all of these to shorten the code but i'm not sure how to do it. Any help would be really appreciated

def tourementPlan():

global teams
global team1
global team2
global team3
global team4
global team5
global team6
global team7
global team8
global team9
global team10
global team11
global team12
global team13
global team14
global team15
global team16
global team17
global team18
global team19
global team20

random.shuffle(teams)

for i in range(len(teams)):
    team + str(i) = teams[i]

r/pythonhelp • • Jan 26 '24

SelectionModel Issues??

1 Upvotes

Hi all,

Hoping for some help. Complete programming beginner. I’m using AI to help me code data management app for my business.

I have a QTableView that i is producing a list of JSON files containing project information i plan to use later. I have a push button for deleting a project. After TONs of hours, I cannot get the delete method to retrieve a selection index from the abstract model and take the project name to eventually delete the project from the directory.

Can anybody provide me steps to help? I can include code snippets if needed.

Thanks

Ash


r/pythonhelp • • Jan 25 '24

I am beginner I need guidance with a number game

1 Upvotes

I want to add a total of 10 tries and add I want to add how many tries it took the user to guess the number i don't know how please help me I'm trying again and again but keep failing please help with non complex codes

print("This game will give you 10 chances to guess a random number")

import random

secretnumber = random.randint(1,15)
while True:

    guessnumber=int(input('enter your guess'))

    if guessnumber> secretnumber:

        print('The number is Too high, Try Again!!!')

    elif  guessnumber< secretnumber:

        print('The number is Too Low, Try Again!!!')

    elif guessnumber == secretnumber:

        print('You have guessed is correct number...Congrulations!!!')

        print('Thanks For Playing')

        break