Code Snippets

 
 
sum_numbers_in_string.png

Sum All Numbers in a string.

n = int(input())
m = str(n)
length = 0
nsum = 0

while n > 0:
   n //= 10
   length += 1 
  
while length > 0:
    i = length - 1
    addme = str(m[i])
    nsum += int(addme)
    length -= 1
   
print(nsum)
 

Three Files Filesize Check and Move

Three files. Randomly check file2 and file 3 for file size and move file1 if filesize is greater than 0. Includes an irrelevant opening and closing of file 1 in notepad as well as a reset of the file locations.

#!/usr/bin/env python3
#import all the modules needed for this.
import os, time, subprocess, random, shutil

#set the files we are working with.
file1 = 'C:\Tempwork\Python\location1\moveme.txt'
file2 = 'C:\Tempwork\Python\oneormore.txt'
file3 = 'C:\Tempwork\Python\zero.txt'
file4 = 'C:\Tempwork\Python\location2\moveme.txt'

#create a list to generate a random file size for use later.
list = [file2, file3]


while 1:
    #open a subprocess as a variable we can call later if needed.
    sp = subprocess.Popen(['notepad.exe', file1])
    time.sleep(2)

    #print all the file sizes, cause why not.
    print("moveme = " + str(os.stat(file1).st_size))
    print("1ormore = " + str(os.stat(file2).st_size))
    print("zero = " + str(os.stat(file3).st_size))

    #Generate a random file size to test against.
    if int(os.stat(random.choice(list)).st_size) > 0:
        shutil.move(file1, file4)

    time.sleep(2)

    #kill the subprocess to end the check.
    os.kill(sp.pid, 10)

    #Check for success and and reset the file locations to go again.
    if os.path.exists(file4):
        shutil.move(file4, file1)
        print ("File Larger than 0, move success.  Resetting the board.")
    else:
        print("File Not larger than 0, trying again.")
    time.sleep(2)

 

Find the longest word and print it.

#take a string of input without punctuation
txt = input()
#split that input into a index of words.
words = txt.split(" ")
#initialize our best by setting it to zero.
best = 0
#for every word in the split list, check it's length against "best". If it's length is larger than "best"
#set best to be equal to that word.
for index in range(len(words)): if len(words[index]) > len(words[best]): best = index print(words[best])