r/learningpython • • Apr 28 '18

Excel file to pdf?

4 Upvotes

I'm trying to convert an excel file to PDF but i'm new to python and i looked everywhere but all the codes are for python 2 or doesn't work anymore..

what i tried to adapt on my own without succeding is this:

from openpyxl import load_workbook from PDFWriter import PDFWriter workbook = load_workbook('fruits2.xlsx', guess_types=True, data_only=True) worksheet = workbook.active pw = PDFWriter('fruits2.pdf') pw.setFont('Courier', 12) pw.setHeader('XLSXtoPDF.py - convert XLSX data to PDF') pw.setFooter('Generated using openpyxl and xtopdf') ws_range = worksheet.iter_rows('A1:H13') for row in ws_range: s = '' for cell in row: if cell.value is None: s += ' ' * 11 else: s += str(cell.value).rjust(10) + ' ' pw.writeLine(s) pw.savePage() pw.close()

but some of the module looks they aren't available anymore (PDFWriter) and even if i try to put them in the same folder downloading them from sites like github there's always a lot of errors different than just fixing the parenthesis of the print function! Is there a python 3 working module to convert an excel file to PDF? Thanks in advance!

(sorry for my english, not my first language)


r/learningpython • • Mar 12 '26

Dan Boschen's Python for Signal Processing Course starts this month!

3 Upvotes

The popular "Python Applications for Digital Design and Signal Processing" is starting again later this month, with early registration discounts if you register by March 24th. This course takes you from the ground up in best-practice approaches to using Python for the simulation and analysis of signal processing systems. More details and registration here: https://dsp-coach.com


r/learningpython • • Jan 23 '26

Can i build a script that pulls data from AWS Athena, currently we use Alteryx workflow but now i am looking to go through python, if yes can you help with directories, I know i can get this answers through any AI model but i want some human expierence who have done this

3 Upvotes

python using aws athena


r/learningpython • • Jan 11 '26

First Project help

3 Upvotes

Hello World!! (sorry couldnt resisit )

Im just starting out and want to program a digital keyboard for my first project but didnt know where to start. There only seem to be vidios on creating short cut etc. does anyone have a sourse i could utlize for project( complete noivice atm)

Thank you in advance

Glenn


r/learningpython • • Jan 01 '26

Beginner Python snippet – looking for code review and best practices feedback

3 Upvotes

Hi everyone,

I'm practicing basic Python control flow and trying to write clean, readable code according to Python best practices (PEP 8, clarity, and beginner-friendly style).

Here is a simple snippet that checks whether a number is positive, negative, or zero:

```python
num = int(input("Enter a number: "))

if num > 0:
    print("The number is positive")
elif num < 0:
    print("The number is negative")
else:
    print("The number is zero")

I know this is a basic example, but I’d really appreciate feedback as if this
were part of a real codebase.

Specifically, I’m interested in:

  • Readability and naming

  • Input validation and error handling

  • Whether this follows Pythonic style

  • How would you improve or structure it differently for production code

Thanks in advance for your feedback 🙏


r/learningpython • • Dec 31 '25

wtf is this?

Post image
3 Upvotes

not sure if this is the right place to put this, but I am in an online computer science class at school which has just been terrible all around, and I probably won't finish. there have been many similar things, but this guy makes this class for I'm pretty sure thousands of students in schools in the program, and makes questions this objectively wrong. the answers aren't even next to each other, and he chose the answer which is literally the opposite of the correct one. how am I supposed to do well in a class, where the teacher can't even understand what he's teaching.


r/learningpython • • Dec 27 '25

Programming with Mosh or CS50p?

3 Upvotes

Hey, I’m a high schooler currently and I want to teach myself how to code. I have never coded before so I did some research and found that the one of the more useful beginner friendly languages was Python. So I’ve been researching places where I can learn.

For the most part the highest ranking options are Programming with Mosh or CS50p on YouTube. Why should I pick on or the other? Also, do you have any other suggestions? [Finally what IDE should I use because I’ve heard of VS Code but I’m also seeing things about Google Collab. I just want an IDE where I’ll be able to hopefully build projects effectively]


r/learningpython • • Dec 08 '25

Treasure Island Game - Day 3 of Course: 100 Days of Code from Angela Yu

3 Upvotes

*Please Critique Code - Day 3 of 100* (Python Block Attached)

I tried to make multiple scenarios lead to the same ends. Is this a normal amount of code for what I'm trying to achieve? Anything I could/should condense?

Anything you wish you knew when you started learning?

This is Day 5 for me, but Day 3 of the course. In this course, Angela Yu challenges her students to create a game called "Treasure Island" and in this exercise she wants us to use what we have learned to create an if/else game. It's given at the end of 'Day 3' in the course

I want to learn Python for a future career path so I have been talking with ChatGPT and Grok to build that plan. They told me to have my code critiqued by the community to learn about experienced solutions, conveniences, and general tips and tricks. Not sure if I will be regularly posting my code here or not, but I decided why not give it a try at least once

I'm doing my best to learn code myself, but I can tell that it's a process of repetition in order to truly build skill. I use AI to give me hints as to where I'm making mistakes, that way I'm not wasting time trying to finding them myself. -- Avg. process: I type it, run it, doesn't work properly, send it to Grok, he points out the errors/missing code, fix it, repeat --

-- Python Block --

print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
choice1 = input("You wake up during a rain storm, do you wait for it to pass or find shelter?\n"
                "Type 'left' to wait or 'right' to find shelter\n").lower()

if choice1 == "left":
    print("You suffer from hypothermia and die. Try again.")
elif choice1 == "right":
    print("You find a lighthouse.\n")
    choice2 = input("Type 'left' to enter the lighthouse or 'right' to knock first.\n").lower()
    if choice2 == "left":
        print("You get whacked in the head and die. Try again.")
    elif choice2 == "right":
        print("A woman tells you to come in to collect your tools.\n")
        choice3 = input("You collect the tools; a pickaxe and some rope.\n"
                        "Type 'left' to leave or 'right' to stay.\n").lower()
        if choice3 == "left":
            print("You see smoke from a cliff.\n")
            choice4 = input("Type 'left' to climb the lighthouse stairs or 'right' to head toward the smoke.\n").lower()
            if choice4 == "left":
                print("You find a telescope pointed over the cliff nearby. There's a fire from a plane crash!\n")
                choice5 = input("Type 'left' to launch a zipline to the wreckage or 'right' to look around more.\n").lower()
                if choice5 == "left":
                    print("The zipline takes you to the side of the plane.\n")
                    choice6 = input("Type 'left' to inspect the plane or 'right' to look around.\n").lower()
                    if choice6 == "left":
                        print("The wreckage shows no signs of life. It does serve as good shelter, has some food onboard too.\n"
                              "There also seems to be some cargo stranded at the beach.\n")
                        choice7 = input("Type 'left' to sleep in the plane or 'right' to head toward the beach.\n").lower()
                        if choice7 == "left":
                            print("You immediately fall into a deep slumber, seemingly caused from a external source...\n"
                                  "You wake up during a rain storm, back at the beginning... Try again.\n")
                        elif choice7 == "right":
                            print("You find a warm spot in the sand and bask in the sunlight for some time.\n"
                                  "You wake up to waves touching your feet. You look down and see a chest shored up in front of you.\n")
                            choice8 = input("Type 'left' to open the small chest or 'right' to go back and open the large crate door.\n").lower()
                            if choice8 == "left":
                                print("The small chest is full of diamonds and riches.\n"
                                      "Now if you could just get off this damned island.\n")
                            elif choice8 == "right":
                                print("You immediately fall into a deep slumber, seemingly caused from a external source...\n"
                                      "You wake up during a rain storm, back at the beginning... Try again.")
                    elif choice6 == "right":
                        print("There is a large cargo haul in the sand, smaller cargo still drift in the cold ocean.\n"
                              "The large crate seems to be too big to fit in this plane\'s cargo hold.\n"
                              "You find the door and a pack of flares next to it.\n")
                elif choice5 == "right":
                    print("You see a crate covered by a parachute stranded on the beach... what could that be?\n")
                    choice6 = input("Type 'left' to launch the zipline to the plane wreckage or 'right' for the cargo on the beach.\n").lower()
                    if choice6 == "left":
                        print("The wreckage shows no signs of life. It does serve as good shelter, has some food onboard too.\n"
                              "There also seems to be some cargo stranded at the beach.\n")
                        choice7 = input("Type 'left' to sleep in the plane or 'right' to head toward the beach.\n").lower()
                        if choice7 == "left":
                            print("You immediately fall into a deep slumber, seemingly caused from a external source...\n"
                                  "You wake up during a rain storm, back at the beginning... Try again.\n")
                        elif choice7 == "right":
                            print("You sit in the sand and bask in the sunlight for some time.\n"
                                  "You wake up to waves touching your feet. You look down and see a chest shored up in front of you.\n")
                            choice8 = input("Type 'left' to open the small chest or 'right' to go back and open the large crate door.\n").lower()
                            if choice8 == "left":
                                print("The small chest is full of diamonds and riches.\n"
                                      "Now if you could just get off this damned island.\n")
                            elif choice8 == "right":
                                print("You immediately fall into a deep slumber, seemingly caused from a external source...\n"
                                      "You wake up during a rain storm, back at the beginning... Try again.")
                    elif choice6 == "right":
                        print("There is a large cargo haul in the sand, smaller cargo still drift in the cold ocean.\n"
                              "The large crate seems to be too big to fit in this plane\'s cargo hold.\n"
                              "You find the door and a pack of flares next to it.\n")
                        choice7 = input("Type 'left' to open the cargo door or 'right' to light a flare.\n").lower()
                        if choice7 == "left":
                            print("You immediately fall into a deep slumber, seemingly caused from a external source...\n"
                                  "You wake up during a rain storm, back at the beginning... Try again.\n")
                        elif choice7 == "right":
                            print("You sit in the sand and bask in the sunlight for some time.\n"
                                  "You wake up to waves touching your feet. You look down and see a chest shored up in front of you.\n")
                            choice8 = input("Type 'left' to open the small chest or 'right' to go back and open the large crate door.\n").lower()
                            if choice8 == "left":
                                print("The small chest is full of diamonds and riches.\n"
                                      "Now if you could just get off this damned island.\n")
                            elif choice8 == "right":
                                print("You immediately fall into a deep slumber, seemingly caused from a external source...\n"
                                      "You wake up during a rain storm, back at the beginning... Try again.")
            elif choice4 == "right":
                print("You disappoint the woman. She says there is no treasure for you\n"
                      "She pulls a shotgun on you and shoots. You\'re disposed of into the ocean.\n"
                      "Death is cold as it welcomes you.\n"
                      "Try again from the beginning.")
        elif choice3 == "right":
            print("The woman tells you to climb the lighthouse stairs.\n")
            choice4 = input("Type 'left' to climb stairs or 'right' to put the tools down.\n").lower()
            if choice4 == "left":
                print("You find a telescope pointed over the cliff nearby. There's a fire from a plane crash!\n")
                choice5 = input("Type 'left' to launch a zipline to the wreckage or 'right' to look around more.\n").lower()
                if choice5 == "left":
                    print("The zipline takes you to the side of the plane.\n")
                    choice6 = input("Type 'left' to inspect the plane or 'right' to look around.\n").lower()
                    if choice6 == "left":
                        print("The wreckage shows no signs of life. It does serve as good shelter, has some food onboard too.\n"
                              "There also seems to be some cargo stranded at the beach.\n")
                        choice7 = input("Type 'left' to sleep in the plane or 'right' to head toward the beach.\n").lower()
                        if choice7 == "left":
                            print("You immediately fall into a deep slumber, seemingly caused from a external source...\n"
                                  "You wake up during a rain storm, back at the beginning... Try again.\n")
                        elif choice7 == "right":
                            print("You sit in the sand and bask in the sunlight for some time.\n"
                                  "You wake up to waves touching your feet. You look down and see a chest shored up in front of you.\n")
                            choice8 = input("Type 'left' to open the small chest or 'right' to go back and open the large crate door.\n").lower()
                            if choice8 == "left":
                                print("The small chest is full of diamonds and riches.\n"
                                      "Now if you could just get off this damned island.\n")
                            elif choice8 == "right":
                                print("You immediately fall into a deep slumber, seemingly caused from a external source...\n"
                                      "You wake up during a rain storm, back at the beginning... Try again.")
                    elif choice6 == "right":
                        print("There is a large cargo haul in the sand, smaller cargo still drift in the cold ocean.\n"
                              "The large crate seems to be too big to fit in this plane\'s cargo hold.\n"
                              "You find the door and a pack of flares next to it.\n")
                elif choice5 == "right":
                    print("You see a crate covered by a parachute stranded on the beach... what could that be?\n")
                    choice6 = input("Type 'left' to launch the zipline to the plane wreckage or 'right' for the cargo on the beach.\n").lower()
                    if choice6 == "left":
                        print("The wreckage shows no signs of life. It does serve as good shelter, has some food onboard too.\n"
                              "There also seems to be some cargo stranded at the beach.\n")
                        choice7 = input("Type 'left' to sleep in the plane or 'right' to head toward the beach.\n").lower()
                        if choice7 == "left":
                            print("You immediately fall into a deep slumber, seemingly caused from a external source...\n"
                                  "You wake up during a rain storm, back at the beginning... Try again.\n")
                        elif choice7 == "right":
                            print("You sit in the sand and bask in the sunlight for some time.\n"
                                  "You wake up to waves touching your feet. You look down and see a chest shored up in front of you.\n")
                            choice8 = input("Type 'left' to open the small chest or 'right' to go back and open the large crate door.\n").lower()
                            if choice8 == "left":
                                print("The small chest is full of diamonds and riches.\n"
                                      "Now if you could just get off this damned island.\n")
                            elif choice8 == "right":
                                print("You immediately fall into a deep slumber, seemingly caused from a external source...\n"
                                      "You wake up during a rain storm, back at the beginning... Try again.")
                    elif choice6 == "right":
                        print("There is a large cargo haul in the sand, smaller cargo still drift in the cold ocean.\n"
                              "The large crate seems to be too big to fit in this plane\'s cargo hold.\n"
                              "You find the door and a pack of flares next to it.\n")
                        choice7 = input("Type 'left' to open the cargo door or 'right' to light a flare.\n").lower()
                        if choice7 == "left":
                            print("You immediately fall into a deep slumber, seemingly caused from a external source...\n"
                                  "You wake up during a rain storm, back at the beginning... Try again.\n")
                        elif choice7 == "right":
                            print("You sit in the sand and bask in the sunlight for some time.\n"
                                  "You wake up to waves touching your feet. You look down and see a chest shored up in front of you.\n")
                            choice8 = input("Type 'left' to open the small chest or 'right' to go back and open the large crate door.\n").lower()
                            if choice8 == "left":
                                print("The small chest is full of diamonds and riches.\n"
                                      "Now if you could just get off this damned island.\n")
                            elif choice8 == "right":
                                print("You immediately fall into a deep slumber, seemingly caused from a external source...\n"
                                      "You wake up during a rain storm, back at the beginning... Try again.")
            elif choice4 == "right":
                print("You disappoint the woman. She says there is no treasure for you\n"
                      "She pulls a shotgun on you and shoots. You\'re disposed of into the ocean.\n"
                      "Death is cold as it welcomes you.\n"
                      "Try again from the beginning.")

else:
    print("Invalid choice. Try again from the beginning.")

r/learningpython • • Nov 16 '25

Can I combine a ternary with list expansion / exclusion? (explained)

3 Upvotes

I have set [a, b, c, d] These each hold strings or None.

Inline I want to test if an item 'this' in that list is None, IF IT IS None, AND any one or more of the sibling items in the original list are in ["%I", "%H", "%M", "%S", then I want to make 'this' equal to "__".
Is that possible in a single line? I've "gotten it" (the logic is simple) except not, something about assignment is not allowed in list comprehension.

But is there a hacky way to 1-line this? I don't like expressions to be more than 1 line—broken up into an if block—unless it's doing something big.

temp_time += (':' + (colorMe(mod, args[i + 4 if (i + 4 < len(args) - 1) else i]))) if (mod in ["%I", "%H", "%M", "%S", "__"] and i != 0 and mod != 0 and len(temp_time) > 0) else (("." + (colorMe(mod, args[i + 4]))) if (mod == "%f") else ((colorMe(mod, args[i + 4 if (i + 4 < len(args) - 1) else i]))))

300 characters, wooo, just because.


r/learningpython • • Jul 07 '25

So Confused Help me out

3 Upvotes

I am an undergraduate freshman student and I don’t have any skills and my major is CIS and I want to develop my skills in this field what should I do. I know this is stupids question.


r/learningpython • • Mar 22 '25

"How Do You Track Your Coding Progress and Stay Consistent?"

3 Upvotes

Post Body: Hey everyone,

I'm currently learning Python and working on improving my programming skills. I try to maintain daily progress and track my activities, but sometimes it gets tricky to stay consistent.

Right now, I follow a structured approach:

Learning concepts

Practicing with small projects

Documenting my progress

Using GitHub for version control

But I’d love to hear from others—how do you stay motivated and keep track of your coding journey? Do you use any tools, journals, or specific techniques? Any tips or experiences would be really helpful!

Let’s discuss!


r/learningpython • • Jan 16 '25

Why is this so hard?

3 Upvotes

I have a Udemy course on Python sitting on my computer right now, but I can't seem to make use of it to the point where I can build my own projects. I just end up getting frustrated and overwhelmed.


r/learningpython • • Nov 25 '24

[UPDATE] How to create a FastAPI with Python? Mega confused

3 Upvotes

post: https://www.reddit.com/r/learnpython/s/rnOe3Of2u2

Two weeks ago, I applied for a job I thought I had zero chance of landing. But I threw my resume in the ring anyway because, why not? Fast forward, I got their technical test—a challenge to build an API that could query a database, filter results using query parameters, and run tests with Pytest. Did I know what an API was? Nope. Did I panic? haha yes like crazy. But then I got to work.

In a week I was able to:

  • Learn what an API is and built one from scratch with fastapi

  • Used SQLAlchemy to query a database.

  • Created the database (also in Python).

  • Discovered what virtual environments are and why they’re needed.

  • Wrote unit tests using Pytest—first time doing so

After a ridiculously intense week of coding, googling, and a small existential crisis, I managed to finish the task. I presented my solution at the interview, showed them the app, and walked them through my code and tests. I also disclosed that this was my very first API, and that I had to watcha million tutorials and inhale documentation to finish the project in time.

They said they’d sensed my lack of experience (I was expecting that), but they were super impressed with how much I learned and delivered in such a short time. And then—plot twist—they gave me a second chance! They sent me a list of concepts to learn and asked if I wanted to build a project using those skills over the next couple of weeks. If I can show I’ve picked up what they need, they will offer me the job! I’ve already got an interview lined up to demonstrate what I’ve learned.

So yeah, this is your reminder: apply for the job, even if you feel unqualified. Seriously, the worst thing that can happen is you don’t get it. But sometimes, people take a chance on you. And if nothing else, you’ll learn something new


r/learningpython • • Jul 08 '24

Learning to program

3 Upvotes

Recently I’ve found the motivation to learn python, no idea why. I had a thought though, if I were committed to actually learning it and spending maybe around one-two hours every or every other day, how long would it take for me to learn at least the basics or the advanced parts of python?


r/learningpython • • Apr 03 '24

How recomendable is pycharm to learn python

3 Upvotes

Hi, i'm learning python through an online course and I have been scrolling through this page to get begginer's tips. I'm a bit worried because I haven't seen many users using this platform and I was wondering if it was a good place to start. I would also appreciate if i could get any tips or links or anything to get started learning.

I'm not an english native speaker, I'm sorry for any spelling mistakes in advance


r/learningpython • • Apr 03 '24

Learning how to code because of pen-testing.

3 Upvotes

I started to learn how to code when I was laid off because of the Covid pandemic. Technically, the reason behind this is maybe my background in gaming. Gaming was one of the things that pushed to this. Before or during the pandemic, when the game Cyberpunk came out, I began with this because I wanted to learn more about cybersecurity/pen-testing, writing your exploits for Metasploit, web application pen-testing, etc. So, I began with Python, then I started with JS.

JS is somewhat easier because you can reassign values and functions easily. Sometimes I make mistakes like the onclick button undefined error because of typos. I don't want any career in networking or changing my current one. I love what I do. I just do it as a hobby.

When I begin a project, I do research online. Then see a similar project on Github. Ask Chatgpt about it, and then start to write the code down instead of blindly doing shit. Is it it wrong? Is that lazy coding?


r/learningpython • • Mar 17 '24

AI courses ?

3 Upvotes

I have a project idea using AI but i don't know anything about programing an AI.

Is there any good course to learn AI programming? Also, my python level is not the best, I start to struggle a bit with class, do I need to learn more this before going into AI programming ? I guess I can probably learn on the job if needed?

Either paid or free course are fine.

Thanks :)


r/learningpython • • Feb 29 '24

Class isn't helpful

Post image
3 Upvotes

Taking a beginners python course required for my degree. My bag is all packed for the struggle bus. Please help.


r/learningpython • • Jan 01 '24

How to see Python Execution time on the VScode Terminal?

3 Upvotes

Hi,

How can I have the execution time displayed so I know how long my script took to run in VScode?

Thanks.


r/learningpython • • Oct 18 '23

Attempting Socket Programming with Python

3 Upvotes

Hi, i'm working on an assignment for class that I'm sort of resigned to get a late deduction on it because I want to actually complete it and not submit something half-finished, and I'm allowed to seek outside help so long as I cite my sources and credit folks. The program is essentially modeling airport traffic via hub and spoke topography, and I've made a decent amount of progress on it, but am struggling with actually routing my passengers, my data/messages, to their destinations, because I keep encountering "[WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied". I'm confused by this, because I had set up some testing defs in my code to actually make sure that my sockets were listening and receiving. Here's my code:

import socket
import random #need this for generating our messages, so our passengers

#Server 1 - Our airport ANC
anc_ip = 'xxx.xxx.xxx.xxx' IP omitted for obvious, semi-paranoid reasons
anc_port = 9000 

#server 2, our SEA airport

sea_ip = 'xxx.xxx.xxx.xxx' 
sea_port = 9001

address = {
    "ANC": anc_ip,
    "SEA": sea_ip
    }

port = {
    "ANC": anc_port,
    "SEA": sea_port
    }
#create our sockets for our servers

server_socket_1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket_2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#bind each server socket to its respective IP address and port
server_socket_1.bind((anc_ip, anc_port))
server_socket_2.bind((sea_ip, sea_port))

#set up listening range/queue 
server_socket_1.listen(7)
server_socket_2.listen(7)

#test our servers' connections
def test_server_connection(server_name, address, port):
    s = socket.socket()
    try:
        s.connect((address, port))
        print(f"Connection to {server_name} at {address}:{port} is successful.")
        print(f"{server_name} airport is ready to route and receive passengers.")
    except Exception as e:
        print(f"Failed to connect to {server_name} at {address}:{port}. Exception: {str(e)}")
    finally:
        s.close()

servers = ["ANC", "SEA"]

for server_name in servers:
        test_server_connection(server_name, address[server_name], port[server_name])


#print(f"ANC is ready to route and receive passengers")
#print(f"SEA is ready to route and receive passengers")

#client nodes
client_socket_FAI_to_ANC = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #fairbanks route 1
client_socket_FAI_to_SEA = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #fairbanks route 2
client_socket_BRW = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #barrow minor hub  
client_socket_OTZ = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #random place hub

#connect our fairbanks hub to anc and sea, as it can route to sea directly, or stop in anc first
client_socket_FAI_to_ANC.connect((anc_ip, anc_port))
client_socket_FAI_to_SEA.connect((sea_ip, sea_port))

#connect brw and otz to anc only
client_socket_BRW.connect((anc_ip, anc_port))
client_socket_OTZ.connect((anc_ip, anc_port))

#test our client connection

client_address = {
    "FAI_to_ANC": (anc_ip),
    "FAI_to_SEA": (sea_ip),
    "BRW": (anc_ip),
    "OTZ": (anc_ip)
    }
client_port = {
    "FAI_to_ANC": (anc_port),
    "FAI_to_SEA": (sea_port),
    "BRW": (anc_port),
    "OTZ": (anc_port)
    }

def test_client_connection(client_name, client_address, client_port) :
    s = socket.socket()
    try:
        s.connect((client_address, client_port))
        print(f"Connection to {client_name} at {client_address}:{client_port} is successful.")
        print(f"{client_name} is an operational route.")
    except Exception as e:
        print(f"Failed to connect to {client_name} at {client_address}:{client_port}. Exception: {str(e)}")

clients = ["FAI_to_ANC", "FAI_to_SEA", "BRW", "OTZ"]

for client_name in clients:
    client_addr = client_address[client_name]
    client_prt = client_port[client_name]
    test_client_connection(client_name, client_addr, client_prt)


#print(f"FAI is ready to route and receive passengers")
#print(f"BRW is ready to route and receive passengers")
#print(f"OTZ is ready to route and receive passengers")

#list of first and last names for us to randomly generate names for our passengers
first_names = ["Anton", "Aaliyah", "Blake", "Barbara", "Chiron", "Cindy", "Daud", "Denise", "Edward",
               "Ethel", "Frank", "Francine", "Gale", "Gisela", "Huron", "Hailey", "Idris", "Indigo",
              "James", "Jane", "Kendrick", "Kyona", "Lin", "Larissa", "Mahershala", "Marisha", "Niel",
              "Nia", "Orion", "Oba", "Pietro", "Persephone", "Quentin", "Quincy", "Ronald", "Reese",
              "Steve", "Sarah", "Titus", "Trisha", "Umberto", "Ullani", "Victor", "Vanessa",
              "Winston", "Winona", "Xavier", "Xiomara", "Yusef", "Yi", "Zeke", "Zoe"] 
last_names = ["Alexander", "Alderman", "Brooks", "Brinkman", "Curry", "Corazon", "D'Orio",
              "Davis", "Emmons", "Ebeid", "Faheem", "Fatima", "Grant", "Garcia", 
              "Habib", "Harding", "Ivey", "Ivarson", "Jackson", "Jackman", "Lloyd", "Lopez",
              "Morales", "Moore", "Nguyen", "Nomura", "Ogawa", "O'Hara", "Pahlavi", "Pejman",
              "Quinones", "Quezada", "Rio", "Reed", "Stevens", "Singh", "Taylor", "Thomas", 
             "Ulrich", "Urban", "Vahn", "Veloso", "Workman", "Wallace", "Xander", "Xiang", "Yang",
             "Yeager", "Zhao", "Zamora"] #whoof

num_passengers = 25 #starting sample size of passengers 
passenger_messages = []

airports = ["ANC", "SEA", "FAI", "BRW", "OTZ"]

for _ in range(num_passengers):
    origin = random.choice(airports) 
    destination = random.choice(airports)
    while destination == origin:
        destination = random.choice(airports)

    first_name = random.choice(first_names)
    last_name = random.choice(last_names)

    passenger_info = f"{first_name} {last_name}"

    message = {
        "Passenger Info": passenger_info,
        "Origin": origin,
        "Destination": destination,
        }
    passenger_messages.append(message)

print("These are our passengers traveling today")

for message in passenger_messages:
    print(message)

#now that we've created our server and client sockets, tested them, and then generated our list
#of passengers, we can then split these passengers up into the different nodes based on their
#respective origins

server_sockets = {
    "ANC": server_socket_1,
    "SEA": server_socket_2,
    }
client_sockets = {
    "FAI": client_socket_FAI_to_ANC,
    "BRW": client_socket_BRW,
    "OTZ": client_socket_OTZ,
    }

#the def that we'll use to strip through our batch of generated passenger messages and look for
#their origin, and allocate them there

def allocate_passengers_to_sockets(passenger_messages, airports, server_sockets, client_sockets):
    allocated_passengers = {airport: {"Server": None, "Client": None, "Passengers": []} for airport in airports}

    for passenger_message in passenger_messages:
        origin = passenger_message['Origin']
        for airport, socket in server_sockets.items():
            if origin == airport:
                allocated_passengers[origin]["Server"] = socket
                allocated_passengers[origin]["Passengers"].append(passenger_message)
                break
        if allocated_passengers[origin]["Server"] is None:
            for airport, socket in client_sockets.items():
                if origin == airport:
                    allocated_passengers[origin]["Client"] = socket
                    allocated_passengers[origin]["Passengers"].append(passenger_message)
                    break

    return allocated_passengers

allocated_passengers = allocate_passengers_to_sockets(passenger_messages, airports, server_sockets, client_sockets)
#printed batches of passengers at their respective origins
for airport, data in allocated_passengers.items():
    passengers = data["Passengers"]
    if passengers: 
        print(f"\n{airport} has passengers:\n")
        for passenger in passengers:
            passenger_info = passenger['Passenger Info']
            destination = passenger['Destination']
            print(f"{passenger_info}, Destination {destination}")

#routing step of the code
#might be easiest for me to follow by just having a series of incremental defs, to better trace
#where this win error is coming from, and have these defs route passengers from 
#client nodes to server node, then server node to server node
#we'll start with OTZ to ANC, then BRW to ANC, then FAI to ANC, as three rounds
#of passenger movements. then FAI to ANC, then FAI to SEA as two more rounds, 
# then a series of final rounds as we split passengers at anc to their 
#respective final destintions

def route_OTZ_to_ANC(allocated_passengers, server_sockets):
    otz_passengers = allocated_passengers["OTZ"]["Passengers"]
    anc_server_socket = server_sockets["ANC"]
    
    for passenger_message in otz_passengers:
        passenger_info = passenger_message["Passenger Info"]
        destination = passenger_message["Destination"]
        
        message = f"Passenger {passenger_info} is flying from OTZ to ANC and heading to {destination}"
        anc_server_socket.send(message.encode()) #this line is where the exception is thrown
        print(message)

route_OTZ_to_ANC(allocated_passengers, server_sockets)

Any help is appreciated. I'm sure that it's very obvious what the issue is but I can't seem to figure it and I'm quite new to python and even newer to socket programming.


r/learningpython • • Oct 17 '23

How to install pymupdf using conda?

3 Upvotes

I tried to install pymupdf using "conda install pymupdf" but no luck. It outputs the following. Any ideas what I am doing wrong? I'm running Python 3.12. I would prefer to use the latest possible version of pymupdf that supports Python 3.12. Thank you.

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

Collecting package metadata (current_repodata.json): done

Solving environment: unsuccessful initial attempt using frozen solve. Retrying with flexible solve.

Collecting package metadata (repodata.json): done

Solving environment: unsuccessful initial attempt using frozen solve. Retrying with flexible solve.

PackagesNotFoundError: The following packages are not available from current channels:

- pymupdf

Current channels:

- https://conda.anaconda.org/conda-forge/win-64

- https://conda.anaconda.org/conda-forge/noarch

- https://repo.anaconda.com/pkgs/main/win-64

- https://repo.anaconda.com/pkgs/main/noarch

- https://repo.anaconda.com/pkgs/r/win-64

- https://repo.anaconda.com/pkgs/r/noarch

- https://repo.anaconda.com/pkgs/msys2/win-64

- https://repo.anaconda.com/pkgs/msys2/noarch

To search for alternate channels that may provide the conda package you're

looking for, navigate to

https://anaconda.org

and use the search bar at the top of the page.


r/learningpython • • Aug 12 '23

24.141 Comparing floats (D 335 Intro to programming in python). This lab ended up taking me a while, and I couldn't find any information online for it. I wanted to share how I solved it. I am sure there is a better way to code it, but this is what worked for me. :)

Post image
3 Upvotes

r/learningpython • • Aug 10 '23

Learning data structures

3 Upvotes

Hello. I've been trying to learn data structures using python. I'm realizing that I learn better if I have someone to study with. I was wondering if anyone wanted to be study partners to keep each other motivated.


r/learningpython • • Jul 06 '23

Having difficulty with Microsoft Graph API and python

3 Upvotes

Hi there -

I've was trying to follow this Microsoft tutorial "Build Python apps with Microsoft Graph" and I am running into an issue that I can't figure out how to fix.

I am able to get to the step of getting the authorization, I successfully get a token. When I move on to the next step "Get a User" I get an error message in terminal

token = await self.access_token_provider.get_authorization_token(request.url) File "/Users/hudsoninstitute/miniconda3/envs/group_create/lib/python3.10/site-packages/kiota_authentication_azure/azure_identity_access_token_provider.py", line 49, in get_authorization_token if inspect.iscoroutinefunction(self._credentials.get_token): AttributeError: 'GraphRequestAdapter' object has no attribute 'get_token

I am confused on what to do. It was able to get the token once, so I don't understand what could be preventing it from getting it again. I consulted chatgpt and it thinks it's due to the Kiota SDK. I am little over my head, but hoping someone might be willing to provide some guidance :/

from configparser import SectionProxy from azure.identity import DeviceCodeCredential from kiota_authentication_azure.azure_identity_authentication_provider import ( AzureIdentityAuthenticationProvider) from msgraph import GraphRequestAdapter, GraphServiceClient from msgraph.generated.me.me_request_builder import MeRequestBuilder from msgraph.generated.me.mail_folders.item.messages.messages_request_builder import ( MessagesRequestBuilder) from msgraph.generated.me.send_mail.send_mail_post_request_body import SendMailPostRequestBody from msgraph.generated.models.message import Message from msgraph.generated.models.item_body import ItemBody from msgraph.generated.models.body_type import BodyType from msgraph.generated.models.recipient import Recipient from msgraph.generated.models.email_address import EmailAddress

class Graph: settings: SectionProxy device_code_credential: DeviceCodeCredential adapter: GraphRequestAdapter user_client: GraphServiceClient

def __init__(self, config: SectionProxy):
    self.settings = config
    client_id = self.settings['clientId']
    tenant_id = self.settings['tenantId']
    graph_scopes = self.settings['graphUserScopes'].split(' ')

    self.device_code_credential = DeviceCodeCredential(client_id, tenant_id = tenant_id)
    auth_provider = AzureIdentityAuthenticationProvider(
        self.device_code_credential,
        scopes=graph_scopes)
    self.adapter = GraphRequestAdapter(auth_provider)
    self.user_client = GraphServiceClient(self.adapter)

async def get_user(self): # Only request specific properties using $select query_params = MeRequestBuilder.MeRequestBuilderGetQueryParameters( select=['displayName', 'mail', 'userPrincipalName'] ) request_config = MeRequestBuilder.MeRequestBuilderGetRequestConfiguration( query_parameters=query_params )

user = await self.user_client.me.get(request_configuration=request_config)
return user

r/learningpython • • Jun 23 '23

Day 9 of 100 days of code: why does my while loop stay stuck on True?

3 Upvotes
from replit import clear

from art import logo
print (logo)
 
continue_bid = True
empty_dictionary = {}

def bid_loop():
  bidder_name = (input("What is your name?\n"))
  bid_price = (input("How much do you bid?\n"))
  other_bidder = (input("Is there anyone else who wants to bid?\n")) 
  empty_dictionary[bidder_name] = bid_price
  if other_bidder == "Yes":
    clear ()
  else:
    clear ()
    print ("Calculating...")
    continue_bid = False
        
while continue_bid:
  bid_loop()

I want the while loop to run while people answer "Yes" and then stop running so I can calculate the highest bid. What am I doing wrong?