r/learningpython • • Mar 02 '19

Beginner help understanding for statements

2 Upvotes

Right now I am having trouble understanding for statements and if anybody could help explain I would be eternally grateful. Right now the code looks this this.

w = [ 'jasper', 'merball', 'critterbob' ]

for x in w: print(x)

Its prints out

jasper merball critterbob

I sort of understand this but the real trouble is when I print (x) only critterbob is returned. Can anybody please explain why this happens?

Ps: Don't judge the strings they are all family nicknames :D thanks a ton.


r/learningpython • • Feb 24 '19

Write list of list to CSV?

2 Upvotes

Hi, I would like to ask on how we can write these set of list which has list in it?
Target output on csv is like this(attached).

Image -> https://imgur.com/a/mqc9TnC

MY CODE:

opo = ['device1', 'device1', 'device1']
intfname = [['HundredGigE0/2/0/0', 'HundredGigE0/2/0/0.242', 'HundredGigE0/2/0/0.244 l2transport', 'HundredGigE0/2/0/1', 'HundredGigE0/2/0/0.244'], ['TenGigabitEthernet1/1/0.138'], ['TenGigE0/1/0/15']]
descname = ['0/2/0/0info1', '0/2/0/0.242info2', '0/2/0/0.244info3']
 
## EXPORT AS CSV
with open('intlist.csv', 'w', newline='') as updatecsv:
    write = csv.writer(updatecsv, delimiter=',',lineterminator='\n')
    write.writerows(zip(opo,intfname,descname))
updatecsv.close()
print ("Done...")

Thank you


r/learningpython • • Feb 16 '19

Thread Modes How to store the value from variable into list & run a statement then put in variable

2 Upvotes

Hi, I have 2 question regarding this code,

1st I want to put all the values into list from the variable?

Example, Im grepping multiple ip from a file.

f = os.popen('grep '+ ip[i] + ' *') 
now = f.read() 
print ("output: ", now)

2nd from #1 there will be 2 possible output 1 is no match and 2 will be the matched output from grep.

If there's no match then I should put a word none in the list while if there a match I need to put exist?

I think I can do it using if else but totally blind in where to start haha. Still searching for sample command.

Thanks


r/learningpython • • Feb 10 '19

taking a file name (full path) as an argument?

2 Upvotes

Hi, I'm working on a script that takes in a file and parses it line by line.

Right now I have the file path hard coded.

I tried searching a bit but I don't think I have the language to describe what I'm trying to do properly.

I'd love that if I ran

$python3 textParser.py /root/documents/file

then later I could be like:

fileName = argument
file = open(filename,"r")
magicOccurs()
file.close()

Then the program would be, while still a hack, much more scriptable (ex with bash)

How can I translate this logic into code?

Thanks for the help


r/learningpython • • Feb 04 '19

Splitting Columns Based on Rows with Varying Lengths

2 Upvotes

I have a DataFrame like the following:

Tool_NameMeasurements
Tool_A02_04_06
Tool_B02_04
Tool_C02_04_06_08

I would like to split it into the following:

Tool_NameMeasurement 1Measurement 2Measurement 3Measurement 4
Tool_A020406
Tool_B0204
Tool_C02040608

Using:

df[['Measurement 1','Measurement 2','Measurement 3','Measurement 4']] = df.Measurements_Name.str.split("_", expand=True,)

I get a "ValueError: Columns must be same length as key"

What is the correct way to do this?


r/learningpython • • Jan 09 '19

Telnet to switch from jump start server(linux)

2 Upvotes

Hi,

I just want to ask if anyone here has script or idea what method, library etc should. My target is to SHH first from my workstation to Linux jumpstart server then from jumpstart server I'll access the network devices like switch and routers to execute some show commands.

PYTHON SCRIPT ----SSH---> Jumpstart server(ubuntu) ----Telnet---> Network Devices (Cisco)

import base64, time, sys
import paramiko, getpass, telnetlib
 
#ENTER Password
##pword = getpass.getpass('Password: ')
 
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname='xxxxx', username='xxxxx', password='xxxxx')
stdin, stdout, stderr = client.exec_command('pwd')
 
for line in stdout:
    print('Teton: ' + line.strip('\n'))
    client.close()

I'm now able to access the jumpstart server from my PC, the next thing is just to telnet from the jumpstart server?

Thank you


r/learningpython • • Nov 12 '18

Checking " in lines

2 Upvotes

I need help checking for " in lines and if there is anything in between i need it converted to a 1 or a specific text Example.

Line 1: Ronnie Cant Swim Without "Parcher nomad

Line 2: Boomer "Its a robot flying" Catcho

And I need to convert everything inside the " with a 1 or anything in between this is PER LINE.

Expected output

Line 1: Ronnie Cant Swim Without 1

Line 2: Boomer 1 Catcho

The issue is, currently I have a Strip and Split that are checking for Keywords in all the lines. so cant go through all the text file twice.


r/learningpython • • Aug 04 '18

How to do an alternating offset with pandas.date_range() ?

2 Upvotes

I'm trying to do an itinerary for work involving tasks done bi-weekly (Sunday and Wednesdays). I'm trying to do it with pandas.date_range, but I don't know which offset alias to use, since the frequency isn't fixed, but varies between three and four days. How can I specify that? Maybe I need to use the date time module instead? I'm reading the documentation, but no luck so far.

All help will be appreciated, thanks!


r/learningpython • • Aug 01 '18

tkinter, after and input = no worky

2 Upvotes

I am very new to Python. I apologize for my ignorance.

I am working on a project that would collect visitor information via a swipe of the visitors drivers license.

I am stuck on building the GUI and then waiting for input simultaneously. Once the card is swiped I want to parse the data and fill the input boxes. At that point all the visitor has to do is click submit.

The code I have below causes the GUI to crash when I am using the license_data with the input function. However when I use the preloaded variable with sample data it works fine.

Any help or direction would be much appreciated.

from tkinter import *
import datetime

def add_text():
       label1 = Label(root, text="Guest Data Submitted.")
       label1.pack()

def clear():
	visitor_name_text_box.delete(0,'end')
	lnumber_text_box.delete(0,'end')
	state_text_box.delete(0,'end')

def data_collector():
	#Test data without using input
	license_data = '%OHCOLUMBUS^BOB$JIM$R$^2725 S READY LINE RD^?;6360231920193567=210319780304?+1043031  D A             1603180BLNBLU                              Y&//_)     ?'
		
	#license_data = input()
		
	fname = ((license_data.split("$"))[1].split("$")[0])
	lname = ((license_data.split("^"))[1].split("$")[0])
	state = (((license_data.split("%"))[1].split("^")[0])[:2])
	lnumber = (((license_data.split("^?;"))[1].split("=")[0])[6:])
	full_name = fname,lname
	now = datetime.datetime.now()
	checkin_date = "%s/%s/%s"%(now.month,now.day,now.year)
	visitor_name_text_box.insert(INSERT,full_name)
	lnumber_text_box.insert(INSERT,lnumber)
	state_text_box.insert(INSERT,state)
		
root = Tk()
root.title("Guest Check-In")
root.geometry("450x200")

visitor_name_label = Label(root, text="Name:")
visitor_name_label.pack()

visitor_name_text_box = Entry(root, bd=1)
visitor_name_text_box.pack()

lnumber_label = Label(root, text="License #:")
lnumber_label.pack()

lnumber_text_box = Entry(root, bd=1)
lnumber_text_box.pack()

state_label = Label(root, text="State:")
state_label.pack()

state_text_box = Entry(root, bd=1)
state_text_box.pack()

enter_button = Button(root, text="Enter", command=add_text)
enter_button.pack()

clear_button = Button(root, text="Clear", command=clear)
clear_button.pack()

root.after(1000,data_collector)
root.mainloop()

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 • • Mar 20 '26

Hey check out my YouTube tutorials about the 2025 AoC problems. I show my Python solutions and explain my approach. Also have Typescript and Scala solutions in my repo. Let me know your feedback!

Thumbnail
youtube.com
1 Upvotes

r/learningpython • • Feb 20 '26

update on my little project: now it can accept pulses as input

Thumbnail
gallery
1 Upvotes

First image: showing response of a non linear damper (green) vs the linear version with average damping coefficient(blue) Second image: still pulse but on a just linear system Third image:pulse applied on a 3 DOF system fourth one is an attempt to implement coulomb dynamic friction damping


r/learningpython • • Jan 27 '26

cmu cs academy

1 Upvotes

Hi, I’m learning Python on my own and I really enjoyed CMU CS Academy’s Exploring Programming.
CS1 requires a classroom code. Would you be willing to create a CMU CS Academy classroom and share the code with me?
It’s free for teachers and I’d work independently.


r/learningpython • • Dec 24 '25

Coaching Python Sessions 1 on 1

1 Upvotes

Hi everyone, Mario Duval here.

I noticed that a lot of you are interested to learn more about python and I truly consider offering 1 on 1 sessions that could help you practice understand and become better.

If you are interested feel free to let me know it will give me an indication if it’s a good idea.


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 • • Sep 27 '25

Want to learn Python? Try out EasyDev: Learn to Code!

Post image
1 Upvotes

Link to the App Store page: https://apps.apple.com/app/6749594445

Hello everyone, I wanted to share my new Learn to Code app, EasyDev. Not only does this app have Python courses, it also has courses in C++ and Java (If you are interested in any of those as well). I found a lot of other learn to code apps to be lacking in quality content, so I decided to change that.

The app itself was made exclusively by me, including all the programming, UI, assets, logos, etc. The actual learning content was also handcrafted by using structures similar to popular websites such as Edube and Codecademy, and there is a lot of interactive and descriptive content that takes inspiration from these websites, which are very popular for their effectiveness in teaching people how to code.

If you are interested in learning Java or just want to check the app out, please consider downloading the app using the link above. Also, if you experience any bugs or errors of any kind, please go to the Discord (in the app store page or directly in the app (Settings -> Join the Discord)) and let me know. Thanks in advance!


r/learningpython • • Aug 29 '25

I built a Chrome extension to run Python in the browser sidebar

1 Upvotes

Hey, guys! I built a Chrome extension called Python Playground that allows you to run Python code in the browser sidebar. It is based on Pyodide and has the following key features:

  • No sign up or usage limits.

  • Instant Python code execution without setting up the environment.

  • Syntax highlighting and autocompletion.

  • Upload files to use them in your code.

  • Package manager. You can install PyPI packages in addition to those built into Pyodide.

  • Auto module import. Python Playground will install them based on import statements.

  • Saving scripts in the browser's local storage.

  • Switch between light and dark themes.

  • Built-in data visualization support.

  • Offline capability (for many features), since Pyodide runs on the client side.

I think it's great for people who are learning Python and want an easy way to experiment with code without setting up a full environment.

Try it here: https://chromewebstore.google.com/detail/python-playground/jfippgilnpggpddhmfjaaecadnfhcopa

It also has a web version: https://python-playground.com/online-python-compiler


r/learningpython • • Jul 19 '25

Mimo Max

1 Upvotes

Sounds pretty cool. Guided step by step python scripting on what looks like VSC however its $25/m. Has anyone tried it or heard feedback?


r/learningpython • • Jul 11 '25

How to make an encrypted messaging platform as a newbie

1 Upvotes

Hello everyone, I recently began programming in python. I am a total newbie to python programming and I understand that my knowledge about the language is shallow as I have only learnt about it from Bro Code -"Python Full Course for free 🐍 (2024)'.However I was wondering if I can build anything like a encrypted messaging platform as a project of mine but then I have no idea how to build one. So yeah please tell me what all things do I need to learn more to be able to do so


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?