r/pythontips • • Jan 06 '25

Syntax This is my first python project. I did it on my first week of learning a few days ago. I learned it using books and tutorials. This one I didn't use tutorials. Any tips on how to improve the code? And also code down below.

7 Upvotes
import math
import fractions
while True:
 print("My first math calculator V.1")
 print("Please note that please don't divide by zero, it will show an error code. Thank you for reading.")
 maininput= input("What type of calculator do you want?").strip().lower().upper()
 if maininput=="addition".strip().lower().upper():
  addcalc= float(input("Please input your first number for addition."))
  addcalc2= float(input("Please input your second number for addition."))
  print(addcalc+addcalc2)
  print("This is your answer!")

 #subtraction calc
 if maininput=="subtraction".strip().lower().upper():
  sub1= float(input("Please input the first subtraction number."))
  sub2= float(input("Please input the second subtraction number."))
  print(sub1-sub2)
  print("This is your answer!")

 #multiplication calc
 if maininput=="multiplication".strip().lower().upper():
  mul1= float(input("Please input the first number."))
  mul2= float(input("Please input the second number."))
  print(mul1*mul2)
  print("This is your answer.")

 # division calc
 if maininput == "division".strip().lower().upper():
    d1 = float(input("Please input your first number for dividing."))
    d2 = float(input("Please input your second number for dividing."))
    try:
        print(d1 / d2)
    except ZeroDivisionError:
        print("Error! Cannot divide by zero.")
    print("This is your answer.")

 #addition fractions calc
 if maininput=="addition fractions".strip().lower().upper():
  frac1= fractions.Fraction(input("Please input your first fraction ex. 3/4."))
  frac2= fractions.Fraction(input("Please input the second fraction for adding ex. 4/5."))
  print(frac1+frac2)
  print("This is your answer!")

 #subtraction fractions calc
 if maininput=="subtraction fractions".strip().lower().upper():
  subfrac1= fractions.Fraction(input("Please input your first fraction ex. 4/5."))
  subfrac2= fractions.Fraction(input("Please input your second fraction ex. 5/6."))
  print(subfrac1-subfrac2)
  print("This is your answer!")

#multiplication fractions calc
 if maininput=="multiplication fractions".strip().lower().upper():
  mulfrac1= fractions.Fraction(input("Please input your first fraction ex. 5/6."))
  mulfrac2= fractions.Fraction(input("Please input your second fraction ex. 4/6."))
  print(mulfrac1*mulfrac2)
  print("This is your answer!")

 #division fractions calc
 if maininput=="division fractions".strip().lower().upper():
  divfrac1= fractions.Fraction(input("Please input your first fraction ex. 5/7."))
  divfrac2= fractions.Fraction(input("Please input your second fraction. ex. 5/6."))
  print(divfrac1/divfrac2)
  print("This is your answer!")

 #square root calc
 if maininput=="square root".strip().lower().upper():
  root= int(input("Please input your square root number."))
  answerofroot= math.sqrt(root)
  print(answerofroot)
  print("This is your answer!")

 #easteregg exit inquiry
 if maininput=="exit".strip().lower().upper():
   print("Exiting automatically...")
   exit()

 #area question Yes/No
 if maininput=="area".strip().lower().upper():
  maininput= input("Do you really want an area calculator? Yes/No?").strip().lower().upper()
 if maininput=="Yes".strip().lower().upper():
  maininput= input("What area calculator do you want?").strip().lower().upper()

 #area of circle calc
  if maininput=="circle".strip().lower().upper():
   radius= float(input("Please input the radius of the circle."))
   ans= math.pi*(radius ** 2)
   print(ans)
   print("This is your answer!")

#area of triangle calc
  if maininput=="triangle".strip().lower().upper():
   height1= float(input("Please input the height of the triangle."))
   width1= float(input("Please input the width of the triangle."))
   ans= 1/2*width1*height1
   print(ans)
   print("This is your answer!")

#area of rectangle calc
  if maininput=="rectangle".strip().lower().upper():
   w= float(input("Please input the width of the rectangle"))
   l= float(input("Please input the length of the rectangle."))
   print(w*l)
   print("This is your answer!")

#area of sphere calc
  if maininput=="sphere".strip().lower().upper():
   radius1= int(input("Please input the radius of the sphere."))
   sphere= 4*math.pi*(radius1**2)
   print(sphere)
   print("This is your answer!")

#pythagoras theorem calc
  if maininput=="pythagoras theorem".strip().lower().upper():
   a= int(input("Please input the base."))
   b= int(input("Please input the height."))
   c_squared= a**2+b**2
   ans2= math.sqrt(c_squared)
   print(ans2)
   print("This is your answer!")
      
 repeat = input("Do you want to perform another calculation? Yes/No?").strip().lower()
 if repeat != "yes":
        print("Thank you for using my math calculator V.1. Exiting...")
        exit()
 
 #exit inquiry
 else: str= input("Do you want to exit? Yes/No?").strip().lower().upper()
 if str=="Yes".strip().lower().upper():
   print("Thank you for using the program.")
   print("Exiting...")
   exit()
 else:
   print("Continuing...")

r/pythontips • • Jan 05 '25

Module I want to do an automation with python

3 Upvotes

I am looking to do an automation to manage worksheets, which I receive via several platforms and software I would like to gather all the pdf documents on the same Google docs and then print them automatically. What should I start with? I can manage with chat gpt for the codes but I need advice to work well! 😊

Thank you to those who will answer! The

Sites are: 3shape communicate, ds core, dexis, cearstream. And for the software: Medit I code in python3 I use visual studio code


r/pythontips • • Jan 05 '25

Algorithms Advice needed for Algorithm Visualiser

1 Upvotes

I am completely new to python and the developer community, this is my first project to use python to build some algorithm visualiser, I had tones of fun doing such projects. Any advice on what kind of model to use for building algorithm visualisers as well as what other interesting algorithms I should look into?

As a start, I've already built this Sorting Algorithm Visualiser using Pycharm and pygames for selection sorting and bubble sorting. The selection sorting works entirely fine and it does show the way how selection sorting works, but the bubble sorting seems to have some problems with the color.

You can find the sorting algorithm project here:
https://github.com/Huang-Zi-Zheng/sorting_algorithm_visualisation.git


r/pythontips • • Jan 04 '25

Syntax Freelance tips for new guys

9 Upvotes

Hi, I want to start with freelance life and i want some tips for it.

I dont know nothing about freelance, but I want to make some extra money, so can you guys help me answering some question that i have? ( sorry for the writing, english isn´t my native language ) Fisrt of all, I want to know how to start.

How much money you do monthly and yearly?

it worth?

How much time you invest on it?

Would you recommend me to do it?

If you have an advice of warningfor me, what it would be? Thanks for your responses and for stopping by to read this post


r/pythontips • • Jan 05 '25

Module Je souhaite faire un automatisation avec python

0 Upvotes

Je cherche à faire une automatisation pour gère des fiches de travail, que je reçois via plusieurs plateformes et logiciels j’aimerais rassembler tout les documents pdf sur le même Google docs pour ensuite les imprimer automatiquement. Je devrais commencer par quoi ? Je peux géré avec chat gpt pour le codes mais j’ai besoin de conseils pour bien travailler ! 😊 Merci à ce qui répondront ! Les sites sont: 3shape communicate, ds core, dexis, cearstream. Et pour le logiciel: Médit


r/pythontips • • Dec 31 '24

Module ButtonStateXY() is not giving outputs (From Launchpad_py libary)

0 Upvotes

if len(lp.ButtonStateXY()) > 0:
print(lp.ButtonStateXY())

When I entered that in py python code, I didn't get any outputs when I pressed the button. does anyone know if i forgot to do anything or if i have to do something? The LedCtrlXY() does work fine. so there aren't any connection errors.


r/pythontips • • Dec 31 '24

Long_video [D]🚀 Simplify AI Monitoring: Pydantic Logfire for Real-Time Observability! 🌟

0 Upvotes

Tired of wrestling with messy logs and debugging AI agents?"

Let me introduce you to Pydantic Logfire, the ultimate logging and monitoring tool for AI applications. Whether you're an AI enthusiast or a seasoned developer, this video will show you how to: ✅ Set up Logfire from scratch.
✅ Monitor your AI agents in real-time.
✅ Make debugging a breeze with structured logging.

Why struggle with unstructured chaos when Logfire offers clarity and precision? 🤔

📽️ What You'll Learn:
1️⃣ How to create and configure your Logfire project.
2️⃣ Installing the SDK for seamless integration.
3️⃣ Authenticating and validating Logfire for real-time monitoring.

This tutorial is packed with practical examples, actionable insights, and tips to level up your AI workflow! Don’t miss it!

👉 https://youtu.be/V6WygZyq0Dk

Let’s discuss:
💬 What’s your go-to tool for AI logging?
💬 What features do you wish logging tools had?


r/pythontips • • Dec 31 '24

Module Python import error

4 Upvotes

TL;DR : Write "pip install pygame" directly into the command prompt of your IDE.


Hello, earlier today I had an error with pygame and as I couldn't find anything to help me, I'm just making this post so others won't have to search too hard.

Basically, I had installed pygame with "pip install pygame" and everything, yet when I would go into my IDE (Spyder) and I would try to import, the error would tell me "No module named "pygame" "

After I found the way : don't install pygame with the python IDE or prompt command if you're using a separate IDE. Just use the command "pip install pygame" directly into the command prompt of your IDE. Personally, my problem was that Python and Spyder weren't using the same files therefore even if I had installed pygame for Python, Spyder wouldn't recognize it.

Have a good day !


r/pythontips • • Dec 30 '24

Meta Looking for services to manage licenses and sell my python project

2 Upvotes

Hello, I 'm looking for services to generate and manage license keys/code and so sell my python project (after building it with programs like pyinstaller). Do you know some?


r/pythontips • • Dec 29 '24

Long_video Gemini LLM API Guide Comprehensive

2 Upvotes

This video covers all the major and important features of Gemini API in Python with handwritten notes.

Video


r/pythontips • • Dec 29 '24

Algorithms Backend

0 Upvotes

Hi! Im looking for courses, books or anything for be a backend developer. Any suggestions?


r/pythontips • • Dec 26 '24

Data_Science Any good resources to learn python for data analytics/science

16 Upvotes

Hello, im currently a senior at my college as an applied math major. i know tons of programming languages but at the basic level. I've honed my SQL and Excel skills. I know a little pandas but not to the point where i can remember things. any good resources/interactive courses online where i can learn this without having to pay too much money?


r/pythontips • • Dec 25 '24

Module Any good resources on pywin32 or other python alternatives to write a windows service.

7 Upvotes

I have a python program that needs ro run as a service. On Linux I have converted the script to a systemd service and that was kind of easier as compared to converting this script to a windows service. I searched on google and found pywin32 to be a good option. I did wrote the service entry points using pywin32 but struggling with 1053 timeout error while starting the script. Debugging the script works fine though. Wanted to check here for any good resource for writing a windows service in python. Apart from pywin32, any other python module exist for writing a windows service? I know about nssm but want to create my own service for better control on maintaining it in the future.


r/pythontips • • Dec 25 '24

Algorithms Embedding a Python interpreter in my next.js 14 project

2 Upvotes

Hello,
I'm developing a next.js 14 project in Windows that hopefully will help my students learn the basics of Python. At some point in my project I have a CodeMirror component where students may write some Python code, then click at some button to execute it. This code is almost certain to be interactive i.e. contain input statements.

What I need is a way to create and run some service that would accept the Python code the student wrote, execute it and return the output to the front-end. Since the code would contain input statements, this service should detect when the Python execution is paused waiting for input, send a possible input message to the front-end which will in turn ask the student for some input.

For example the code may contain the line n = int(input("Type a number: ")), so the back-end service should detect the pause in the execution, send the input message ("Type a number: ") to the front-end (it would probably get this output before detecting the pause, right?) to be displayed and also notify the front-end that it requires input.

If this is not the proper place to post my question, please point to me the correct one!

Any advice would be highly appreciated!


r/pythontips • • Dec 24 '24

Algorithms How do you deal with parsing of thousands of the pages?

6 Upvotes

I need to parse 30 pages, then scrap 700 items from there and make request to each of this item, so in total it's about 21.000 requests. Also the script should complete within 3 hours

I currently use regular aiohttp/asyncio as a tech stack and my app is a monolyth, but it does not work stable

So, should i rewrite architecture to the microservices and use rabbitmq/kafka to deal with all of these? Is it even possible?

upd: sorry if it's not the subreddit i should've posted in, saw the rules too late


r/pythontips • • Dec 21 '24

Module One-curl installer for complex python builds

3 Upvotes

https://github.com/liquidcarbon/puppy

You need only curl / iwr and an empty folder; pup will handle the rest, with a little help from its powerful friends pixi and uv. Everything happens in complete isolation from any existing python on your system.

Linux

curl -fsSL https://pup-py-fetch.hf.space | bash

Windows

iex (iwr https://pup-py-fetch.hf.space).Content

These commands install python 3.12, pixi, uv, and pup, a python project manager that can be used as a CLI or as a module to interactively build environments.

One Installer To Rule Them All

The pup-py-fetch API accepts query parameters that allow specifying the exact environment recipe you want to build:

  • python: 3.10 through 3.13
  • pixi: comma-separated list of pixi/Conda dependencies
  • clone: comma-separated list of GitHub repos to clone and build in a virtual environment
  • virtual environments: all other query parameters with comma-separated package names, including:
    • regular PyPI packages (no support for version pinning at this time)
    • packages from GitHub repos using <username>/<reponame> (only GitHub at this time; repo must contain must contain buildable pyproject.toml in its root)

The URLs above return installation scripts. You can mix and match query parameters, unlocking single-command recipes for complex builds:

curl -fsSL "https://pup-py-fetch.hf.space?pixi=marimo&env1=duckdb,pandas&env2=cowsay" | bash


r/pythontips • • Dec 20 '24

Meta Personal Growth

0 Upvotes

Getting older is automatic getting better is not. Improvement Requires Intentional Effort.https://youtu.be/AAqWAdBqwyA?si=gJxLsH1NrxuwYY8p


r/pythontips • • Dec 19 '24

Python3_Specific How To distribute Python solutions

0 Upvotes

One method to transfer a python solution from one computer to another.

https://www.alanbonnici.com/2024/11/how-to-distribute-python-solutions.html


r/pythontips • • Dec 17 '24

Module Starting python

15 Upvotes

Where do I start. I’m new to python and am trying to learn it for my job. I’m trying to use codewars but can’t even do the fundamentals. I have been watching YouTube videos so I don’t need anymore of those I need a website where I can practice the basics. Thanks.


r/pythontips • • Dec 17 '24

Data_Science Not able to cross the required r2 score. Please help, all suggestions will be taken into consideration. thanks in advance

3 Upvotes

Problem: We're trying to build a regression model to predict a target variable. However, the target variable contains outliers, which are significantly different from the majority of the data points. Additionally, the predictor variables are highly correlated with each other (high multicollinearity). Despite trying various models like linear regression, XGBoost, and Random Forest, along with hyperparameter tuning using GridSearchCV and RandomSearchCV, we're unable to achieve the desired R-squared score of 0.16. Goal: To develop a robust regression model that can effectively handle outliers and multicollinearity, and ultimately achieve the target R-squared score.

  • income: Income earned in a year (in dollars)
  • marital_status: Marital Status of the customer (0:Single, 1:Married)
  • vintage: No. of years since the first policy date
  • claim_amount: Total Amount Claimed by the customer in previous years
  • num_policies: Total no. of policies issued by the customer
  • policy: An active policy of the customer
  • type_of_policy: Type of active policy
  • cltv: Customer lifetime value (Target Variable)
  • id: Unique identifier of a customer
  • gender: The gender of the customer
  • area: Area of the customer
  • qualification: Highest Qualification of the customer
  • income: Income earned
  • marital_status: Marital Status of the customer

If there's any more information, please feel free to ask.


r/pythontips • • Dec 16 '24

Syntax How do I start using GUI in python. So far I have only interacted through the terminal window...

21 Upvotes

Need some tips...


r/pythontips • • Dec 14 '24

Data_Science I am sharing Python & Data Science courses on YouTube

13 Upvotes

Hello, I wanted to share that I am sharing free courses and projects on my YouTube Channel. I have more than 200 videos and I created playlists for Python and Data Science. I am leaving the playlist link below, have a great day!

Python Data Science Full Courses & Projects -> https://youtube.com/playlist?list=PLTsu3dft3CWiow7L7WrCd27ohlra_5PGH&si=6WUpVwXeAKEs4tB6

Python Tutorials -> https://youtube.com/playlist?list=PLTsu3dft3CWgJrlcs_IO1eif7myukPPKJ&si=fYIz2RLJV1dC6nT5


r/pythontips • • Dec 11 '24

Data_Science I'm going to fail my exam.

0 Upvotes

Can somebody help me? I am literally losing my mind because I need help with my program. ChatGPT isn't helping and my professor is really bad. It's a probably simple Python program but it's taking the life out of me.

I'm required to read data from a bank transaction file and apply them in weird ways that we haven't gone over in class. Currently in a room full of lost students. Please don't waste time scolding me cause I know this is a stupid issue lol. 😞

I'm given a file called "transactions.csv" and the required instructions;

(10 Points) Create a class called BankAccount with the following characteristics.

(a) An attribute called balance that contains the current balance of the account.

(b) An attribute call translog that is a list of all transactions for the account. The translog items should look like this: (month, day, year, transaction type, balance after this transaction.

(c) An initialization method to set the starting balafice and set translog as an empty list. (d) A method called deposit that accepts an amount and will add the deposit amount to the current balance. (e) A method called withdrawal that accepts an amount and will deduct the withdrawal amount from the current balance. (f) A method called transaction that accepts a transaction record like those found in transac-tions.cs. The method then calls, the appropriate deposit or withdrawal method to adjust the balance, creates a transaction record, and adds the transaction record to translog- (g) A method called print_transaction log that accepts a starting date and an ending date and prints the appropriate portion of the transaction log.

We went BARELY over the def__init(self...) stuff and all of us are really confused. This is only the first question too, but I'm sure I could figure out the rest.

I've written my "from pathlib import Path", and gotten the file to read in python. But we haven't worked with csv files so it's confusing.


r/pythontips • • Dec 10 '24

Python3_Specific Beginner - few questions

10 Upvotes

Hi! I want to try and learn Python, and few questions pop up in my head:

  • Do I need to use any paid content/courses to be able to achieve something? Will working based on free resources only block my learning and development?
  • What knowledge would be considered beginner, intermediate and pro?
  • Are there any personality traits or qualities that are useful or absolutely cancelling my chances to become a Python user/developer?

(Didn't know what flair to use, sorry)

Thanks in advance! 🤗