r/pythonhelp • • Feb 25 '21

New to python and having a simple error can’t figure out how to implement a system where it displays a error message when the value the user enters is less than a set number.

3 Upvotes

Basically what I’m doing is a scrap code to try learn some new skills in python and I’ve been doing trial and error for like 1h tryna figure this out now and it’s getting really annoying so I thought to come ask. So my code will more than likely have formatting errors here due to me having to send it from my phone so please just ignore the formatting errors in my python screen the formatting is all correct it my code goes as follows.

Def choice1(number): Input(‘enter your choice’)

Def your_wage(number): Print(‘how much do you earn a week’)

Def your_age(number) Print(‘how old are you’)

Def your_job(string) Print(‘what job do you currency have)

Def your_education(alpha numberic) Print(‘what is your highest form of education’)

Print(‘ ‘, ‘#’*27’) Print(‘ #’) Print(‘ # 1)your wage. #’) Print(‘ # 2)your age. #’) Print(‘ # 3)your job. #’) Print(‘ # 4)your education. #’) Print(‘ # 5)quit. #’) Print(‘ #’) Print(‘ ‘,’#’*27) Print(\n\n\n’) Choice=int(input(‘enter your choice’)) If choice==1: Print(your_wage) Elif choice==2: Print(your_age) Elif choice==3: Print(your_job) Elif choice==4: Print(your_education) Elif choice==5: Print(‘quit’) Else: Print(‘invalid number’)


r/pythonhelp • • Feb 10 '21

INACTIVE Can't upgrade pip

3 Upvotes
(s) C:\Users\itama\PycharmProjects\app>pip install --upgrade pip
Collecting pip
  Using cached pip-21.0.1-py3-none-any.whl (1.5 MB)
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 20.2.4
    Not uninstalling pip at c:\users\itama\appdata\local\programs\python\python38-32\lib, outside environment c:\users\itama\pycharmprojects\app\s
    Can't uninstall 'pip'. No files were found to uninstall.
  WARNING: Failed to write executable - trying to use .deleteme logic
Successfully installed pip-21.0.1
WARNING: You are using pip version 20.2.4; however, version 21.0.1 is available.
You should consider upgrading via the 'c:\users\itama\pycharmprojects\app\s\scripts\python.exe -m pip install --upgrade pip' command.

I also tried to do the command that it suggests but it shows the same results


r/pythonhelp • • Feb 01 '21

I know my fundamentals, I know one must indent in python, what I don’t know is what I’m doing wrong...

3 Upvotes

r/pythonhelp • • Jan 30 '21

Python Newbie, Can someone please help me with the error on line 37?

Post image
3 Upvotes

r/pythonhelp • • Jan 27 '21

I installed a python package using pip3 on linux and now cant figure out how to actually launch it

3 Upvotes

I'm using Linux mint, I've got python 3 installed and I used pip3 from the terminal to install a scraping tool from GitHub, its telling me its installed successfully but I cant figure out how to actually find and run the program

I'm sure I'm overlooking something very simple, any help would be greatly appreciated.


r/pythonhelp • • Jan 14 '21

SOLVED How to Iterate through a list of tuples in python?

3 Upvotes

I have a list of tuples that contain coordinates, for example :

list = [(9,8),(65,8),(66,12),(12,58),(33,54),(12,32),(11,56),(66,12),(32,55)(85,21),(22,77),(51,420)]

I want to iterate through this list and calculate the distances between the consecutive coordinates, in return calculating the distance of the path plotted by these coordinates.


r/pythonhelp • • Jan 12 '21

Need help with loop (beginner)

3 Upvotes

Hi! I need help fixing my coding to make my investment amounts follow a loop/show accumulated interest and so on. Here are more specific instructions with an example of what the output should look like

def futureval():
	# Read from the keyboard: amount, interest rate, periods
	# read the amount (principal)
	P: float = float(input('Please enter the amount to invest: $'))
	rate: float = float(
	    input('Please enter the interest rate per period, with no %: '))
	periods: int = int(input('Please enter the number of periods: '))
	fixed: int = int(
	    input('Please enter the amount you want to invest each period: $'))
	# Print out the initial parameters
	print('Investing $', P, 'at', rate, "% for", periods, "months at $", fixed,
	      'a month')
	# Adjust the rate from a percentage to a raw number
	rate = (rate) / 100

	# Calculate and print out the investment table
	# Print a header row
	print('Period\tInterest\tPlus interest\tIncrement\tAmount')
	# Print the starting amount
	print('Initial\t\t\t\t\t\t\t\t\t\t\t$', round(P, 2))
	# Print out the table, row by row
	for i in range(periods):
		#Add the fixed amount
		Increment = fixed
		# Calculate the interest
		interest = P * rate
		# Add the interest back into the principal
		P = interest + P
		#Calculate total amount
		Amount = P + fixed
		interest = Amount * rate

		# Print the table row
		print((i + 1), '\t\t\t$', round(interest, 2), '\t\t$', round(P, 2),
		      '\t\t$', round(Increment, 2), '\t\t$', round(Amount, 2))


if __name__ == "__main__":
	import sys
	futureval()

r/pythonhelp • • Jan 10 '21

Need help with this question

3 Upvotes

Hey, I've got this question and I'm not sure how to approach it:

Given a list of numbers and a number called 'initial_sum', the function (called 'culmulative_sum(lst, initial_sum=0)') calculates recursively the cumulative sum of each index with the initial_sum and returns a list of the cumulative sums of each index of the list.

For example, if the input is: [0, 1, 2, 3, 4], 0
The function will return: [0, 1, 3, 6, 10]
Explanation: the 4th element is 6 because 0+0+1+2+3=6

if the input is: [2, 0, 0, 0, 2], 1
The function will return: [3, 3, 3, 3, 5]
Explanation: the 3rd element is 3 because 1+2+0+0=3

Notes: the function has to work recursively, and the time complexity has to be O(n), where n is the length of the list.

Any help?


r/pythonhelp • • Jan 07 '21

SOLVED Why isnt it defined

Post image
3 Upvotes

r/pythonhelp • • Jan 04 '21

I’m making a blackjack script but code can’t use “>” . Changing my inputs to int(input hasn’t worked. I checked and it does add up the numbers, for example if I get a 9 of hearts, 7 of diamonds it correctly adds to 16 but I still get the error. Can someone help?

Post image
3 Upvotes

r/pythonhelp • • Dec 15 '20

I am trying to make a bot that adds a role for when a new user and its not working. please help

3 Upvotes

I am trying to make a bot that adds a role for when a new user is added I got as far as this but it does not seem to be working. Any ideas?

Here is my code:

https://imgur.com/a/b1xFhl2


r/pythonhelp • • Dec 09 '20

I have a cool challenge if you want to try (its makes you think!)

3 Upvotes

SADDER SNAKES PYTHON 2 CHALLENGE

OBJECTIVE: Create a Python program that will replace all vowels in a string with a character specified by the user.

REQUIREMENTS:

  1. Create a Python program in Sandbox entitled “Replace Vowels”.

  2. Add the following for user input:

    1. Ask the user for string and store string in variable

    2. Ask the user for a character to replace the vowels in string. Length of character should only be 1. 

      1. Repeatedly ask user for character until length is 1. Print error message if length is not 1.

    3. Create a function named replace_vowels that will replace all vowels in the user string with the character that user provided.

      1. Function should receive two parameters: user string and replacement character.

      2. Replace all vowels with the replacement character.

      3. Count the number of vowels replaced.

      4. Print the count with the message “Total vowels replaced is “

      5. Return the modified string

    4. Call replace_vowels() function with the user string and replacement string

    5. Print the updated string - Good luck , sadder snakeYT


r/pythonhelp • • Dec 07 '20

Python Homework Help Please

3 Upvotes

The code I need to write needs to meet these criteria:

Regular servicing will keep your vehicle more reliable, reducing the chance of breakdowns, inconvenience and unnecessary expenses. In general, there are two types of service you need to

perform:

a. a minor service every 6000 miles

b. a major service every 12000 miles

Write a Python program that prompts the user to enter the miles traveled, and then calculates and displays how many miles are left until the next service, as well as the type of the next service.

Ex:

Enter miles traveled: 21600

Your car needs a major service in 2400 miles.


r/pythonhelp • • Nov 22 '20

I just need to change the tick frequency or stepsize

3 Upvotes

The default is 3 hours and I would like 15-30 minute intervals

style.use("ggplot") start = dt.datetime(2019,4,24) end = dt.datetime(2019,4,25) df = web.get_data_yahoo("TSLA", start, end) df["Adj Close"].plot() plt.title('Tesla Price v. First Quarter Earnings 2019') plt.ylabel('USD') plt.show()


r/pythonhelp • • Nov 16 '20

Counting atoms with python

3 Upvotes

I wish to calculate partial charge in complex (im a chemist)

So my problem is that i have a list : ['H2O','OH','COOH'] for exemple

I need to know the number of occurrences of all atoms. So here 4 for H. My problem is that the number of occurrences is the number of occurrences of the letter describing the atom if no stoechiométric coefficient, and else the number of that coefficient, but the number could appear or not at any place except at position 0.

I don't see how can i make this with python and now i'm quite confused.

Do you have any tips for me?

Thanks for your help and time!


r/pythonhelp • • Nov 09 '20

Shutdown MacOS with Python script?

3 Upvotes

Hi. I'm very new to Python and don't know much about it. I created a script to mess with my friend and I don't know how to get it to work. I want to make it so that the Mac shuts down after the countdown but it doesn't seem to be working. Here's the code.

import time

import subprocess

shutdown = input("Do you wish to go on an epic adventure? (y/n) ")

if shutdown == 'no':

print('\nYour loss, pal.')

exit()

else:

seconds = 3

print('Alright! You ready?')

for i in range(seconds):

print(str(seconds - i)

time.sleep(2):

subprocess.call(['osascript', '-e',

'tell app "System Events" to shut down'])

Any help would be useful. Thanks.


r/pythonhelp • • Nov 03 '20

When I integrate a function using Sympy it returns a Zero

3 Upvotes

I wrote this code to find the reaction fraction process in a tubular chemical reactor.

from sympy.interactive import printing
from sympy import Limit, limit, Symbol, S
from sympy import Integral, integrate
printing.init_printing(use_latex='mathjax')
f = Symbol('f')

def frac(fx,V,Q):
    gfx=[]
    for i in range(0,100):
        ff=i/100
        n=[Integral(fx, (f,0.0,ff)).doit(),ff]
        gfx.append(n)
    c=0
    for i in gfx:
        if i[0]<=(V/Q):
            c=c+0.01
    return(c-.01)
V=90
Q=17
K=0.0554
cde=4.897
fx=(-cde/(-K*(cde*(1-f))**2))
fr=frac(fx,V,Q)

How you can see, the list who saves the integrated values all are zeros, I was trying using SymboLab and Wolfram Alpha and all of them give others values different from zero.

Why Sympy give me a wrong integration with this function and these values?


r/pythonhelp • • Nov 01 '20

Cvs file and scatter plot

Thumbnail
gallery
3 Upvotes

r/pythonhelp • • Oct 30 '20

I dont really understand the logic of the question and the steps I should take so any help is appreciated

3 Upvotes

Write a function translate(string) that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. Write a main function to test it.


r/pythonhelp • • Oct 30 '20

Can someone tell me why it misses out the line for the row “A” and how the remaining letters are on the wrong side? (Should be in line with “A”) Thanks

Post image
3 Upvotes

r/pythonhelp • • Oct 28 '20

Live Write to File with Code That is Reading File and Writing to Serial Port - Python

3 Upvotes

Currently have a code that takes in a .txt file and submits commands to the serial. Then it reads the reply from the serial port and writes it to a hard coded .txt file. The problem is it doesn't save it live and so if I need to stop the code for any reason, I can't gather current data and the text file is blank. I'm not as familiar with buffering and things like that and tried "outputFile = open("./outputFile.txt", "a", 0)" but that gave me the error "can't have unbuffered text I/O” in python 3?" so I'm not sure what to do. Here is the general layout if you would like to mess around with it:

```

with open(test_file) as file_test:

Lines = file_test.readlines()

for line in Lines:

#send_str is the command to send to the serial port

send_str = line

file_result.write(line + "\n") #<--- if I were to cancel out after this it wouldn't be saved(*)

ser.write(send_str.encode('utf-8'))

time.sleep(send_pause)

reply_str = ser.readline().decode('utf-8').strip()

file_result.write("reply:" + reply_str + "\n") #<---(*)

file_result.write('\n') #<---(*)

```

anything helps thank you in advanced


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 21 '20

Need hlep.Plz. :)

3 Upvotes

Im a beginner and im watching a lot of tutorials there's one that I really liked it is about creating a pygame for beginners, I chose falppy bird. So I started and the first step was to install a pygame. It told me to go on Command Prompt and write this:py -m pip install pygame. I did that but its giving me this message:

ERROR: Command errored out with exit status 1:

command: 'C:\Users\user\Documents\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\user\\AppData\\Local\\Temp\\pip-install-fbs2xk25\\pygame\\setup.py'"'"'; __file__='"'"'C:\\Users\\user\\AppData\\Local\\Temp\\pip-install-fbs2xk25\\pygame\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\user\AppData\Local\Temp\pip-pip-egg-info-wmjnlqip'

cwd: C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\

Complete output (17 lines):

WARNING, No "Setup" File Exists, Running "buildconfig/config.py"

Using WINDOWS configuration...

Download prebuilts to "prebuilt_downloads" and copy to "./prebuilt-x64"? [Y/n]Traceback (most recent call last):

File "<string>", line 1, in <module>

File "C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\setup.py", line 194, in <module>

buildconfig.config.main(AUTO_CONFIG)

File "C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\buildconfig\config.py", line 210, in main

deps = CFG.main(**kwds)

File "C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\buildconfig\config_win.py", line 576, in main

and download_win_prebuilt.ask(**download_kwargs):

File "C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\buildconfig\download_win_prebuilt.py", line 302, in ask

reply = raw_input(

EOFError: EOF when reading a line

----------------------------------------

ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.