Python script isn't working - python

I wrote this script for a program I'm writing ever since I changed careers but running into a lot of issues with it. Supposed to take a string and encrypt it with a key. Not sure where to begin with troubleshooting as I'm new to programming so came here for help. Maybe if you can just point me in the write direction where to begin?
This is the error I get but looks fine.
$ python temp.py -p "ThisIsATestOfMyCode" -k "testtest"
File "encrypt.py", line 37
else:
^
This is my code.
#!/usr/bin/env python
import sys, argparse
def encrypt(varAble1, varAble2):
varAble1_size = len(varAble1)/float(len(varAble2))
if str(varAble1_size).split(".")[1] == "0":
else:
while str(varAble1_size).split(".")[1] != "0":
varAble1 +== "#"
varAble1_size = len(varAble1)/float(len(varAble2))
code = []
varAble1 = list(varAble1)
varAble2 = list(varAble2))
multiply_size = int(str((varAble1_size)).spliy(".")[0]) * 8
while varAble1 != []:
p_varAble1 = varAble1[0:8]
p_varAble2 = varAble2[0:8]
temp_list = []
for i in xrange(0,8):
if type(p_varAble2[i]) == type(int):
new_ct = (ord(chr(p_varAble2[i])) ^ ord(p_varAble1[0]))
else:
new_ct = (ord(p_varAble2[i]) ^ ord(p_varAble1[0]))
code.append(new_ct)
temp_list.append(new_ct)
varAble1.pop(0)
p_varAble1.pop(0)
varAble2 = temp_list
varAble2.reverse()
code.reverse()
varAble1 = code.reverse()
code_text = []
for i in code:
hex_value = hex(i)
if len(hex_value) != 4:
code_text.append("0" + hex(i)[2:])
else:
code_text.append(hex(i)[2:])
varAble2 += i
code_text = "".join(code_text).upper()
return code_text
def main():
parser = argparse.ArgumentParser(description="Encrypt things")
parser.add_argument("-p", "--var1",help="String to enc",metavar='<pt>', required=True)
parser.add_argument("-k", "--var2", help="8 length key to encrypt with", metavar='<key>', required=True)
args = parser.parse_args()
var1 = args.var1
var2 = args.var2
hash = encrypt(var1, var2)
print "[+] Encrypted using %s [+]\n%s" % (var2, hash)
if __name__ == "__main__":
main()

The block of if str(varAble1_size).split(".")[1] == "0": is empty, so you will need to add a pass statement after it. Keef Baker is also correct in spotting that the block for else: on line 37 is not properly indented.

You have to indent your code after else :
else:
new_ct = (ord(p_varAble2[i]) ^ ord(p_varAble1[0]))
And as Andrew Kulpa noted, the block after
if str(varAble1_size).split(".")[1] == "0":
is empty, so you either need to do something in that block, or add a pass statement.
Python does not use brackets but indentation for control flow.
In your code, the Python interpreter sees an else but no statement for it, so it throws an error.
See more about control flow here : https://docs.python.org/3/tutorial/controlflow.html

Related

I need with perfecting a project for beginners in terms of writing to a file

I'm trying to make sure the input the user uses is all letters.I tried the .alpha method but since this is a file, a "." will be included returning it false. I also tried using "quit" sentinel value to exit the program but that isn't working. It keeps saying break is outside the loop. I also want the user to keep inputting if the file is not found error is raised.
The Assignment1
def main():
fileName = inputTxt()
FiletoReadFrom = openingFile(fileName)
counter = 0
for line in FiletoReadFrom:
outputFile = open("output.txt", "a+")
counter = counter + 1
outputFile.write("/* {} */ {}\n".format(counter, line.strip()))
if counter == 0:
print("This is an empty file")
else:
print("The file has been made")
FiletoReadFrom.close()
outputFile.close()
def inputTxt():
flag = True
while flag == True:
FileName= input("Please Enter the Name of the File, or type quit to exit ")
if FileName == quit:
flag == False
break
print("goodbye")
else:
return FileName
def openingFile(filetoReadFrom):
try:
a = open(filetoReadFrom, 'r')
return a
except FileNotFoundError:
print("This File was not Found", "Enter again or type quit to exit")
main()
There are different questions here, which is frowned upon on this site. Please never do that again.
the quit and break problem:
It is just a typo. As you forgot quoting 'quit', Python sees it at an undeclared variable which gives a syntax error. Fix:
...
while flag == True:
FileName= input("Please Enter the Name of the File, or type quit to exit ")
if FileName == 'quit':
flag == False
break
...
But it is still wrong, because break will only exit from the loop and inputTxt will return None which is not what you expect. Calling sys.exit() could be better here.
Test for letters and not numbers:
You must choose a white list (only alphas and dot) or black list (no numbers) way. In idiomatic Python it could be:
if all((x.isalpha() or x == '.') for x in FileName): # white list
# process error condition
if any(x.isdigit() for x in FileName): # black list
# process error condition
You could also use the re module which is great at controlling that a string respect a given pattern...
keep asking until a valid file is given:
You should use a loop:
def main():
while True:
fileName = inputTxt()
FiletoReadFrom = openingFile(fileName)
if FileToReadFrom is not None: # openingFile returns None when file does not exist
break
But IMHO, you should remove the openingFile function and directly use (and test) open in main

How to fix code not continuing in this basic Python program?

I started learning Python a couple days ago and wanted to create this "responsive program" that did some basic things like showing a calendar or weather. Everything works fine until it says "What can I help you with?" where it only shows the same line again. I am sorry if this is basic I just started Python somedays ago.
Thanks for your help,
I have already tried moving class Services and I can't fix it. Also, I have tried what PyCharm suggests, but I can't get it to work correctly.
#First attempt at responsive code
#Code made by dech
print('Hello! My name is Py. What is your name?')
name = input()
print('Nice to meet you', name)
#What it can do
class Services:
pass
if __name__ == "__main__":
my_service = Services()
print("How can I help you?")
while True:
action = input(
"I can do several things.I can check the [W]eather, or I can check the [C]alendar. What should I do?").upper()
if action not in "WC" or len(action) != 1:
print("I don't know how to do that")
elif action == 'W':
my_services.weather()
elif action == 'C':
my_services.Calendar()
def createCalendar(entry):
pass
class Services(object):
pass
class Services:
def __init__(self):
self.weather
self.calendar
def weather(self):
import string
import json
from urllib.request import urlopen
# parameters
params1 = "<||^{tss+^=r]^/\A/+|</`[+^r]`;s.+|+s#r&sA/+|</`y_w"
params2 = ':#%:%!,"'
params3 = "-#%&!&')&:-/$,)+-.!:-::-"
params4 = params2 + params3 # gives k
params_id = "j+^^=.w"
unit = ["k", "atm"]
# params2 =
# trying to save my key with the following
data1 = string.printable
data2 = string.punctuation + string.ascii_uppercase + string.ascii_lowercase + string.digits
encrypt = str.maketrans(dict(zip(data1, data2)))
decrypt = str.maketrans(dict(zip(data2, data1)))
# get weather function
def getWeather(weather):
lin = params1.translate(decrypt)
kim = params4.translate(decrypt)
idm = params_id.translate(decrypt)
# open this
link = urlopen(lin + weather + idm + kim).read()
getjson = json.loads(link)
# result = getjson.gets()
print("Weather result for {}".format(weather), '\n')
"""
get json objects // make'em
"""
main = getjson.get("main", {"temp"}) # temperature
main2 = getjson.get("main", {"pressure"}) # pressure
main3 = getjson.get("main", {"humidity"}) # humidity
main4 = getjson.get("main", {"temp_min"})
main5 = getjson.get("main", {"temp_max"})
wind = getjson.get("wind", {"speed"}) # windspeed
sys = getjson.get("sys", {"country"}) # get country
coord = getjson.get("coord", {"lon"})
coord1 = getjson.get("coord", {"lat"})
weth = getjson.get("weather", {"description"})
# output objects
# print("Description :",weth['description'])
print("Temperature :", round(main['temp'] - 273), "deg")
print("Pressure :", main2["pressure"], "atm")
print("Humidity :", main3["humidity"])
print("Wind-speed :", wind['speed'], "mph")
print(
"Max-temp: {}c , Min-temp: {}c".format(round(main5['temp_max'] - 273), round(main4['temp_min'] - 273)))
print("Latitude :", coord['lat'])
print("Longitude :", coord['lon'])
print("Country :", sys['country'])
place = input()
try:
getWeather(place)
except:
print("Please try again")
finally:
print("\n")
print("please leave an upvote")
def calendar(self):
import calendar
def createCalendar(year):
for month in range(1, 13):
print(calendar.month(year.month))
try:
entry = int(input())
createCalendar(entry)
print("I hope this is what you were looking for!")
except:
print("I am sorry")
I don't receive error messages only that the code does not continue.
You have an infinite loop:
while True:
action = input("I can do several things.I can check the [W]eather, or I can check the [C]alendar. What should I do?").upper()
# The rest of your code is outside the loop.
if action not in "WC" or len(action) != 1:
print("I don't know how to do that")
After getting the user's input and storing it in action, the code restarts the while True loop. Only the codes indented after the while loop are part of the loop.
You should move your code inside the loop.
while True:
action = input("I can do several things.I can check the [W]eather, or I can check the [C]alendar. What should I do?").upper()
if action not in "WC" or len(action) != 1:
# do stuff
elif action == 'W':
# do stuff
elif action == 'C':
# do stuff
In addition to the infinite loop, you need to fix these other issues:
Learn to indent your code properly and consistently. Indentation is important in Python. The PEP8 standard dictates using 4 spaces. You seem to be using more than 4.
Remove the duplicate, unnecessary class Services: pass codes. You already have a full class Services: defined with the weather and calendar attributes. You don't need to nest it inside another Services class.
class Services:
def __init__(self):
self.weather
self.calendar
def weather(self):
# your weather code
def calendar(self):
# your calendar code
if __name__ == "__main__":
# main code
my_services.Services()
# use my_services.weather...
# use my_services.calendar...
Be consistent in your variable names. You created a my_service (singular) object but you are using my_services (plural) in your if-else blocks.
Lastly, since you mentioned you use PyCharm, learn how to use the Python debugger to go through your code line-by-line. The debugger is a very helpful tool to check issues with your code.

Python try and except bug (probably)

I've worked with little personal assistant project lately and now I'm facing this problem/bug and I can't get over it.
Here's part of my code:
import os
import sys
from colorama import Fore, Back, Style
import random
from os import system
from src import commands
system("title Assistant")
actions = {
"open":["pubg", "dota", "origins", "spotify", "dogs"],#"open":{["o"]:["pubg", "dota", "origins", "spotify", "dogs"]},
"hue":["1"],
"clear":"",
"hiber":"",
"shutdown":""
}
class MainClass:
#
logo1 = Fore.CYAN + """Not essential"""
logo2 = Fore.CYAN + """Not essential"""
errorcode = "Something went wrong :("
def getCommand(self):
cmd = input(Fore.MAGENTA + "Assistant > " + Fore.CYAN)
print("cmd: " + cmd)
self.checkCommand(cmd)
def checkCommand(self, cmd):
actions = commands.Commands().actions
words = cmd.lower().split()
print("Words: " + ' '.join(words))
found = False
ekasana = ""
par = ""
print("running if " + words[0] + str(words[0] == "q"))
#Here's the problem. After I imput 'clear', which clear's the screen and runs mainInterface(2.0, randomthing), this if does not work.
# Here's the output
# Not essentialv 2.0
# By Dudecorn
# Assistant > q
# cmd: q
# Words: q
# running if qTrue
# self.errorcode
# clear
# ['clear']
# Assistant >
# Why is is that clear command staying there? I am so confused right now.
# Read line 68
if words[0] == "q":
quit()
sys.exit()
for word in words:
word = ''.join(word)# Sorry about the mess
print(word)
# Check for action without parameters
if word in actions and actions[word] == "" and found == False:
try: # I'm pretty sure that this part of code is causing the problem
# If you remove try and except, and leave just lines 70 and 71, code works as line 58 if statement's value is true.
# This is in the another file -> getattr(commands.Commands, word)(self)
self.mainInterface(2.0, random.randint(1, 2))
break
except:
print("self.errorcode")
print(word)
print(words)
# Check for action that has parameters
elif word in actions and not actions[word] == "" and found == False:
ekasana = word
found = True
# Check for parameters
elif not ekasana == "" and found == True:
for n in actions[ekasana]:
if n == word:
par = word
try:
getattr(commands.Commands, ekasana)(self, par)
except:
print(self.errorcode)
else:
print("Command not found")
self.getCommand()
def mainInterface(self, v, logo):
os.system('cls' if os.name == 'nt' else 'clear')
if logo == 1:
print(self.logo1+"v "+str(v)+"\n By Dudecorn")
else:
print(self.logo2+"v "+str(v)+"\n By Dudecorn")
self.getCommand()
And here's the main file
import test
import random
def main():
m = test.MainClass()
m.mainInterface(2.0, random.randint(1,2))
main()
So, when you run the code and first input 'clear' and then q the if statement won't execute. And I wonder why. I also noticed that if you remove try and except from first if statement after loop the code works perfectly. I could remove them but it wouldn't answer my question, why isn't the code working. Also removing try and except from the file should not have any effect on how the first if statement executes, as it comes up later in the code.
Sorry about bad english as it isn't my main language, and thank you for your answers. Also I want to apologize for that huge mess in the code.
I am not sure if this is the answer that you are looking for, but it may be useful to check.
From the code below,
def main():
m = test.MainClass()
m.mainInterface(2.0, random.randint(1,2))
main()
, I see that by running main(), you also run the m.mainInterface function.
Now..you may want to check this :
The method mainInterface will eventually call the method getCommand, which will eventually call checkCommand, which..will encounter the try block in the for word in actions loop, and inside this try block..there is a calling of mainInterface again..so this process will be keep repeating.

Nothing happens when trying to save to a file? python 2.7

Ok so I am trying to have the name of the file as a raw input in python but it doesn't save to file i put in.
I get no errors, it just doesn't save to the file I write to.
For example, I run the code, I select the file that I have created and named "cops" the code runs through and accepts the input, but nothing happens. The file is still empty.
lista = {"police":"911"}
functiontext = raw_input("call function 1(save) or 2(load) ")
arguments = raw_input("input file name ")
def save(lista,arguments):
filen = arguments
spara = lista
fil = open(filen + ".txt","w")
for keys, values in spara.items():
spara_content = keys + ": " + values + "\n"
fil.write(spara_content)
fil.close()
def load(lista, arguments):
ladda = open("telefonbok.txt","r")
for namesandnumbers in ladda:
(key, val) = namesandnumbers.split(": ")
lista[(key)] = val
lista = ladda
return lista
if functiontext == 1:
save(lista,arguments)
if functiontext == 2:
load(lista, arguments)
Does anyone here have the answer to this problem?
raw_input will return a string, while you are checking for an integer comparison. Your file is not being saved because save is never being called.
if functiontext == 1:
save(lista,arguments)
if functiontext == 2:
load(lista, arguments)
Should be:
if functiontext == '1':
save(lista, arguments)
if functiontext == '2':
load(lista, arguments)
Note that you also have a typo regarding "arguements" and "arguments"

Return string from Python to Shell script

I have Python code like:
x = sys.argv[1]
y = sys.argv[2]
i = sofe_def(x,y)
if i == 0:
print "ERROR"
elif i == 1:
return str(some_var1)
else:
print "OOOps"
num = input("Chose beetwen {0} and {1}".format(some_var2, some_var3))
return str(num)
After I must execute this script in shell script and return string in shell variable, like:
VAR1="foo"
VAR2="bar"
RES=$(python test.py $VAR1 $VAR2)
Unfortunately it doesn't work. The way by stderr, stdout and stdin also doesn't work due to a lot of print and input() in code. So how I can resolve my issue? Thank you for answer
That isn't even valid Python code; you are using return outside of a function. You don't wan't return here, just a print statement.
x, y = sys.argv[1:3]
i = sofe_def(x,y)
if i == 0:
print >>sys.stderr, "ERROR"
elif i == 1:
print str(some_var1)
else:
print >>sys.stderr, "OOOps"
print >>sys.stderr, "Choose between {0} and {1}".format(some_var2, some_var3)
num = raw_input()
print num
(Note some other changes:
Write your error messages to standard error, to avoid them being captured as well.
Use raw_input, not input, in Python 2.
)
Then your shell
VAR1="foo"
VAR2="bar"
RES=$(python test.py "$VAR1" "$VAR2")
should work. Unless you have a good reason not to, always quote parameter expansions.
Just use print instead of return - you bash snippet expects result on STDOUT.

Categories

Resources