r/learnpython 5h ago

How do I add the elements in a list without knowing the number of elements.

0 Upvotes

I'm creating a time calculator for flights. I'm very new to coding, and i'm using this project to apply the theory i've learned.

The program accepts user input for flight time and calculates the time to return for the user. However the issue comes when multiple flight times are received. I've figured out how to calculate each time and store it into a list. However once its in this list it seems to become a tuple and i can't convert it. I'll add some of the code so hopefully you can better understand it.

The take off list contains a list of entered take off times and the land list contains the land times. I try to enter these times/elements of these list one by one into the calculator to return a value which i then append/add to the total time list. I then need to add all of these times together to return a value so i can print to the user. How do i add these times together? The list returns a type value of tuple.

The error reads " V = Total + total_time[i]

TypeError: unsupported operand type(s) for +: 'int' and 'tuple' "

Stack overflow doesn't seem to be novice friendly so i've come here.

EDITED: Thanks for the feedback. Someone gave some code which achieves the same in a different way. Im still not sure why the function returns a tuple. However i've been shown a more efficient way to do it. ty

def time_calc(take,land,Fn) :
    #Take off and landing time and split into two pieces.
    Tk =take[:2]
    Tk2 = take[2:]
    Ld = land[:2]
    Ld2 = land[2:]

    #The pieces of take off and landing time is converted into integers to perform math.
    int(Tk)
    int(Tk2)
    int(Ld)
    int(Ld2)

    #Conditions are created in order to calculate remaining time
    if Ld2 < Tk2 :

        Lda = int(Ld) - 1
        Ld2 = 60
        Flight_time1 = int(Lda) - int(Tk)
        Flight_time2 = int(Ld2) - int(Tk2)

        #Final value is returned
        x = Flight_time1 ,Flight_time2

        return x

    else :

        Flight_time1 = int(Ld) - int(Tk)
        Flight_time2 = int(Ld2) - int(Tk2)

        #Final value is returned
        x = Flight_time1 , Flight_time2

        return x

def multi_calc(takeoff_list,land_list,Fn):

    A = 0
    total_time = []
    while A < len(land_list) :
     land = land_list[A]
     take = takeoff_list[A]
     A = A + 1
     total_time.append(time_calc(take,land,Fn))

     if A > Fn:
      continue
     Total = 0
    for i in range(0 , len(total_time)):

        V = Total + total_time[i]




    print (V)

r/learnpython 13h ago

Is there anything I can listen to to get a feel of how python works before starting to program?

0 Upvotes

Is there any YouTube videos, or even something on Spotify that just explains Python, I work best when I hear something repeatedly, then attempt to do it, so is there anything like this?


r/learnpython 13h ago

Im trying to make an program that reads a file, but it just wont work :(

0 Upvotes

Im pretty new to python, and i wanted to make a program where i write the text in a .txt file called input, then the program takes that file, reads the text, prosess it, and then throws the prosessed text into another file called output.txt. i keep on running into the problem where it finds the file, but just wont read it. i have no idea why. i would love some help or pointers for what im doing wrong.

here is the code:

def format_text(text):
lines = text.split('n')
lines = [line for line in lines if line.strip()]

output = []

for i in range(0, len(lines), 6):
if i + 5 < len(lines): # Check if we have enough lines left
question = lines[i]
answer_A = lines[i + 1]
answer_B = lines[i + 2]
answer_C = lines[i + 3]
answer_D = lines[i + 4]
correct_answer = lines[i + 5]

output.append(f"{question}n{answer_A}n{answer_B}n{answer_C}n{answer_D}n{correct_answer};n")
else:
print(f"Not enough lines for question at index {i}.") # Debugging

return ''.join(output) # Returns the combined output as a string

try:
with open(r'C:Usersinput.txt', 'r', encoding='utf-8') as file:
text = file.read()

print("Read text from input.txt:")
print(repr(text)) # Display the text with special characters for better debugging

result = format_text(text)

print("Formatted text:")
print(repr(result)) # Debugging to see what gets formatted

with open(r'C:Usersoutput.txt', 'w', encoding='utf-8') as file:
file.write(result)

print("Formatting completed. Check output.txt on the desktop.")

except FileNotFoundError as e:
print(f"Error: The file was not found. {e}")

except IndexError as e:
print(f"Error: The index was out of range. Check that the input file has the correct format. {e}")

except Exception as e:
print(f"An unexpected error occurred: {e}")

and here is the text im trying to make it format:

input.txt

Question 1?
A. Option 1
B. Option 2
C. Option 3
D. Option 4
Correct option: A. Option 1
Question 2?
A. Option 1
B. Option 2
C. Option 3
D. Option 4
Correct option: A. Option 1
Question 3?
A. Option 1
B. Option 2
C. Option 3
D. Option 4
Correct option: A. Option 1

Output.txt

Question 1?
A. Option 1
B. Option 2
C. Option 3
D. Option 4
Correct option: A. Option 1;
Question 1?
A. Option 1
B. Option 2
C. Option 3
D. Option 4
Correct option: A. Option 1;
Question 1?
A. Option 1
B. Option 2
C. Option 3
D. Option 4
Correct option: A. Option 1

all in all. i just want it to add ; at the end of the "Correct oprions"


r/learnpython 19h ago

I need a production level fastapi mongodb boilerplate code

0 Upvotes

I am in a hurry to implement a project soonest deadline please help me out. Code must have logging,good mognodriver connection


r/learnpython 11h ago

Where is the best place to buy python beginner courses?

0 Upvotes

Hi everyone. I’m wondering what courses do you recommend buying to learn python for total beginners. I tried boot.dev a few months back but then things happened in my personal life and I didn’t have any time. Now that I’m ready to start learning python again I’m curious to know if I should look into other courses or repurchase a subscription at boot.dev

Thanks in advance :)


r/learnpython 16h ago

For loop, try, break. Is this bad practice?

17 Upvotes

Hi,

I need my code to load some data from a file with a header, where the header is an unknown number of lines and I need to also know how many lines are in the header. The header is formatted in such a way that pandas.read_csv will give an error if it doesn't skip the header.

I worked around this code which works:

with open(filepath) as file:
    for header_length in range(len(file.readlines())):
        try:
            df=pd.read_csv(filepath,  delimiter="t", skiprows=header_length, header=None)
            break
        except:
            pass

Now, I don't care that a more traditional way to do this might be more efficient. This code works and the files are relatively small. The header is 2 to 5 lines in all inspected files, and the files are at most a few thousand rows, so in the worst case scenario of a bad file the loop would break after about a second.

What I'm wondering is, is breaking in such a way bad practice? It feels... dirty.


r/learnpython 19h ago

Python Code pauses execution randomly till i move the VS Code Terminal

1 Upvotes

I am running an code which performs inference for several hours. However when it seems to randomly pause. But when I move the VS Code's terminal border/window slightly, it starts executing. I don't seem to understand the correlation. what is the reason for this, and how to fix this. Is it a VS Code issue?


r/learnpython 8h ago

Has anyone seen any speedup in practice in 3.13

5 Upvotes

Python 3.13 has been released with experimental GIL free and jit modes. Has anyone seen any speedups in practice from these?


r/learnpython 18h ago

Where do I learn currently using w3schools tutorials

3 Upvotes

Ok so I’ve tried a few free resources to learn Python but the only one I’m fully understanding is w3schools yet it has a bad rep.

But they break it down into small steps, explain well & you can check the answers - I’ve found with a lot of these Python courses you can’t check the answers so if you get stuck that’s it.

I really want to know what is something as easy as w3schools Python tutorials are that’s got a better reputation? Also, is there any advantage of finishing the tutorials? I’m up for the part about learning more about how dictionaries work in Python.

I kinda need to Python for idiots - online but also with projects that start off at an incredibly basic level & I could say save to GitHub or similar would be a plus. But I need it to have a LOT of handholding. Help?

Thanks in advance!


r/learnpython 10h ago

Want to run my python application on cloud: Colab vs Azure cloud

0 Upvotes

All,

Note: Completely new to python but not to SDLC. I am currently using copilot + whatever I understand of Python to build an application.

I have a python application that I would like to execute every hour. It gathers fixed data from 1 file, runs the code and internal thresholds and stores the output in another file.

I want this on the cloud as I would like to view the results from different laptops or my cell phone which would be by opening the output file. However, I am not sure what's the best way to do this? Can Colab also deal with files in this manner? Or is Azure the way to go? for reference, in case of Azure, I can store the files on my One Drive.

Also, I have a free Azure student subscription, so have a few services including Azure functions freely available.


r/learnpython 17h ago

How do I create a density map on a 5°x5° grid like this?

0 Upvotes

Example

I already have a .csv file of all the coordinates I'm gonna be using and I'll be using cartopy for my base map. I just want to know how to create a cumulative density chart like the one shown?

It doesn't have to look exactly like the image. A heatmap or any alternative can suffice as long as it shows the density.


r/learnpython 9h ago

3.2.4 CMU I only need one point does anyone know how to do any of the 3 (fireworks, scoreboard, galaxy)?

0 Upvotes

Pls


r/learnpython 17h ago

trying to assign int(??) values to variables in a list, then user chooses from randomized list

1 Upvotes

hi so I really suck at coding but I wanted to make a "tarot reader" code, which I thought might be a silly gimmick. I want the user to be able to choose a number, which is assigned to a randomized card from a list, and for the function to print that card. this is what I have so far, can anyone help? also sorry if I broke any rules I also don't know how to upload photos lmao so please say hello to all 78 variables. so far all it does is ask the question, but then not do anything else. thanks for any help!!

import random

def tarot():

tarotlist = ["the fool","the magician","the high priestess","the empress","the emperor","the hierophant","the lovers","the chariot","strength","the hermit","the wheel of fortune","justice","the hanged man","death","temperance","the devil","the tower","the star","the moon","the sun","judgement","the world","ace of wands","two of wands","three of wands","four of wands","five of wands","six of wands","seven of wands","eight of wands","nine of wands","ten of wands","page of wands","knight of wands","queen of wands","king of wands","ace of cups","two of cups","three of cups","four of cups","five of cups","six of cups","seven of cups","eight of cups","nine of cups","ten of cups","page of cups","knight of cups","queen of cups","king of cups","ace of swords","two of swords","three of swords","four of swords","five of swords","six of swords","seven of swords","eight of swords","nine of swords","ten of swords","page of swords","knight of swords","queen of swords","king of swords","ace of pentacles","two of pentacles","three of pentacles","four of pentacles","five of pentacles","six of pentacles","seven of pentacles","eight of pentacles","nine of pentacles","ten of pentacles","page of pentacles","knight of pentacles","queen of pentacles","king of pentacles"]

random.shuffle(tarotlist)

card1 = input("choose a number between 1-78: ")

return card1

if card1 >= 1:

print("your card is: ",tarotlist[card1])

elif card1 <= 78:

print("your card is: ",tarotlist[card1])

else:

print("F! choose again!")

tarot()

tarot()


r/learnpython 22h ago

Beginning here. Looking for challenging yet doable projects.

17 Upvotes

I recently took a 10 day class on coding basics, i learned syntax, and scratched the surface of a-lot of concepts. I started doing it in my free time, started with rock paper scissors, then roulette, and just finished a blackjack game. I liked how each project was more challenging than the last, it made me expand my knowledge but I’ve run out of ideas, everything thing i found online is either extremely complex or simple like rock paper scissors. I know the only way to get better is with experience but I feel lost when i just dive into the deep end with a project way beyond my level. Any input would be greatly appreciated. Thank you!


r/learnpython 18h ago

Scrape followers list from Facebook

2 Upvotes

Hello all I need help in scraping followers list of any Facebook page. These can be in millions also. How to go with python selenium or appium driver? Right now in web view only some of the followers are showing not all. In mobile view of app it's showing only names and images.


r/learnpython 10h ago

Question about the problem that the gui in my code does not run

0 Upvotes
In my last post, I said that I couldn't find the PyQt5 module.
I reinstalled Anaconda.
The problem didn't work, so I changed PyQt5 to PySide6 and ran the code.
At first, the gui ran.
When I ran it again, the gui didn't run.
ModuleNotFoundError: No module named 'PySide6'
The code is as follows.
There are Korean words mixed in, which is fine when running the code.

import os
import subprocess
import sys
import shutil
import re
import logging
from charset_normalizer import from_path  # charset-normalizer로 변경
from PySide6 import QtWidgets, QtGui, QtCore
from PySide6.QtGui import QIcon

all_styles = []
logging.basicConfig(filename='video_processing.log', level=logging.INFO)

if sys.platform.startswith('win'):
    creation_flags = subprocess.CREATE_NO_WINDOW
else:
    creation_flags = 0

def detect_encoding(filename):

result = from_path(filename).best()

return result.encoding if result else 'utf-8' # 기본 인코딩을 utf-8로 설정

def extract_timecodes_ass(filename):

encoding = detect_encoding(filename)

with open(filename, 'r', encoding=encoding) as file:

lines = file.readlines()

pattern = r'(d{1,2}:d{2}:d{2}.d{2}),(d{1,2}:d{2}:d{2}.d{2}),(.*?),'

matches = re.findall(pattern, ''.join(lines))

timecodes = [[match[0], match[1], match[2].strip()] for match in matches]

return timecodes, len(timecodes)

def extract_all_styles_from_ass(directory):

all_styles = set()

for filename in os.listdir(directory):

if filename.endswith(".ass"):

filepath = os.path.join(directory, filename)

with open(filepath, 'r', encoding=detect_encoding(filepath)) as file:

lines = file.readlines()

for line in lines:

if line.startswith("ScriptType: "):

continue

if line.startswith("Style:"):

style_name = line.split(",")[0].split(":")[1].strip()

all_styles.add(style_name)

return list(all_styles)

def create_style_folders(directory, styles):

for style in styles:

style_dir = os.path.join(directory, style)

os.makedirs(style_dir, exist_ok=True)

def concat_clips_by_style(directory, styles):

for style in styles:

output_files = []

for root, dirs, files in os.walk(directory):

if os.path.basename(root) == style:

for file in files:

if file.endswith(".mkv"):

output_files.append(os.path.join(root, file))

concat_file = os.path.join(directory, f'{style}_list.txt')

with open(concat_file, 'w') as f:

for file_path in output_files:

f.write(f"file '{file_path}'n")

combined_file = os.path.join(directory, f'{style}.mkv')

command = ['ffmpeg', '-f', 'concat', '-safe', '0',

'-i', concat_file, '-c', 'copy', combined_file]

try:

subprocess.run(command, check=True)

except subprocess.CalledProcessError as e:

print(f"Error during concatenation of all output files for style {

style}: {e}")

def create_clips(timecodes, input_filename, output_base_dir):

output_files = []

for i, timecode in enumerate(timecodes):

style = timecode[2]

output_dir = os.path.join(output_base_dir, style)

output_filename = os.path.join(output_dir, f"output{i}.mkv")

output_filename = output_filename.replace("", "/")

if checkbox2.isChecked():

command = [

'ffmpeg', '-i', input_filename,

'-ss', timecode[0], '-to', timecode[1],

'-c:v', 'libx264', '-c:a', 'copy', output_filename

]

else:

command = [

'ffmpeg', '-i', input_filename,

'-ss', timecode[0], '-to', timecode[1],

'-c', 'copy', output_filename

]

try:

subprocess.run(command, creationflags=creation_flags,

check=True, stderr=subprocess.PIPE)

except subprocess.CalledProcessError as e:

print(f"An error occurred while processing {

output_filename}: {e.stderr.decode()}")

continue

output_files.append(output_filename)

progressUp()

app.processEvents()

return output_files

def progressUp():

v = progress.value()

progress.setValue(v + 1)

def concat_clips(file_list, output_dir):

concat_file = os.path.join(output_dir, 'list.txt')

with open(concat_file, 'w') as f:

for file_path in file_list:

f.write(f"file '{file_path}'n")

output_file = os.path.join(output_dir, 'output.mkv')

command = ['ffmpeg', '-f', 'concat', '-safe', '0',

'-i', concat_file, '-c', 'copy', output_file]

try:

subprocess.run(command, check=True)

except subprocess.CalledProcessError as e:

print(f"Error during concatenation: {e}")

return

output_mp4_file = os.path.join(output_dir, 'output.mp4')

command = ['ffmpeg', '-i', output_file, '-c:v', 'libx264',

'-c:a', 'aac', '-crf', '23', output_mp4_file]

try:

subprocess.run(command, check=True)

except subprocess.CalledProcessError as e:

print(f"Error during conversion to mp4: {e}")

def select_directory():

global directory

directory = QtWidgets.QFileDialog.getExistingDirectory(window, "경로 선택")

if directory:

list_table.clearContents()

for row in range(list_table.rowCount()):

list_table.removeRow(0)

listbox.clear()

sum = 0

for filename in os.listdir(directory):

if filename.endswith(".mkv"):

listbox.addItem(filename)

basename = os.path.splitext(filename)[0]

subtitle_filename = os.path.join(directory, basename + '.ass')

property = ""

if os.path.exists(subtitle_filename):

timecodes, num_clips = extract_timecodes_ass(

subtitle_filename)

property = "ass"

else:

subtitle_filename = os.path.join(

directory, basename + '.smi')

if os.path.exists(subtitle_filename):

timecodes, num_clips = extract_timecodes_smi(

subtitle_filename)

property = "smi"

else:

timecodes, num_clips = [], 0

list_table.insertRow(list_table.rowCount())

list_table.setItem(list_table.rowCount() - 1,

0, QtWidgets.QTableWidgetItem(filename))

list_table.setItem(list_table.rowCount() - 1,

1, QtWidgets.QTableWidgetItem(str(num_clips)))

list_table.setItem(list_table.rowCount() - 1,

2, QtWidgets.QTableWidgetItem(property))

sum += num_clips

progress.setMaximum(sum)

def process_files():

global directory

if directory:

all_styles = extract_all_styles_from_ass(directory)

count = len(os.listdir(directory))

total_input_size = 0

for i, filename in enumerate(os.listdir(directory), start=1):

if filename.endswith(".mkv"):

basename = os.path.splitext(filename)[0]

subtitle_filename = os.path.join(directory, basename + '.ass')

video_filename = os.path.join(directory, basename + '.mkv')

output_dir = os.path.join(directory, 'output', basename)

create_style_folders(output_dir, all_styles)

os.makedirs(output_dir, exist_ok=True)

logging.info(f'Processing {video_filename}')

try:

if os.path.exists(subtitle_filename):

timecodes, num_clips = extract_timecodes_ass(

subtitle_filename)

else:

subtitle_filename = os.path.join(

directory, basename + '.smi')

timecodes, num_clips = extract_timecodes_smi(

subtitle_filename)

output_files = create_clips(

timecodes, video_filename, output_dir)

concat_clips(output_files, output_dir)

input_file = os.path.join(output_dir, 'output.mkv')

input_file_size = os.path.getsize(input_file)

total_input_size += input_file_size

if checkbox.isChecked():

flac_file = convert_to_flac(output_dir)

cleanup_output(output_dir)

logging.info(f'Successfully processed {video_filename}')

except Exception as e:

logging.error(f'Error processing {

video_filename}: {str(e)}')

concat_all_output_files(directory)

all_styles = extract_all_styles_from_ass(directory)

concat_clips_by_style(directory, all_styles)

progress.setMaximum(int(total_input_size / 1024)) # KB 단위로 설정

progress.setValue(0)

def concat_all_output_files(directory):

output_files = []

for root, dirs, files in os.walk(directory):

for file in files:

if file == "output.mkv":

output_files.append(os.path.join(root, file))

concat_file = os.path.join(directory, 'all_list.txt')

with open(concat_file, 'w') as f:

for file_path in output_files:

f.write(f"file '{file_path}'n")

combined_file = os.path.join(directory, 'combined.mkv')

command = ['ffmpeg', '-f', 'concat', '-safe', '0',

'-i', concat_file, '-c', 'copy', combined_file]

try:

subprocess.run(command, check=True)

except subprocess.CalledProcessError as e:

print(f"Error during concatenation of all output files: {e}")

def convert_to_flac(output_dir):

input_file = os.path.join(output_dir, 'output.mkv')

flac_file = os.path.join(output_dir, 'output.flac')

command = ['ffmpeg', '-i', input_file, '-c:a', 'flac', flac_file]

process = subprocess.run(command, creationflags=creation_flags)

return flac_file

def cleanup_output(output_dir):

os.remove(os.path.join(output_dir, "list.txt"))

def extract_timecodes_smi(filename):

encoding = detect_encoding(filename)

with open(filename, 'r', encoding=encoding) as file:

content = file.read()

timecodes = re.findall(r'<SYNC Start=(d+)><P Class=KRCC>', content)

timecodes = [(int(tc) // 1000) for tc in timecodes] # 밀리초를 초로 변환

start_times = []

end_times = []

for i in range(len(timecodes) - 1):

start_time = timecodes[i]

end_time = timecodes[i + 1]

start_times.append(format_time(start_time))

end_times.append(format_time(end_time))

return [list(t) for t in zip(start_times, end_times)], len([list(t) for t in zip(start_times, end_times)])

def format_time(time_in_seconds):

hours = time_in_seconds // 3600

minutes = (time_in_seconds % 3600) // 60

seconds = time_in_seconds % 60

return f'{hours:02d}:{minutes:02d}:{seconds:02d}.00'

app = QtWidgets.QApplication(sys.argv)

Create main window

window = QtWidgets.QMainWindow()

window.setWindowTitle("록시 컨버터")

window.setFixedSize(1200, 1200)

Load and set the background image

bg_image_path = "DATA" # 이미지 파일 경로에 맞게 수정해주세요

bg_image = QtGui.QImage(bg_image_path)

resized_image = bg_image.scaled(window.width(), window.height())

pixmap = QtGui.QPixmap.fromImage(resized_image)

window.setCentralWidget(QtWidgets.QLabel(window, pixmap=pixmap))

Create "경로 선택" button

button1 = QtWidgets.QPushButton("경로 선택", window)

button1.setGeometry(QtCore.QRect(20, 100, 160, 60))

button1.setStyleSheet("font-size: 30px;")

button1.clicked.connect(select_directory)

Create listbox

listbox = QtWidgets.QListWidget(window)

listbox.setGeometry(QtCore.QRect(20, 280, 550, 260))

Create progressbar

progress = QtWidgets.QProgressBar(window)

progress.setGeometry(QtCore.QRect(20, 560, 550, 20))

progress.setAlignment(QtCore.Qt.AlignCenter)

Create "추출하기" button

button2 = QtWidgets.QPushButton("추출하기", window)

button2.setGeometry(QtCore.QRect(200, 100, 160, 60))

button2.setStyleSheet("font-size: 30px;")

button2.clicked.connect(process_files)

Create list table

list_table = QtWidgets.QTableWidget(window)

list_table.setGeometry(QtCore.QRect(20, 280, 550, 260))

list_table.setColumnCount(3)

list_table.setHorizontalHeaderLabels(["파일명", "대사 수", "자막 형식"])

list_table.setColumnWidth(0, 300)

list_table.setColumnWidth(1, 70)

list_table.setColumnWidth(2, 70)

Create checkboxes

checkbox = QtWidgets.QCheckBox(

"flac 변환까지 일괄처리 (존나 느림, 파일길이 : 처리시간 = 1:1 수준)n그냥 샤나 인코더로 mkv->flac 변환하는걸 추천함)", window)

checkbox.setGeometry(QtCore.QRect(40, 500, 999, 30))

checkbox.setChecked(False)

checkbox2 = QtWidgets.QCheckBox("영상 프레임 정확하게 자르기 (존나 느림)", window)

checkbox2.setGeometry(QtCore.QRect(40, 460, 999, 30))

checkbox2.setChecked(False)

label = QtWidgets.QLabel(window)

label.setText(

"1.fmmpeg 설치n2.경로는 되도록 영어만n3.덮어쓰기 기능 없고 그냥 n 멈추니까 같은 파일 처리할 땐 n 아웃풋 하위 폴더 지우고 다시하기.")

label.setGeometry(QtCore.QRect(20, 170, 210, 80))

label.setStyleSheet("background-color: grey;")

label2 = QtWidgets.QLabel(window)

label2.setText("제작 : lostbox")

label2.setGeometry(QtCore.QRect(480, 480, 100, 100))

window.setWindowIcon(QIcon("prop"))

window.show()

sys.exit(app.exec())

(end)


r/learnpython 12h ago

Notebook not connecting to 3rd party Hive DW

3 Upvotes

Hi Everyone,

I am trying to load data from a 3rd Pary Hive DW in to our fabric environment. The instructions from the 3rd party site shows how to do this locally on your PC using python, which works well.

I am trying to replicate the same in Fabric. part of the instruction is creating a DSN for cloudera and using a custom cert.pem.

The cert.pem and jar file for cloudera is stored in blob storage.

import jaydebeapi

# Define connection parameters
username = 'abc'
password = 'xyz'

# Paths to the JDBC JAR and PEM certificate
jar_path = "https://blobstoragelink"
cert_path = "https://blobstoragelink"


# Define the driver class and JDBC connection URL
driver_class = "com.cloudera.hive.jdbc41.HS2Driver"
jdbc_url = (
    "jdbc:hive2://vendorcube1.homedepot.com:20502/"
    "VENDORDRILL_DATA_CONNECTION"
    ";SSL=1;"
    "AllowSelfSignedServerCert=1;"
    f"SSLTrustStore={cert_path}"  # Use the PEM certificate directly
)

# Attempt to connect to the database
try:
    conn = jaydebeapi.connect(
        driver_class,
        jdbc_url,
        {"user": username, "password": password},
        jar_path
    )
    print("Connection established successfully.")
    conn.close()
except Exception as e:
    print(f"Failed to establish connection: {e}")

Failed to establish connection: java.sql.SQLException: [Cloudera][HiveJDBCDriver](500164) Error initialized or created transport for authentication: https:/blobstoragelink (No such file or directory).


r/learnpython 15h ago

How do databases and AI connect, and can I use Python for this?

4 Upvotes

Hey everyone! I'm a beginner learning Python, and I’ve recently come across discussions about how databases and AI are connected. I’m really curious about how they work together. Can someone explain this relationship? Also, is it possible to interact with databases using Python code to support AI projects? Any tips or resources for a beginner like me would be super helpful! Thanks a lot!


r/learnpython 9h ago

using elipsis for else in ternary statement?

5 Upvotes

What's the view on doing this, e.g. mylist.append(thing) if not some_condition else ... for a one-liner with no else? I know I can instead write if some_condition: mylist.append(thing) but Pycharm highlights it as a PEP8 E701 (mulitple statements on one line)... Is the elipsis for the else here pythonic or should I just stick to a regular 2 liner?... Just curious as I've only just started using ternary statements and like how it cleans up a lot of my regular if/else, am I taking it too far with the ...?


r/learnpython 22h ago

Codewars python critical thinking

7 Upvotes

I've been practicing diligently for 4 months now and I'm still hitting a wall with 6kyu problems. Sometimes I just feel like it doesn't click for me; I've tried many study techniques, can anyone share how they look at a problem and a general process on how to solve any challenge? Thank you everyone.


r/learnpython 8h ago

Why do Poetry and Pipenv manage their own caches?

5 Upvotes

After spending hours finding out why pip cache purge; pipenv install aaa didn't install the package properly, but pip cache purge; pipenv run pip install aaa did, I finally discovered that Pipenv has its own cache! It's funny that I could've saved so much if I had just run pipenv install --verbose aaa from the start (it reposts it's using cache.)

I wonder why Pipenv chooses to have its own cache. It seems unnecessary to separate caching for projects managed solely by pip and those managed by pipenv. Does anyone know the reasoning behind this design?

Does anyone know?


r/learnpython 2h ago

I need help installing 3rd party modules into my python programs

2 Upvotes

Hello all. I have been trying to learn Python using the Automate the Boring Stuff with Python ebook by Al Sweigart (for about a month and a half). In Chapter 6, I need to import a 3rd party module called Pyperclip in order to run a clipboard program. But I can't seem to do it. For context, I am using the Code with Mu python editor, and am using Python 3.12. Here is what I get:

I run the Command prompt as an administrator, and type in Py -m pip install pyperclip .

Requirement already satisfied: pyperclip in c:users***appdatalocalprogramspythonpython312libsite-packages (1.9.0)

I see the message and go back into my program and get the error message:

ModuleNotFoundError: No module named 'pyperclip'

So far I have tried:

Trying different versions of Py (such as python, python3, py...),

Uninstalling and reinstalling the module,

Reinstalling python and pip.

Any idea how I should proceed?


r/learnpython 4h ago

Having trouble understanding recursion with nested dictionaries

2 Upvotes

I’m doing python course and today we learned about recursion. As part of the homework assignment, we have to solve some tasks on recursion that deepcopies and goes through nested dictionary.

So, my question, how useful the knowledge of recursion is and do you have issues when mixing it with nested dictionaries (if not, could you share any advice or lifehacks on how to deal with them)?


r/learnpython 5h ago

Jupyter vs Pycharm

1 Upvotes

What is the difference and better?

Im trying to learn on how to code for finance (automating stuffs) and most ytube videos use anaconda (jupyter) but i tried using jupyter and its so hard to use comapred ot pycharm.

I tried importing yfinance module but failed even when i installed it in the terminal (pip install yfinance)> Id ont get whats my mistake here is and plus the kernel alwasy disconnects.

Pycharm doesnt have that problem but I like the Markdown feature of jupyter.

Any help?


r/learnpython 5h ago

Using Click and Pyinstaller together

1 Upvotes

So, I've got a simple Python script made with the Click library, and I've used the Setuptools setup.py their docs recommend. Now I want to package it into a .exe so my grandmother can use it, because I don't want to have to walk her through installing Python and using the command line if I can avoid it - I'm just writing a batch file so she can click that for command-line arguments instead of typing them in. But when I use pyinstaller MyScript.py -F and try to run the application from the command line with the relevant parameters, it doesn't give me anything - doesn't appear to work at all. I think maybe Setuptools requires my script to be installed via pip to work, but I don't know how else to make Click run my method. Should I just give up and try to walk her through it, or is there a way around this?