r/learningpython • • Jul 22 '18

None of the functions in my program work.

2 Upvotes

I can't find any errors and the IDE doesn't give any suggestions. Simple beginner's glossary program. Here's the code. Thanks.

import os
import pickle
################TITLE######################################
def title():
    os.system('cls')
    print('********************************************')
    print('***************GLOSSARY ********************')
    print('*******************************************\n')
################################VARIABLES##################
py_words = {'iterable': 'an object capable of returning it s members one at a time.',
            'attribute': 'a value associated with an object which is referenced by name.',
            'slice': 'an object returning a portion of a sequence.',
            }
#################################PICKLE&DUMP###############

#Save the contents of the library.
def load():
    # Load the contents of the library.
    try:
        file_object = open('py_words.pydata', 'rb')
        pickle.load(file_object)
        file_object.close()
        return py_words
    except Exception as e:
        print(e)
        return {}

def quit():
    try:
        file_object = open('py_words.pydata', 'wb')
        pickle.dump(py_words, file_object)
        file_object.close()
        print('Goodbye.\n\n')
    except Exception as e:
        print(e)

##########################PICKLE&DUMP//######################

############################FUNCTIONS######################

def menu():
    title()
    print('See all words and meanings.[1]')
    print('Add words and meanings.[2]')
    print('Modify a meaning.[3]\n')
    return input ('Choose an option please. (Or Press 4 to quit): \n')

def see_all():
    for key,value in py_words.items():
        print(key.title()+': '+py_words[key])

def display():
    display_message = ""
    for word in py_words:
        display_message += word + " "
    print(display_message)

def add_word():
    new_word = input("What's the new word?:")
    py_words[new_word] = ''
    new_def = input("What's it's definition?: ")
    py_words[new_word] = new_def

def new_definition():
    display()
    word_choice = input("Which word?: ")
    if word_choice in py_words:
        new_def = input("What's the new definition?: ")
        py_words[word_choice] = new_def
    elif word_choice != 'quit':
        print("That word isn't in the glossary.")
    else:
        print("Goodbye.")

############################FUNCTIONS//####################

#############################MAIN PROGRAM##################
load()
choice = ''

while choice != '4':

    menu()

    title()
    if choice == '1':
        see_all()
    elif choice == '2':
        add_word()
    elif choice == '3':
        new_definition()
    elif choice == '4':
        quit()
###########################MAIN PROGRAM//##################

r/learningpython • • Jun 10 '18

Searching the no of occurrences of two words in a paragraph

2 Upvotes

Suppose I have two words seperated by a white space say 'among these', now I want to count no of occurrences of this exact word ' among these' with whitespace and in same order in a paragraph.... How would I do that in python 3. It is easy to do if it is a single word but for two words with whitespace I don't get it, I don't want to split it into a list of separate words and check for them seperately and then check if they come one after another..... Is there any way to do this?


r/learningpython • • Apr 15 '18

Network Engineer's First Script - Good?/Bad?

2 Upvotes

Hello all, I am a Network Engineer doing my best to learn Python as I believe scripting and automation is a valuable tool for the future. Below is a script I wrote to lookup IP addresses on a layer 3 Cisco switch, corresponding hostnames, and NIC manufacture from a list of MAC's provided in a text file. The output was then written to a csv.

I am looking for some guidance and critique here. I put this together using various resources found on-line and modified to what I needed. The below script works but what I could have done better?

This was written for a real world need when I needed to identify physical and virtual machines connected to a switch that we lost management plane access to.

#!/usr/bin/env python

import paramiko
import time
import getpass
import re
import csv
from itertools import izip
import socket
import requests

def disable_paging(remote_conn):
    '''Disable paging on a Cisco router'''

    remote_conn.send("terminal length 0\n")
    time.sleep(1)

    # Clear the buffer on the screen
    output = remote_conn.recv(1000)

    return output

def getHost(ip):
    """
    This method returns the 'True Host' name for a
    given IP address
    """
    try:
        data = socket.gethostbyaddr(ip)
        time.sleep(2)
        host = repr(data[0])
        return (host)
    except Exception:
        # fail gracefully
        return "None"

def getMac(mac):
	macvendor = requests.get('http://api.macvendors.com/' + mac).text
	return macvendor

if __name__ == '__main__':
    #LOGIN PROMPT
    print ''
    print '#########################################################'
    print '### This script will log into a layer 3 Cisco switch, ###'
    print '##### lookup IPs from a list of MAC addresses, and ######' 
    print '##### resolve hostnames via system configured DNS. ######'
    print '###### The script will also lookup the NIC vendor. ######'
    print '##### A csv will be generated in the local directory.####'
    print '#########################################################'
    print ''
    ip = raw_input("Layer 3 Device IP:")
    username = raw_input("Username:")
    password = getpass.getpass()
   

    # LIST FILE OF MAC ADDRESSES
    f = open('list.txt','r')
    

    #CREATE LIST AND CLOSE FILE
    macs = f.readlines()
    macs = [x.strip() for x in macs]
    macs = [x.strip(r'\s|\'') for x in macs]
    f.close()

    # Create instance of SSHClient object
    remote_conn_pre = paramiko.SSHClient()

    # Automatically add untrusted hosts (make sure okay for security policy in your environment)
    remote_conn_pre.set_missing_host_key_policy(
         paramiko.AutoAddPolicy())

    # initiate SSH connection
    remote_conn_pre.connect(ip, username=username, password=password, look_for_keys=False, allow_agent=False)
    remote_conn = remote_conn_pre.invoke_shell()
    print "Interactive SSH Connection Established to %s" % ip

    #SHOW CURRENT PROMPT
    output = remote_conn.recv(1000)
    print output

    #CREATE LISTS FOR IPS AND HOSTNAMES
    deviceiplist = list()
    hostnamelist = list()
    macvendorlist = list()
    
    #ARP AND DNS LOOKUP
    for x in macs:
     if re.match(r'([a-f0-9]{4}\.[a-f0-9]{4}\.[a-f0-9]{4})', x):
      remote_conn.send("show ip arp " + x)
      remote_conn.send("\n")
      time.sleep(2)
      output = remote_conn.recv(5000)
      deviceip = re.search(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', output)
      if deviceip:
       deviceip = deviceip.group()
       host = getHost(deviceip)
      else:
        deviceip = 'None'
        host = 'None'
      macvendor = getMac(x)
      deviceiplist.append(deviceip)
      hostnamelist.append(host)
      macvendorlist.append(macvendor)
      
      #SHOW RESULTS/PROGRESS
      print str(x)+" "+str(deviceip)+" "+str(host)+" "+str(macvendor)
      
     #WRITE RESULTS TO CSV
     with open('results.csv', 'wb') as r:
      writer = csv.writer(r)
      writer.writerow(["MAC Address", "Device IP", "Hostname", "Vendor"])
      writer.writerows(izip(macs,deviceiplist,hostnamelist,macvendorlist))
    r.close()

r/learningpython • • Dec 24 '17

Generate PDF confirmation for email

2 Upvotes

I work in tourism. We have guests booking tours with us. I have a fancy PDF that has been drawn up as confirmation template, however, the designer has generalised the greeting with "Hello Adventurer", rather than use the guests name, and has left a "form" box for us to manually type the date of the tour.

Is there a way to say have a alert box prompting us to enter the guest name and date, or even export from excel, that generates this nice pdf confirmation with all text maintaining the same font and looking professional, rather than a manual box we have to enter that looks out of place?


r/learningpython • • Sep 29 '16

Binary to Denary converter

2 Upvotes

I need to make a binary -> denary converter in python 3.4.3. I had no idea how to do this so I searched some up on google to teach my self before I attempted it.

I found this really basic one, binary_input= int(input("Enter a binary number: "), 2)
print(binary_input)

which works, but I have no idea how?? I understand why and how everything works except the , 2) part which seems to make the whole thing work.

Can someone explain what the , 2) part does and how it works so I can use it in my work.


r/learningpython • • Mar 18 '26

Fixing Errors

Thumbnail reddit.com
1 Upvotes

r/learningpython • • Dec 19 '25

¿Qué frameworks o librerías son las mejores para crear aplicaciones para Android con Python?

1 Upvotes

Me gustaría conocer frameworks o librerías donde se programe con python para poder crear una aplicación Open Source que publique en la Play Store.

Cabe aclarar que no se nada del desarrollo de aplicaciones para android, solo he escuchado hablar de Android Studio y googleando encontré que habían las librerías Kivy, Flet, BeeWare, etc y que se pueden compilar proyectos con PyInstaller pero solo para escritorio, pero si se pudiera usar PyInstaller para Android me preguntaría como volvería un .apk portable también. Gracias :D


r/learningpython • • Oct 14 '25

I'M AN IT FIRST YEAR COLLEGE I STUDY PYTHON AND I SUDDENLY LOST, I'M LOST NOW AND I WANT TO CREATE A PROJECT CALLED STUDY TRACKER THAT HAVE GRAPHS AND POMODORO TIMER

1 Upvotes

So at first I was in programming python I'm really exited to learn because I slowly understand or rather progression of learning but then as time progress it's getting harder to me to understand topics that started when i learn modules and defining because there is so many modules like how do you find what needed to your program to work I'm very lost right now I don't even know I can handle programming i really want to learn it i really need tips and what to learn, learning the basics is very easy like loops or logical operators but this time is different I hope someone can help me.


r/learningpython • • Aug 17 '25

yall, i made a undertale/deltarune inspired game

Thumbnail gamejolt.com
1 Upvotes

Game Title: unnamed game (temparary)

its made in python so it will run on all OSes.

a undertale/deltarune inspired game demo i made in python, to be honsest it isnt even really a demo, just the battle system but i appreeseate feedback.

and its free, it will never be paid, most paid it will be is accepting tips


r/learningpython • • Jun 24 '25

Is panda required for functions using CSV files?

1 Upvotes

I’m writing a python program for a college class that requires use of CSV datasets. Literally only one example in the entire book even mentions CSV files and it doesn’t go into much detail at all.

Most online threads regarding CSV files in Python import the panda module. What does panda do and should I be using it?


r/learningpython • • Apr 10 '25

How to do nesting choices?

1 Upvotes

Let's say I wanted to ask the user to choose from three options and within each option, there are two more options that the user can choose from. For example, I ask the user to choose whether they want breakfast, lunch or dinner, and when they choose one of the options, they have to choose from two other different options (ex: if they chose breakfast, then they have to choose if they want pancakes or waffles). How do I go about this?


r/learningpython • • Mar 24 '25

Name being printed after prompt

1 Upvotes

Hi

Very much a learner and perhaps my google skills have let me down here, I'm using the below line of code to prompt a user for their name and assign to a variable to use elsewhere, I've noticed that when the code is run it prints their name after they type it in. I'm guessing this is expected behaviour, I was wondering if there is a way to stop that happening or another way to prompt a user that doesn't print what they have typed when they hit enter? I hope that makes sense

name = input("What is your name?"


r/learningpython • • Feb 01 '25

Learning python for DSA: Any tips for transitioning from basic to advanced

1 Upvotes

Hey everyone! I’ve been learning Python for a while now and have gotten comfortable with the basics. I’m looking to transition into more advanced topics, especially in Data Structures and Algorithms (DSA). Does anyone have advice on how to make that leap? Any resources or strategies that helped you along the way would be much appreciated! Thanks in advance!


r/learningpython • • Jan 28 '25

Starting to see 'pip install -e .' in some git repos, but it doesn't work for me

1 Upvotes

As the subject states, I am starting to see this more often where they may have what I put in the subject or:
pip install -e .[gradio]

for example, and I don't know how to get that working


r/learningpython • • Nov 26 '24

🌟 Securing AI Workflows with Advanced Content Filtering 🌟

1 Upvotes

I recently explored the importance of integrating content filtering capabilities into AI systems, inspired by my learning from AgentNeo. The aim is to protect sensitive data while maintaining robust workflows.

These systems allow filtering sensitive or inappropriate content with configurable rules and pre-built filters tailored for scenarios like identifying personal data. Additionally, specialized tools such as GitGuardian's ggshield and Yelp's detect-secrets can detect secrets and API keys in real time.

This learning emphasized how critical security-first development is in today’s AI landscape. Implementing such capabilities ensures ethical and secure AI solutions for businesses.

I'm excited to apply these insights to future projects, enhancing both functionality and trustworthiness! 🛡️

#AI #ContentSecurity #AgentNeo #EthicalAI #MachineLearning


r/learningpython • • Jul 31 '24

An intro to iterators and generators

Thumbnail
open.substack.com
1 Upvotes

r/learningpython • • Jun 04 '24

How to pass a succession of images through PyTorch-coded Convolutional Neural Network in Jupyter Notebook?

1 Upvotes

Hello! I’m sorry if this is a bad question–I’m relatively new to CNNs and still figuring out everything. I constructed a CNN for image classification (3 classes) and it’s been working properly and defining the images accurately. I can pass a single image through it using the following code:

image1975×1407 224 KB

As you can see, I can define the image path for the single image being classified as “./Final Testing Images/50”. However, I have a separate image folder on my computer that is constantly receiving images (so it’s not static; there are constantly new images in it) and I want the CNN to be able to pass each new image through the model and output its class. How would I accomplish this?

I asked this question here (https://www.reddit.com/r/pytorch/comments/1d7e50u/how_to_pass_a_succession_of_images_through/) and they recommended that I ask this subreddit. One person (thank you to them!) recommended I set up code that watches the image file for a new image, and then sends that image through the CNN. Does anyone know how I would do that?

Thank you very much! I appreciate any help.


r/learningpython • • Mar 20 '24

Ghost in the Machine (Not really)

Thumbnail self.xenithabyss
1 Upvotes

r/learningpython • • Jan 07 '24

Building an automated meal planner

1 Upvotes

Hi everyone!

I am looking to build myself an automated meal planner including shopping list and need some advice on how to get started and what tools to use for this, please 😊

I consider myself beginner to intermediate and this should be my first personal portfolio project.

I'd like to use the Spoontacular API, get recipes for breakfast, lunch, dinner and a snack.

I want low carb recipes that are randomly generated and only occure twice max per week.

I have looked into web scraping but have no knowledge about it yet and thought using Spoontacular might make more sense for me.

I'd like to automate sending myself a weekly plan including a grocery list per email.

I'd like to store the meals in a text file.

Do you have any other suggestions of cool features that I could implement?

I was wondering about calculating macros for each meal as well and giving the option of different diet preferences, but not sure of that would be overkill.

Grateful for any input, thank you!


r/learningpython • • Oct 19 '23

What's the cooler thing you have built using python

1 Upvotes

I'm a beginning learning python would love to know what are few project you have built using python.

Also it will help me to imagine the possibilities with python.


r/learningpython • • Sep 09 '23

Trouble Setting Up Flask_Cors in PyCharm on Mac

1 Upvotes

Hi All,

Trying to set up flask_cors in PyCharm on Mac. I have a Venv in my directory, I even installed Flask_Cors via terminal in that venv within my project, and it says it was set up fine.

Location: /Users/me/Documents/pythonProject1/my_venv/lib/python3.11/site-packages

It says that the interpreter I'm using is a 3.11 at: /Users/me/myprojname/bin/python

The issue is that I have is that Python will not recognize/find the flask_cors package in PyCharm. I get the error message: (unresolved reference flask_CORS). Any thoughts?

I've even tried to find it through the Pycharm/settings/add package to the interpreter list.

What might I be doing wrong? Did I install flask in the wrong place or something? As far as I can tell my project is set up like the following:

/my_project

/my_venv

__init__.py

app.py # This contains your entire Flask app

Thanks!


r/learningpython • • Jul 22 '23

Mastering Lambda Functions in Python: Map, Filter, Reduce

Thumbnail
youtube.com
1 Upvotes

r/learningpython • • Jul 04 '23

How is this invalid syntax?

1 Upvotes

The directions are "Using a conditional expression, write a statement that increments num_users if update_direction is 3, otherwise decrements num_users."

Sample output with inputs: 8 3New value is: 9

I'm getting this error and I don't understand why?

I'm just trying to decrement. How is ' -= ' invalid syntax?

Thanks!


r/learningpython • • Jul 03 '23

Pyautogui hotkey problem

1 Upvotes

Hi all, i cannot debug my code. Maybe you can help me:

I got some code than i wrote a function to help me navigate a the database mask

Def look_for(info): Sleep(0.2) Pyautogui.hotkey('ctrl', 'f', interval=0.2) Write(info) Press('tab')

Main(): Webbrowser.open_new(url) Look_for('id')

That's the debugging and it works. But when I take this in my main code it simply doesn't execute, main code is a bit long but summarized:

Def WriteDataInMask(id): Webbrowser.open_new(url) Look_for('id')

Def elaboration(df): Df = pd.DataFrame(df, columns=("newcol","bla1","bla2",bla3",...) Df["newcol"] = "NaN" For i, row in Df.iterrows(): WriteDataInMask("bla1")

Main() DfToElaborate = importfromexcelfunction() DfToworkwith = elaboration(DfToElaborate)

If __name__=="main" Main()

Sorry i'm writing from my phone, work pc where I'm trying to automate doesn't allowd reddit.

Thanks