r/pythonhelp • • Mar 07 '21

HOMEWORK I need to create a number guessing game with a score.

3 Upvotes
#Imports
import random
import time
import os

def Main():
    file = open("score.txt","r")
    score = int(file.read())
    file.close()
    print("your current score is" , score)
    
    time.sleep(1)
    
    sides = int(input("How many sides do you wish your dice to have(Difficulty): "))
    if sides == 1:
        sides = 2
    guess = int(input("What do you think the role will be: "))
    
    time.sleep(1)
    
    print("\n\n\nyour dice roles are: \n")
    role = int(random.randint(1,sides))
    
    time.sleep(1)
    f = open("score.txt","w")
    if role == guess:
        print("your role is" , role , "and you are correct")
        score = score + sides*2
        score = str(score)
        f.write("0"+ score)
        f.close()
        Main()
    else:
        print("your role is" , role , "and you are incorrect" )
        if score != 0:
            score = score - sides
            score = str(score)
            f.write("0"+ score)
            f.close()
            Main()
        else:
            f.write("0")
            f.close()
            Main()

path = os.getcwd() + "/score.txt"
if os.path.exists(path):
    Main()
else:
    file1 = open("score.txt","w")
    file1.write("0")
    file1.close
    Main()

So, It works well, as long as a file exists with an integer value inside, whenever i try to create the file with "0" inside it doesn't write "0" it creates the file and everything but it wont write 0. Please help.


r/pythonhelp • • Mar 03 '21

error on visual studio code

3 Upvotes

I am using visual studio code and python 3.9.2 I'm quite new to this so I probably did something dumb :)


r/pythonhelp • • Feb 27 '21

Help!! I am stuck on writing a code for this question my teacher gave me!!! I have the first half completed!

3 Upvotes

Help!!! I am stuck on making a code for this image. I have the first half down, but the "countdown" and anything after that I'm struggling with. Im not sure how to countdown from a number that a user has to provide, then subtracting that value by one and forming it in the structure shown in the image. I need help on this ASAP cause its already late.


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

"-=" not working the way I want it to.

3 Upvotes

Hey all, I want to make a gambling game that doubles the amount of points you get that you bet.

But for some reason "-=" isn't working... Why? Here's my code.

import random
points = 100


def repeat():
    global points
    bet = input(f'Right now, you have {points} points.\nHow much do you want to bet?  ')
    yon = random.randrange(2)
    if yon <= 0:
        points -= bet
        print(f'\nOuch, you lost {bet} points...\n')
        repeat()
    elif yon >= 1:
        points += bet*2
        print(f'\nNice! You just gained {bet} points!\n')
        repeat()


repeat()

Help would be appreciated :)


r/pythonhelp • • Feb 03 '21

How to point to an IP of one service out of many services for the purpose of comparing it to a DNS address?

3 Upvotes

When I run:

for i in services.items:
if i.servicename == 'specific-service-name':
print("%s" % (i.status.service))

What is printed out is the status of that specific service, which looks like:

[{'hostname': None, 'ip': '10.10.100.100'}]

So, what I need to do is first check the service name, and if it is the specific service I need the IP from, then compare that IP (as seen in the list/dict above) to a DNS record I've gotten in another function. I'm not clear on how I would do that.


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

Sooo tell me why python taken screenshot is worse quality than with a software called greenshot? Any way to make python scrnshot better quality?

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 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 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 • • Oct 31 '20

'float' object is not subscriptable

3 Upvotes

Hey guys,

so I want to ge this code to run but I always get the error message: TypeError: 'float' object is not subscriptable because of the last line. X is a data frame with 3 columns and y is a data frame with one column both with date time index.

What am I doing wrong? Should I change the data input?

model = lr().fit(X, y)

summary_result = pd.DataFrame(columns = ['y_hat'])

yhat_list = [float(i[0]) for i in np.ndarray.tolist(model.predict(X))]


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 anyone plz help me with my project 🥺

Post image
3 Upvotes

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