r/pythonhelp • • Apr 02 '22

I need assistance for coding for python

0 Upvotes

When I copied a piece of code from my old laptop to my new desktop computer it wouldn't work in VS Code because "%s" would come up blue and on my old laptop it would be orange.

webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe -profile-directory="Profile 1" %s').open(url)

This was the code that wasnt working.


r/pythonhelp • • Feb 22 '22

Issue with URL pasting in Python

0 Upvotes

Hey there, so recently I've been trying to make a Youtube Video Downloader, and for some reason when I input a FULL url it shows an error that goes something like: File "c:\Users\User\OneDrive\Desktop\The Youtube Video Downloader.py", line 10, in <module> video = YouTube(url)

Anyways Here Is The Script:

from pytube import YouTube

import time

print("The Youtube Video Downloader")

time.sleep(0.2)

print("\nBy: ViridianTelamon.")

time.sleep(0.2)

#url = input("\nInput The Full Url For The Youtube Video That You Want To Download (Shortened Urls Will Not Work): ")

url = input("\nInput The Url For The Video: ")

#print(f"Url Inputted: {url}")

#print(url)

video = YouTube(url)

time.sleep(0.2)

print("\n----------Video Title----------")

time.sleep(0.2)

print(video.title)

time.sleep(0.2)

print("\n----------Video Thumbnail Url----------")

time.sleep(0.2)

print(video.thumbnail_url)

time.sleep(2)

print("\n----------Video Download----------")

time.sleep(0.2)

video = video.streams.get_highest_resolution

video.download()

print("\nVideo Successful Downloaded In The Same Directory As This Script.")


r/pythonhelp • • Mar 14 '22

Pi Pico and Gyroscope GY-521

0 Upvotes

I am requiring assistance on how to code a Pi Pico and Gyroscope Gy-521 to control the computer mouse. I am using Thonny and adafruit.


r/pythonhelp • • Apr 07 '22

Cant figure out discord bots.

0 Upvotes

I'm trying to make a discord bot but it won't work. I took the code from a website that's meant to help but it won't work for some reason, here's the code:

# bot.py
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
client.run(TOKEN)


r/pythonhelp • • Aug 01 '24

could someone figure out why my limit doesn't work?

0 Upvotes

numGus and numAtt are the limits. basically the user enters the amount of attempts they want to have and then the code gives them that many attempts to guess a random number from a range of their choosing. (the random number part works fine) any help would be greatly appreciated. excuse the messy code

=======================================================================

import turtle

screen = turtle.Screen() #sets the background to a preselected image

screen.bgpic("Screenshot 2024-07-22 133150.png")

print ("WELCOME TO THE NUMBER GUESSING GAME.")

import random

playAgain = input("Do u wanna play a game(Y or N)") #asks the user if they want to play the game

numAtt = +1 #the number of guesses allowed

numGus = 0 #the number of allowed guesses

while numAtt != numGus:

while playAgain.lower() == ("y"):

numMin = 0 #the start of the range for random numbers

numMax = 0 #the end of the range for random numbers

attempt = 0 #the number of tries it takes for the user to guess the correct number (displayed once number is guessed)

numUse = 0 #the number that the player enters as a guess

numAtt == numGus #tells code that numAtt is equal to numGus

numGus=int(input("how many attempts do you want?"))

numAtt=int(input("how many attempts do you want?")) #the user inputs the amount of attempts that they want to have

numMin=int(input("Minimum number")) #user inputs the number for the start of the range

numMax=int(input("Maximum number")) #user inputs the number for the end of the range

numHid = random.randint(numMin, numMax) #numHid is the random number

print("what is your guess from " + str(numMin)+ " to " + str(numMax)) #asks the user what their guess is from the start of the range to the end of the range

while numHid != numUse: #puts user in a loop until they get the correct answer

numUse = int(input("enter your guess:"))

attempt = attempt + 1

if numHid>numUse:

print ("too low, guess higher")

if numHid<numUse:

print ("too high guess lower")

if numHid == numUse:

print ("well done!")

print ("Attempts: "+str(attempt))

playAgain = input("Wanna play again (Y or N)") #asks the user if they want to play the game again

else:

print ("try again")

the code checks to see if the numHid is higher or lower than numUse

if numHid is higher than numUse it tells the user that their guess is too high and that they should guess lower

alternatively if numHid is lower than numUse it tells the user that their guess is too low and that they should guess higher

if playAgain.lower() == ("n"): #if the user types "n" it prints goodbye and ends the game

print("goodbye")

if numAtt == numGus: #if the number of attempts is equal to the number of guesses allowed it ends the code

print("goodbye")


r/pythonhelp • • Jul 19 '24

Beginner in python NEED someone

0 Upvotes

Hi, Im from spain and im starting to use python for my job. I must learn how to progam a code to search instagram accounts including filtrers, I tried using chatgpt and other ias but I couldn't manage to have success. So is thereanyone that have the knowledge to do it? My goal is to generate a list of accounts that have on their usernames certain words and also a minimum and maximum of followers


r/pythonhelp • • Jul 17 '24

Python script to fetch zip codes within a radius fails to populate CSV correctly

0 Upvotes

SOLVED: Fixed, Updated to GitHub https://github.com/hlevenberg/radiuszip

Hi team, I am trying to write a Python script that reads a CSV file with zip codes, fetches zip codes within a radius using an API, and then populates the results into a new column in the CSV. The API requests seem to be working correctly, and I can see the responses in the console output. However, the resulting CSV file does not have the expected values in the radius_zips column.

Here is my current script:

import pandas as pd
import requests

# Define the file paths
input_file_path = 'test_zips.csv'  # Located on the Desktop
output_file_path = 'test_zips_with_radius_zips_output.csv'  # Will be saved on the Desktop

# Define the API details
url = "https://zip-code-distance-radius.p.rapidapi.com/api/zipCodesWithinRadius"
headers = {
    "x-rapidapi-key": "your_api_key",
    "x-rapidapi-host": "zip-code-distance-radius.p.rapidapi.com"
}

# Read the CSV file
df = pd.read_csv(input_file_path)

# Function to get zip codes within a radius for a given zip code
def get_radius_zips(zip_code, radius="10"):
    querystring = {"zipCode": zip_code, "radius": radius}
    try:
        response = requests.get(url, headers=headers, params=querystring)
        response.raise_for_status()
        data = response.json()
        print(f"Response for {zip_code}: {data}")  # Print the full response
        if 'zip_codes' in data:
            zip_codes = [item['zipCode'] for item in data]
            print(f"Zip codes within radius for {zip_code}: {zip_codes}")
            return ', '.join(zip_codes)
        else:
            print(f"No zip codes found for {zip_code}")
    except requests.exceptions.RequestException as e:
        print(f"Error fetching data for zip code {zip_code}: {e}")
    except ValueError as e:
        print(f"Error parsing JSON response for zip code {zip_code}: {e}")
    return ''

# Apply the function to the total_zips column and create the radius_zips column
def process_total_zips(total_zips):
    zip_codes = total_zips.split(', ')
    radius_zip_codes = [get_radius_zips(zip.strip()) for zip in zip_codes]
    radius_zip_codes = [z for z in radius_zip_codes if z]  # Filter out empty strings
    return ', '.join(radius_zip_codes) if radius_zip_codes else ''

df['radius_zips'] = df['total_zips'].apply(process_total_zips)

# Write the modified DataFrame to a new CSV file
df.to_csv(output_file_path, index=False)

print("The new CSV file 'test_zips_with_radius_zips_output.csv' has been created.")

When I run that in my terminal, it returns this (below)

Response for 01002: [{'zipCode': '01002', 'distance': 0.0}, {'zipCode': '01003', 'distance': 3.784731835743482}, ... {'zipCode': '01088', 'distance': 9.769750288734354}]

No zip codes found for 01002

Clearly this is working, but it's not printing inside of the output CSV. Any reason why?


r/pythonhelp • • Aug 05 '24

Dividing two histograms

0 Upvotes

I am trying to divide the data from two histograms, one that is a total of all the data and one that is a sample from the entire data.

My code is

Satellite Redshift histogram:

set binwidth

binwidth = 0.01

hist2, bins, patches = plt.hist(sat_z, bins=np.arange(0., max(sat_z) + binwidth, binwidth), facecolor = 'red')

plt.title('Satellite Redshift Histogram')

plt.xlabel("Redshift 'z'")

plt.ylabel("Population Density")

plt.show()

Satellite Total Histogram

binwidth = 0.01

hist3, bins, patches = plt.hist(z_spec, bins=np.arange(0., max(sat_z) + binwidth, binwidth), facecolor = 'green')

plt.title('Total Redshift Histogram')

plt.xlabel("Redshift 'z'")

plt.ylabel("Population Density")

plt.show()

plt.hist(hist2/hist3, bins, facecolor='green')

Any help would be greatly appreciated


r/pythonhelp • • Jan 30 '20

Docstring help

0 Upvotes

What will be the docstring for this

def calc_project(project_grade, project_weight): return project_grade * project_weight


r/pythonhelp • • Dec 14 '17

Am I doing something wrong?

0 Upvotes

I'm working through some problems on a site calledexercism.io, and essentially I have to check whether a word is an isogram or not.

Here is the solution I have.

Here is the class I'm testing it against.

I'm really at a loss on what I've done incorrectly. Could anyone shed some light? Thank you.


r/pythonhelp • • Nov 02 '21

SOLVED Beginner in need of guidance

0 Upvotes

Hi,

i am new to python and i just got some homework where i have to make a calculator where the user can choose the operation (+,-,/,*, or a random combination of all) and is given 10 calculations and he has to write in the correct answers. The numbers have to be random and the user can choose the difficulty (1 where the numbers are up to 10; 2) 1-25; 3) 1-100; 4) 1-1000). I was wondering if someone can help me shorten my code.

import random
num1 = random.randint(1,10)
num2 = random.randint(1,10)

rac = str(num1) + " + " + str(num2) + " = "
c= input(rac)
if c == "":
print("Goodbye!")
else:
c = int(c)
if c == num1 + num2:
print("Good, correct!")
else:
print("Wrong answer")
print(rac, num1 + num2)
print()

The problem is that I have to repeat this proces x10 for the 10 calculations and x4 because of the different difficulty of the numbers (1-4). And then i have to do the sam thing for -, /, *.


r/pythonhelp • • Nov 18 '21

HOMEWORK Python exercise

0 Upvotes

Hello,

I've got the following question in my programming class, but have no idea how to solve this. (I know this is A easy question for you....) Could anyone kindly explain this with a solution ?

Fill in the gaps in the Python code, so that it returns the following output : [2, -5, 1, -3, 7]

d = {1: 2, 🔲: 4, -5:🔲, 2: 0, 🔲:🔲 }   
a = [0, 0, 0, 0, 0]  
    
for k in d:               
    v = d[k]              
    a[v] = k      

print(a)

r/pythonhelp • • Nov 18 '21

HOMEWORK Python exercise

0 Upvotes

Hello,

I've got the following question in my programming class, but have no idea how to solve this. Could anyone kindly explain this with a solution ?

The following Python code fills an empty dictionary d step-by-step with information on how often each letter appears in tuple t and then returns the results as seen at the end. Fill in the gaps [ ]:

d = {}

t = ('M', 'I', 'S', 'S', 'I', 'S', 'S', 'I', 'P', 'P', 'I')

[ ] b in t:

if b not in :

d[b] = 1

[ ] :

d[b] = d[b] + [ ]

[ ] b, a [ ] d.items():

print ("t includes {} {}".format( [ ], [ ]))

Output:

t includes 1 M

t includes 4 I

t includes 4 S

t includes


r/pythonhelp • • Nov 07 '21

Python assignment: csv files

0 Upvotes

"Reads, row by row, the excerpt of the Hotel Selling Prices dataset in the file Hotel_Selling_Prices.csv and
prints within Python and writes to a new file all247_Hotel_Selling_Prices_Calculations.csv the following items
for the Los Angeles Market: the average number of floors, the maximum number of rooms, the minimum land area square feet, and the number of properties where the year built was 1980 or later."

Can someone please help me with the code. I can't use pandas for this assignment.


r/pythonhelp • • Nov 11 '21

Unindent does not match any outer indentation level

0 Upvotes

I'm making aprogram that takes a text file and generates a dictionary where the keys are the words and the values are the number of occurrences of each word.

However when I run the program it either switches between IndentationError: unindent does not match any outer indentation level or UnboundLocalError: local variable 'word' referenced before assignmentwhen I add or remove indentations from one part of the program.

I've seen others face similar issues and they suggested replacing spaces with tabs, but I've tried that and the error persists. Why does it not just work??


r/pythonhelp • • Nov 18 '21

HOMEWORK Create a Procedure to Calculate and Return the Sum of All of the Odd Numbers

0 Upvotes

Instructions: Complete lines 1 and 2 below to create the code to add up all the numbers from 1 to 5 and print the sum.

This is what I have so far can someone help me fix the errors I'm having trouble doing so.

sum =

thingsToAdd =

for number in thingsToAdd:

sum = sum + number

print(sum)


r/pythonhelp • • Mar 15 '24

can someone please explain what these two code pieces do

0 Upvotes

hi guys what is the difference between these

j = 1

while j <= 10:

print('hi')

j += 1

AND

i = 0

while i < 10:

i += 1

print('hi')

thanks guys.


r/pythonhelp • • Mar 02 '24

Hey why my code dosen't work

0 Upvotes

import pyautogui

import time

def get_pixel_color(x, y):

"""

Obtient la couleur d'un pixel spécifique sur l'écran.

Args:

- x (int): La coordonnée x du pixel.

- y (int): La coordonnée y du pixel.

Returns:

- color (tuple): Un tuple contenant les valeurs RGB du pixel.

"""

# Capturer la couleur du pixel spécifié

color = pyautogui.pixel(x, y)

return color

if __name__ == "__main__":

# Coordonnée x du pixel à scanner

x_pixel = 100

# Liste des coordonnées y à scanner

y_pixel = 100 # Vous pouvez étendre cette liste autant que nécessaire

# Couleur à détecter

target_color = (255, 57, 57)

while True:

for y_pixel in y_positions:

# Obtenir la couleur du pixel spécifié

pixel_color = get_pixel_color(x_pixel, y_pixel)

# Vérifier si la couleur du pixel correspond à la couleur cible

if pixel_color == target_color:

print(f"La couleur du pixel ({x_pixel}, {y_pixel}) est : {pixel_color}")

# Continuer à scanner la couleur si elle change

while True:

new_color = get_pixel_color(x_pixel, y_pixel)

if new_color != target_color:

# Si la couleur change, effectuer un clic droit

pyautogui.click(button='right')

break

time.sleep(0.5) # Attendre 0.5 seconde entre chaque vérification


r/pythonhelp • • Mar 22 '24

Rookie non-programmer needs to figure out the problem with this ChatGPT generated code

0 Upvotes

>>> from openpyxl import Workbook

>>> from openpyxl.styles import Font, Alignment, PatternFill

>>>

>>> def create_scorecard(candidate_name, evaluator_name):

... wb = Workbook()

... ws = wb.active

... ws.title = "Scorecard"

...

>>> # Candidate and Evaluator Name

>>> ws['A1'] = "Candidate Name:"

File "<stdin>", line 1

ws['A1'] = "Candidate Name:"

IndentationError: unexpected indent

>>> ws['B1'] = candidate_name

File "<stdin>", line 1

ws['B1'] = candidate_name

IndentationError: unexpected indent

>>> ws['A2'] = "Evaluator Name:"

File "<stdin>", line 1

ws['A2'] = "Evaluator Name:"

IndentationError: unexpected indent

>>> ws['B2'] = evaluator_name

File "<stdin>", line 1

ws['B2'] = evaluator_name

IndentationError: unexpected indent

>>>

>>> # Criteria

>>> criteria = [

File "<stdin>", line 1

criteria = [

IndentationError: unexpected indent

>>> "Technical Knowledge",

File "<stdin>", line 1

"Technical Knowledge",

IndentationError: unexpected indent

>>> "Analytical Skills",

File "<stdin>", line 1

"Analytical Skills",

IndentationError: unexpected indent

>>> "Communication Skills",

File "<stdin>", line 1

"Communication Skills",

IndentationError: unexpected indent

>>> "Project Management",

File "<stdin>", line 1

"Project Management",

IndentationError: unexpected indent

>>> "Teamwork",

File "<stdin>", line 1

"Teamwork",

IndentationError: unexpected indent

>>> "Problem-Solving",

File "<stdin>", line 1

"Problem-Solving",

IndentationError: unexpected indent

>>> "Industry Knowledge",

File "<stdin>", line 1

"Industry Knowledge",

IndentationError: unexpected indent

>>> "Experience and Qualifications"

File "<stdin>", line 1

"Experience and Qualifications"

IndentationError: unexpected indent

>>> ]

File "<stdin>", line 1

]

IndentationError: unexpected indent

>>>

>>> # Headers

>>> ws.merge_cells('A4:B4')

File "<stdin>", line 1

ws.merge_cells('A4:B4')

IndentationError: unexpected indent

>>> ws['A4'] = "Criteria"

File "<stdin>", line 1

ws['A4'] = "Criteria"

IndentationError: unexpected indent

>>> ws['A4'].font = Font(bold=True)

File "<stdin>", line 1

ws['A4'].font = Font(bold=True)

IndentationError: unexpected indent

>>> ws['A4'].alignment = Alignment(horizontal='center', vertical='center')

File "<stdin>", line 1

ws['A4'].alignment = Alignment(horizontal='center', vertical='center')

IndentationError: unexpected indent

>>> ws['A4'].fill = PatternFill(start_color="87CEEB", end_color="87CEEB", fill_type="solid")

File "<stdin>", line 1

ws['A4'].fill = PatternFill(start_color="87CEEB", end_color="87CEEB", fill_type="solid")

IndentationError: unexpected indent

>>>

>>> ws['C4'] = "Score (1-5)"

File "<stdin>", line 1

ws['C4'] = "Score (1-5)"

IndentationError: unexpected indent

>>> ws['C4'].font = Font(bold=True)

File "<stdin>", line 1

ws['C4'].font = Font(bold=True)

IndentationError: unexpected indent

>>> ws['C4'].alignment = Alignment(horizontal='center', vertical='center')

File "<stdin>", line 1

ws['C4'].alignment = Alignment(horizontal='center', vertical='center')

IndentationError: unexpected indent

>>> ws['C4'].fill = PatternFill(start_color="87CEEB", end_color="87CEEB", fill_type="solid")

File "<stdin>", line 1

ws['C4'].fill = PatternFill(start_color="87CEEB", end_color="87CEEB", fill_type="solid")

IndentationError: unexpected indent

>>>

>>> ws['D4'] = "Comments"

File "<stdin>", line 1

ws['D4'] = "Comments"

IndentationError: unexpected indent

>>> ws['D4'].font = Font(bold=True)

File "<stdin>", line 1

ws['D4'].font = Font(bold=True)

IndentationError: unexpected indent

>>> ws['D4'].alignment = Alignment(horizontal='center', vertical='center')

File "<stdin>", line 1

ws['D4'].alignment = Alignment(horizontal='center', vertical='center')

IndentationError: unexpected indent

>>> ws['D4'].fill = PatternFill(start_color="87CEEB", end_color="87CEEB", fill_type="solid")

File "<stdin>", line 1

ws['D4'].fill = PatternFill(start_color="87CEEB", end_color="87CEEB", fill_type="solid")

IndentationError: unexpected indent

>>>

>>> # Inserting Criteria

>>> for row, criterion in enumerate(criteria, start=5):

File "<stdin>", line 1

for row, criterion in enumerate(criteria, start=5):

IndentationError: unexpected indent

>>> ws[f'A{row}'] = criterion

File "<stdin>", line 1

ws[f'A{row}'] = criterion

IndentationError: unexpected indent

>>> ws[f'A{row}'].alignment = Alignment(horizontal='left', vertical='center')

File "<stdin>", line 1

ws[f'A{row}'].alignment = Alignment(horizontal='left', vertical='center')

IndentationError: unexpected indent

>>> ws[f'B{row}'] = ""

File "<stdin>", line 1

ws[f'B{row}'] = ""

IndentationError: unexpected indent

>>> ws[f'B{row}'].alignment = Alignment(horizontal='left', vertical='center')

File "<stdin>", line 1

ws[f'B{row}'].alignment = Alignment(horizontal='left', vertical='center')

IndentationError: unexpected indent

>>> ws[f'C{row}'] = ""

File "<stdin>", line 1

ws[f'C{row}'] = ""

IndentationError: unexpected indent

>>> ws[f'C{row}'].alignment = Alignment(horizontal='center', vertical='center')

File "<stdin>", line 1

ws[f'C{row}'].alignment = Alignment(horizontal='center', vertical='center')

IndentationError: unexpected indent

>>> ws[f'D{row}'] = ""

File "<stdin>", line 1

ws[f'D{row}'] = ""

IndentationError: unexpected indent

>>> ws[f'D{row}'].alignment = Alignment(horizontal='left', vertical='center')

File "<stdin>", line 1

ws[f'D{row}'].alignment = Alignment(horizontal='left', vertical='center')

IndentationError: unexpected indent

>>>

>>> # Overall Assessment

>>> row += 1

File "<stdin>", line 1

row += 1

IndentationError: unexpected indent

>>> ws.merge_cells(f'A{row}:B{row}')

File "<stdin>", line 1

ws.merge_cells(f'A{row}:B{row}')

IndentationError: unexpected indent

>>> ws[f'A{row}'] = "Total Score:"

File "<stdin>", line 1

ws[f'A{row}'] = "Total Score:"

IndentationError: unexpected indent

>>> ws[f'A{row}'].font = Font(bold=True)

File "<stdin>", line 1

ws[f'A{row}'].font = Font(bold=True)

IndentationError: unexpected indent

>>> ws[f'A{row}'].alignment = Alignment(horizontal='center', vertical='center')

File "<stdin>", line 1

ws[f'A{row}'].alignment = Alignment(horizontal='center', vertical='center')

IndentationError: unexpected indent

>>> ws[f'A{row}'].fill = PatternFill(start_color="87CEEB", end_color="87CEEB", fill_type="solid")

File "<stdin>", line 1

ws[f'A{row}'].fill = PatternFill(start_color="87CEEB", end_color="87CEEB", fill_type="solid")

IndentationError: unexpected indent

>>>

>>> ws[f'C{row}'] = ""

File "<stdin>", line 1

ws[f'C{row}'] = ""

IndentationError: unexpected indent

>>> ws[f'C{row}'].alignment = Alignment(horizontal='center', vertical='center')

File "<stdin>", line 1

ws[f'C{row}'].alignment = Alignment(horizontal='center', vertical='center')

IndentationError: unexpected indent

>>>

>>> row += 1

File "<stdin>", line 1

row += 1

IndentationError: unexpected indent

>>> ws.merge_cells(f'A{row}:D{row}')

File "<stdin>", line 1

ws.merge_cells(f'A{row}:D{row}')

IndentationError: unexpected indent

>>> ws[f'A{row}'] = "Comments:"

File "<stdin>", line 1

ws[f'A{row}'] = "Comments:"

IndentationError: unexpected indent

>>> ws[f'A{row}'].font = Font(bold=True)

File "<stdin>", line 1

ws[f'A{row}'].font = Font(bold=True)

IndentationError: unexpected indent

>>> ws[f'A{row}'].alignment = Alignment(horizontal='center', vertical='center')

File "<stdin>", line 1

ws[f'A{row}'].alignment = Alignment(horizontal='center', vertical='center')

IndentationError: unexpected indent

>>> ws[f'A{row}'].fill = PatternFill(start_color="87CEEB", end_color="87CEEB", fill_type="solid")

File "<stdin>", line 1

ws[f'A{row}'].fill = PatternFill(start_color="87CEEB", end_color="87CEEB", fill_type="solid")

IndentationError: unexpected indent

>>>

>>> # Save the workbook

>>> wb.save(f"{candidate_name}_Scorecard.xlsx")

File "<stdin>", line 1

wb.save(f"{candidate_name}_Scorecard.xlsx")

IndentationError: unexpected indent

>>>

>>> if __name__ == "__main__":

... candidate_name = input("Enter Candidate Name: ")

... evaluator_name = input("Enter Evaluator Name: ")

... create_scorecard(candidate_name, evaluator_name)

... print("Scorecard created successfully!")


r/pythonhelp • • Feb 23 '24

Script traceback

0 Upvotes

I'm trying to figure out what my traceback means If anyone is willing to help id greatly appreciate it.


r/pythonhelp • • Nov 24 '22

Python function

0 Upvotes

Hi Guys, I am learning Python coding and I meed help with my assignment. Can somebody pls help me? Thanks !


r/pythonhelp • • Dec 08 '22

Can't Understand What is Wrong In My Looping Code

0 Upvotes

I have created an excel sheet and gives headings like [ Item_1 , Item_2 ] parallel to each other & store data in those headings . #using this stored data in other application.

What I want is :-

If Item_1 (Cell contains value):

do this (specific steps)

Else(if Cell is empty) :

do this(specific steps)

SAME GOES FOR [ ITEM_2 ]

In loop

I am Able to Successfully Loop [ Item_1 ] only

2nd Item is not looping (getting no error in code it's working ok but not reading 2nd item)

To check Cell Values(empty or not) I am Using Below Code :-

if pd.isna(df.loc[0, 'Item_1']) is False:

Full Code Demo

df = pd.read_excel(r"excel file link .xlsx)

itm1 = df["Item_1"].values

itm2 = df["Item_2"].values

zipped = zip(itm1, itm2)

for (a, b) in zipped:

if pd.isna(df.loc[0, 'Item_1']) is False:

do this

else :

do this

it's looping item_1 only not including item_2 .


r/pythonhelp • • Dec 02 '22

question about how to store a solution

0 Upvotes

I'm currently in a class for python and for our final we have to make a program that uses the things we've learned. But how I want to use dict/pickle we haven't been taught or isn't in the book we use, and I cant find the answer to my question online.

My program is a menu based calculator and I want to store my solutions to look up later via a list, Do I just store the object of the equation and it brings the result with it, or is there a way to just store what it creates as a value.

As a base I have you input say an x value and a y value they become self.x/y respectfully, do I save that or how do I save just the end result from something like self.x ** self.y.


r/pythonhelp • • Feb 17 '17

How might I screw around with base systems?

0 Upvotes

Do I need to import something and what are the different commands? Thanks.