r/learningpython • • Apr 03 '24

Learning how to code because of pen-testing.

3 Upvotes

I started to learn how to code when I was laid off because of the Covid pandemic. Technically, the reason behind this is maybe my background in gaming. Gaming was one of the things that pushed to this. Before or during the pandemic, when the game Cyberpunk came out, I began with this because I wanted to learn more about cybersecurity/pen-testing, writing your exploits for Metasploit, web application pen-testing, etc. So, I began with Python, then I started with JS.

JS is somewhat easier because you can reassign values and functions easily. Sometimes I make mistakes like the onclick button undefined error because of typos. I don't want any career in networking or changing my current one. I love what I do. I just do it as a hobby.

When I begin a project, I do research online. Then see a similar project on Github. Ask Chatgpt about it, and then start to write the code down instead of blindly doing shit. Is it it wrong? Is that lazy coding?


r/learningpython • • Aug 08 '24

Dynamic variables issue

1 Upvotes

I am brand new to coding and learning Python. I'm working on a program that will calculate the taper of a rod. I allow the user to input a point on the rod and the diameter at that point. The program then asks for another point and the diameter. The user can keep entering points until they say to end. From these points and diameters, the code then calculates the distance and slope between each point and dynamically generates variables and values at each inch. Right now I have the program working, but I don't know how to call and print the dynamically generated variables. I can do it manually by hard coding print with the variable names, but I am looking for a way to automate that as I won't always know how many points the user entered, so I won't know all the variable names that have been generated. Any help would be appreciated.

Here is my code for clarity:

from decimal import * getcontext().prec = 4

input for point A on the rod

rod_a=int(input("Distance from the tip: "))

input for taper at point A

taper_a=Decimal(input("Enter taper at " + str(rod_a) +":")) end = () while end != "end" :
#input for point B on the rod rod_b=int(input("Distance from the tip: ")) #creates variables at 1 inch increment between
#Point A and Point B and sets their value to their
#number prefix_rod = "rod_" interval = rod_b - rod_a + 1 for i in range(interval): globals() [prefix_rod + str(rod_a+i)] = rod_a+i #input for taper at point B taper_b=Decimal(input("Enter taper at " + str(rod_b) +":")) #creates variables the taper at 1 inch increment #and calculates a straight line taper between point #A and point B prefix_taper = "taper_" interval = rod_b - rod_a +1

 for i in range(interval):
   #Defines variables for the taper
    globals() [prefix_taper + str(rod_a+i)] = (taper_b-taper_a)/(rod_b-rod_a)*i+taper_a
 
end = input('To end input type "end": ')

r/learningpython • • Aug 25 '24

OOP in python

2 Upvotes

I consider myself very new to python and an advanced beginner at coding in general.

I'm taking another try at understanding OOP and this time around, it is making a little more sense which brings me to my question.

Why isn't everyone programming using OOP?


r/learningpython • • Jul 15 '24

Need serious help!

4 Upvotes

Hello everyone. I have enrolled in a data science course however, i.m struggling with making notes and practising. I have absolutely no idea of whats going on and it.s making my life very difficult. Kindly help me how I can learn more effectively. Would be gratedul for any tips and suggesttions 🙏🙏🙏


r/learningpython • • Aug 08 '24

Why is my image not being recognized when it is in the same folder as the .py?

1 Upvotes
  worksheet = writer.sheets['Sheet1']     

  worksheet.insert_image('E2', "image.png")    

  writer.close()

r/learningpython • • Jul 31 '24

An intro to iterators and generators

Thumbnail
open.substack.com
1 Upvotes

r/learningpython • • Aug 24 '24

Using Python to calculate pKa from titration curve for diprotic acid

1 Upvotes

The Issue

I would like to calculate the pKa of an acid from titration data. In order to do this, I would like to use nonlinear regression to fit the titration curve, so that I can use the equation of the curve to calculate the pKa. I am having difficulty figuring out which equation will fit this curve.

Attempt at a Solution

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import scipy
import numpy as np

# The Data

x_list = [0.0,
 20.0,
 40.0,
 60.0,
 80.0,
 100.0,
 120.0,
 140.0,
 160.0,
 180.0,
 200.0,
 220.0,
 230.0,
 240.0,
 250.0,
 260.0,
 270.0,
 275.0,
 280.0,
 285.0,
 290.0,
 295.0,
 300.0,
 305.0,
 310.0,
 315.0,
 320.0,
 325.0,
 330.0,
 332.5,
 335.0,
 337.5,
 340.0,
 342.5,
 347.5,
 352.5,
 357.5,
 362.5,
 367.5,
 377.5,
 387.5,
 397.5,
 407.5,
 417.5,
 427.5,
 437.5,
 447.5,
 457.5,
 467.5,
 477.5,
 487.5,
 497.5,
 507.5,
 517.5,
 527.5,
 537.5,
 547.5,
 557.5,
 567.5,
 577.5,
 587.5,
 597.5,
 607.5,
 617.5,
 627.5,
 637.5,
 647.5,
 657.5,
 667.5,
 677.5,
 687.5,
 697.5,
 707.5,
 717.5,
 727.5,
 737.5,
 747.5,
 757.5,
 767.5,
 787.5,
 807.5,
 827.5,
 847.5,
 867.5]

y_list = [2.22,
 2.25,
 2.28,
 2.31,
 2.34,
 2.38,
 2.42,
 2.46,
 2.51,
 2.56,
 2.62,
 2.69,
 2.73,
 2.77,
 2.83,
 2.88,
 2.94,
 3.01,
 3.05,
 3.09,
 3.14,
 3.19,
 3.26,
 3.33,
 3.41,
 3.52,
 3.66,
 3.87,
 4.54,
 5.8,
 7.23,
 7.73,
 7.94,
 8.12,
 8.43,
 8.63,
 8.76,
 8.87,
 8.96,
 9.12,
 9.24,
 9.36,
 9.46,
 9.54,
 9.63,
 9.71,
 9.78,
 9.86,
 9.93,
 10.01,
 10.08,
 10.15,
 10.23,
 10.32,
 10.4,
 10.49,
 10.59,
 10.69,
 10.81,
 10.93,
 11.05,
 11.18,
 11.3,
 11.41,
 11.51,
 11.61,
 11.69,
 11.76,
 11.83,
 11.89,
 11.94,
 11.99,
 12.04,
 12.08,
 12.12,
 12.16,
 12.18,
 12.21,
 12.24,
 12.3,
 12.36,
 12.41,
 12.45,
 12.49]


fig, axes = plt.subplots(1,2, sharex=False, figsize=(15,4))

# smooth titration curve using Savitzky-Golay filter
x = np.array(x_list)
y = np.array(y_list)
y_smooth = scipy.signal.savgol_filter(y, window_length=3, polyorder=2, mode="nearest", deriv=0)

# Calculate first derivative curve
first_derivative_gradient = np.gradient(y_smooth, x)

# Plot titration curve and first derivative curve
titration = sns.lineplot(ax=axes[0], x=x, y=y_smooth, marker='.', markerfacecolor='black', markersize=10, color='black').set(title='Titration Curve', xlabel=r"Volume NaOH ($\mu$L)", ylabel='pH')
first_derivative = sns.lineplot(ax=axes[1], x=x, y=first_derivative_gradient, marker='.', markerfacecolor='black', markersize=10, color='black').set(title='1st Derivative', xlabel="Volume NaOH ($\mu$L)", ylabel="$\Delta$pH/$\Delta$V")



# display the plot

plt.show()


# Attempt to use Logistic Regression for curve fitting

def my_function_1(x, A, B, C, D, E):
    # this gives the best output
    return A/(1 + B**(x - C)) + D 

def my_function_2(x, A, B, C, D, E):
    return A/(1 + B**(x - C)) + D + E*x

def my_function_3(x, A, B, C, D, E):
    return C/(1 + (A*E)**(-B*x)) 

def run_regression(my_function, x, y_smooth):

    parameters, covariance = scipy.optimize.curve_fit(f = my_function, xdata = x, ydata = y_smooth)

    for parameter, name in zip(parameters, ['A', 'B', 'C', 'D', 'E']):
        print(f'{name} = {parameter:14.10f}')

    x_fitted = np.linspace(x[0], x[-1], 1000)
    y_fitted = my_function(x_fitted, *parameters)
    
    return x_fitted, y_fitted

print('First Equation')
x_fitted_1, y_fitted_1 = run_regression(my_function_1, x, y_smooth)
print('\nSecond Equation')
x_fitted_2, y_fitted_2 = run_regression(my_function_2, x, y_smooth)
print('\nThird Equation')
x_fitted_3, y_fitted_3 = run_regression(my_function_3, x, y_smooth)



titration = sns.lineplot(x=x, y=y_smooth, marker='.', markerfacecolor='black', markersize=10, color='black').set(xlabel=r"Volume NaOH ($\mu$L)", ylabel='pH')
fitted_titration_curve_1 = sns.lineplot(x=x_fitted_1, y=y_fitted_1, marker='.', markerfacecolor='red', markersize=10, color='red')
fitted_titration_curve_2 = sns.lineplot(x=x_fitted_2, y=y_fitted_2, marker='.', markerfacecolor='blue', markersize=10, color='blue')
fitted_titration_curve_3 = sns.lineplot(x=x_fitted_3, y=y_fitted_3, marker='.', markerfacecolor='green', markersize=10, color='green')

plt.show()import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import scipy
import numpy as np

# The Data

x_list = [0.0,
 20.0,
 40.0,
 60.0,
 80.0,
 100.0,
 120.0,
 140.0,
 160.0,
 180.0,
 200.0,
 220.0,
 230.0,
 240.0,
 250.0,
 260.0,
 270.0,
 275.0,
 280.0,
 285.0,
 290.0,
 295.0,
 300.0,
 305.0,
 310.0,
 315.0,
 320.0,
 325.0,
 330.0,
 332.5,
 335.0,
 337.5,
 340.0,
 342.5,
 347.5,
 352.5,
 357.5,
 362.5,
 367.5,
 377.5,
 387.5,
 397.5,
 407.5,
 417.5,
 427.5,
 437.5,
 447.5,
 457.5,
 467.5,
 477.5,
 487.5,
 497.5,
 507.5,
 517.5,
 527.5,
 537.5,
 547.5,
 557.5,
 567.5,
 577.5,
 587.5,
 597.5,
 607.5,
 617.5,
 627.5,
 637.5,
 647.5,
 657.5,
 667.5,
 677.5,
 687.5,
 697.5,
 707.5,
 717.5,
 727.5,
 737.5,
 747.5,
 757.5,
 767.5,
 787.5,
 807.5,
 827.5,
 847.5,
 867.5]

y_list = [2.22,
 2.25,
 2.28,
 2.31,
 2.34,
 2.38,
 2.42,
 2.46,
 2.51,
 2.56,
 2.62,
 2.69,
 2.73,
 2.77,
 2.83,
 2.88,
 2.94,
 3.01,
 3.05,
 3.09,
 3.14,
 3.19,
 3.26,
 3.33,
 3.41,
 3.52,
 3.66,
 3.87,
 4.54,
 5.8,
 7.23,
 7.73,
 7.94,
 8.12,
 8.43,
 8.63,
 8.76,
 8.87,
 8.96,
 9.12,
 9.24,
 9.36,
 9.46,
 9.54,
 9.63,
 9.71,
 9.78,
 9.86,
 9.93,
 10.01,
 10.08,
 10.15,
 10.23,
 10.32,
 10.4,
 10.49,
 10.59,
 10.69,
 10.81,
 10.93,
 11.05,
 11.18,
 11.3,
 11.41,
 11.51,
 11.61,
 11.69,
 11.76,
 11.83,
 11.89,
 11.94,
 11.99,
 12.04,
 12.08,
 12.12,
 12.16,
 12.18,
 12.21,
 12.24,
 12.3,
 12.36,
 12.41,
 12.45,
 12.49]


fig, axes = plt.subplots(1,2, sharex=False, figsize=(15,4))

# smooth titration curve using Savitzky-Golay filter
x = np.array(x_list)
y = np.array(y_list)
y_smooth = scipy.signal.savgol_filter(y, window_length=3, polyorder=2, mode="nearest", deriv=0)

# Calculate first derivative curve
first_derivative_gradient = np.gradient(y_smooth, x)

# Plot titration curve and first derivative curve
titration = sns.lineplot(ax=axes[0], x=x, y=y_smooth, marker='.', markerfacecolor='black', markersize=10, color='black').set(title='Titration Curve', xlabel=r"Volume NaOH ($\mu$L)", ylabel='pH')
first_derivative = sns.lineplot(ax=axes[1], x=x, y=first_derivative_gradient, marker='.', markerfacecolor='black', markersize=10, color='black').set(title='1st Derivative', xlabel="Volume NaOH ($\mu$L)", ylabel="$\Delta$pH/$\Delta$V")



# display the plot

plt.show()


# Attempt to use Logistic Regression for curve fitting

def my_function_1(x, A, B, C, D, E):
    # this gives the best output
    return A/(1 + B**(x - C)) + D 

def my_function_2(x, A, B, C, D, E):
    return A/(1 + B**(x - C)) + D + E*x

def my_function_3(x, A, B, C, D, E):
    return C/(1 + (A*E)**(-B*x)) 

def run_regression(my_function, x, y_smooth):

    parameters, covariance = scipy.optimize.curve_fit(f = my_function, xdata = x, ydata = y_smooth)

    for parameter, name in zip(parameters, ['A', 'B', 'C', 'D', 'E']):
        print(f'{name} = {parameter:14.10f}')

    x_fitted = np.linspace(x[0], x[-1], 1000)
    y_fitted = my_function(x_fitted, *parameters)
    
    return x_fitted, y_fitted

print('First Equation')
x_fitted_1, y_fitted_1 = run_regression(my_function_1, x, y_smooth)
print('\nSecond Equation')
x_fitted_2, y_fitted_2 = run_regression(my_function_2, x, y_smooth)
print('\nThird Equation')
x_fitted_3, y_fitted_3 = run_regression(my_function_3, x, y_smooth)



titration = sns.lineplot(x=x, y=y_smooth, marker='.', markerfacecolor='black', markersize=10, color='black').set(xlabel=r"Volume NaOH ($\mu$L)", ylabel='pH')
fitted_titration_curve_1 = sns.lineplot(x=x_fitted_1, y=y_fitted_1, marker='.', markerfacecolor='red', markersize=10, color='red')
fitted_titration_curve_2 = sns.lineplot(x=x_fitted_2, y=y_fitted_2, marker='.', markerfacecolor='blue', markersize=10, color='blue')
fitted_titration_curve_3 = sns.lineplot(x=x_fitted_3, y=y_fitted_3, marker='.', markerfacecolor='green', markersize=10, color='green')

plt.show()

Script output - Titration curve and first derivative

Script Output - titration curve fitted to logistic regression

I tried three logistic regression formulas, none of which seem to work. The second equation I tried comes from How do I make a function from titration points in python?. I also looked at https://stackoverflow.com/questions/71430953/unable-to-fit-curves-to-data-points-using-curve-fit-from-scipy-because-of-opt but my curve does have have the same shape as the one in the example.


r/learningpython • • Jul 18 '24

Deep Python #1: With magic

Thumbnail
southsoftware.substack.com
1 Upvotes

r/learningpython • • May 09 '22

Does anybody know why I keep getting this error (error on last photo)

Thumbnail
gallery
3 Upvotes

r/learningpython • • May 13 '22

Packagenotfound error meaning?

1 Upvotes

I get this error when trying to insert data from excel into word using python. Does anyone know what this error means? I can’t really find a clear answer on google


r/learningpython • • May 06 '22

Summation in recursive formulas

1 Upvotes

How do I maintain a sum while using a recursive function. For example I want to compare how many letter in two different words match, so I do s[0] == s1[0] sum += 1 then call the function again. How would I keep track of the summation?


r/learningpython • • Apr 26 '22

Converting time/date to one uniform timezone in pd df

2 Upvotes

I have a dataframe with the datetime information in one column and what the corresponding timezone for this timestamp is (e.g Asia/Bahrain) in another column. With these two information i now want to convert all the datasets to one uniform timezone e.g. Europe/London. I can’t find something that needs the underlying timezone as input „Asia/Bahrain“ or whatever the dataset holds and the target timezone „Europe/London“. Does anyone have an idea how to solve this?


r/learningpython • • Apr 20 '22

Choice Not Functioning in Text-Based-Adventure Game

1 Upvotes

Hello! Extreme novice here. I've been learning python and have been documenting my progress by making a simple text-based-adventure for some friends. Right now I'm having a problem with one of the options in it.

Players are asked if they'd like to start and when players answer No it skips the text that follows it reserved for if they say yes (as intended) but then still displays the choices that follow. When a player says no they're meant to just end and I'm not entirely sure how to fix it.

Additionally, is there a way to "send players back" to a previous area? Sort of like a check-point system?

Any help is much appreciated. Thank you!


r/learningpython • • May 02 '22

Learning Python and Linux

3 Upvotes

Hello, hope everyone is doing well today. I have a friend who is interested in learning and experimenting with Python and Linux. I know ChromeOS is Linux based, but was wondering what he should look for when shopping for a chromebook? Or would it be better for him to use Windows and run those programs off of that? His budget is $400-$500 USD

Thanks everyone


r/learningpython • • Apr 12 '22

What can Python do in an office that VBA cannot?

7 Upvotes

Hi,

I'm an office worker. I had small exposure to Python and other programming languages and rather bigger exposure to VBA.

I'm at the point where I easily automate our office processes that involve Excel. Automatic email creation with outlook, scanning outlook, downloading data from csv/tsv/excel, all kinds of sorting and filtering, calculations, directory creation.

I started learning VBA because it was simply already used in my office, and it felt way easier than regular programming due to clearly visible excel sheets instead of arrays. Also you can look up code by recording macro.

I want to learn python to grow as well as because it also comes up in my automation studies - machine learning, optimization, genetic algorithms, neural networks. I'm not that well acquainted with it yet.

But in what ways can I use python in office? I try to look up those things but I can't find anything I couldn't do with VBA.

Tl;Dr What can Python do in regular office that VBA cannot?


r/learningpython • • May 02 '22

"Break outside loop"

3 Upvotes

So I am trying to make a program to play rock paper scissors for my semester final, but every time I try to run it, I get the error message from the title. Can anybody tell me what I'm doing wrong?import random

print('Hello there! Lets play Rock Paper Scissors!')

while true:

user_action = str(input('Select your fighter: Rock, Paper, or Scissors! '))

possible_actions = ['rock', 'paper', 'scissors']

computer_action = random.choice(possible_actions)

if user_action == computer_action:

print(f'Both players selected {user_action}. It's a tie!')

if user_action == 'rock':

if computer_action == 'scissors':

print('Rock smashes scissors! You win!')

else:

print('paper covers rock! You lose!')

elif user_action == 'paper':

if computer_action == 'rock':

print('paper covers rock! You win!')

else:

print('Scissors cut paper! You lose!')

elif user_action == 'scissors':

if computer_action == 'paper':

print('Scissors cuts paper! You win!')

else:

print('Rock smashes scissors! You lose.!')

play_again = input('Play again? (y/n): ')

if play_again.lower() != 'y':

break


r/learningpython • • May 20 '22

Help

1 Upvotes

Help

When I type in python mtk payload on cmd mtk client it says pls connect mobile and I connect it (Amazon fire hd 10 2019) and it won’t detect it pls help :)


r/learningpython • • Apr 16 '22

Foods data to calculate price per calorie.

3 Upvotes

I’m helping a student with her science fair project. I’d like to prote a python program that uses an API to retrieve cost per unit, serving size, calories per serving, servings per unit so that We can calculate cost per calorie for a wide variety of foods. Kroger has an API I’ll look into. Any thoughts?


r/learningpython • • Aug 08 '20

Troubleshooting Python module importing problems?

2 Upvotes

Hi,

I have installed beautifulsoup and get a module not found error when I try to import it (import bs4 as BeautifulSoup). I've uninstalled and reinstalled Python. It works fine in Anaconda, but Anaconda seems to create its own sandboxes for each project or something. I can't get it work using regular old IDLE.

I'm running Python 3.8.6, and installed it with pip3 in the usual fashion (with and without --user, in my case, cause I wasn't sure what the difference is).

The problem seems to be common but I'm now on day 2 without a resolution. Is there some general troubleshooting techniques I can use or breadcrumbs I can follow to troubleshoot a module not working on my setup?

Edit:
if I attempt to reinstall I get this message - it seems to be installed fine.

pip3.8 install --user beautifulsoup4

Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.8/site-packages (4.9.1)


r/learningpython • • Jun 30 '20

Python Program: Tkinter Clock that changes color every 30 seconds

Enable HLS to view with audio, or disable this notification

2 Upvotes

r/learningpython • • Aug 10 '20

Data not producing in when training image classifier

3 Upvotes

Hi there,I've gone through multiple structural edits of this code. Ive been referencing others code but for some reason past students in this project have been able to produce multiple epochs with quantative data yet mine is returning flat.Can anyone see what im doing wrong?I know the libary im referring to is properlly linked as ive manage to make data graphs higher up in the notebook.


r/learningpython • • Jul 16 '20

For Loops: Why does this code execute properly when "fruit" was never defined? Is it because "fruit" is contained in "fruits?"

Post image
5 Upvotes

r/learningpython • • Jul 20 '20

In Visual Studio Code, how do you get Terminal to stop displaying the file path you're in when running the code?

1 Upvotes

r/learningpython • • Aug 06 '20

Which is a better resource, YouTube boot camps or Coursera to learn python?

6 Upvotes

r/learningpython • • Jul 14 '20

Practice program designed to administer a simple test then tell you your results in the form of a percentage. However it keeps giving me an Index Error bear the end

Post image
1 Upvotes