Im new to programming and I wrote a program to solve different variables in an equation. I have "if" "elif" and "else" set up to solve for different parts of the equation. For some reason though, it will only solve for the first part (the "if" part) I'll copy and paste the program below.
import math
print 'A=Pert Calculator'
print ''
print 'Created by Triton Seibert'
print ''
Y = raw_input('What letter would you like to solve for?: ')
if Y == 'A' or 'a' or '1':
print 'Solving for A'
print ''
P = float(raw_input('Set value for P (initial investment):'))
e = 2.71828
print ''
r = float(raw_input('Set value for r (rate):'))
print ''
t = float(raw_input('Set value for t (time in years):'))
print ''
ert = e**(r*t)
answer = P*ert
print 'A equals:'
print answer
elif Y == 'P' or 'p' or '2':
print 'Solving for P'
print ''
A = float(raw_input('Set value for A (Final answer):'))
e = 2.71828
print ''
r = float(raw_input('Set value for r (rate):'))
print ''
t = float(raw_input('Set value for t (time in years):'))
print ''
answer = A / math.e**(r*t)
print 'P equals:'
print answer
elif Y == 'R' or 'r' or '3':
print 'Solving for r'
print ' '
A = float(raw_input('Set value for A (Final answer): '))
P = float(raw_input('Set value for P (initial investment):'))
e = 2.71828
print ' '
t = float(raw_input('Set value for t (time in years):'))
print ' '
almost = A/P
getting_there = math.log10(almost)/math.log10(e)
answer = getting_there/t
print 'r equals:'
print answer
elif Y == 'T' or 't' or '4':
print 'Solving for t'
print ' '
A = float(raw_input('Set value for A (Final answer): '))
P = float(raw_input('Set value for P (initial investment):'))
e = 2.71828
print ' '
r = float(raw_input('Set value for r (rate):'))
print ' '
#equation here (not done yet)
print 't equals:'
print answer
else:
print 'Not yet'
#change log to ln : log base e (x) = log base 10 (x) / log base 10 (e)
This part always evaluates to True:
if Y == 'A' or 'a' or '1':
It's not doing what you think it's doing; it's doing this:
if (Y == 'A') or ('a') or ('1'):
and 'a' evaluates to True, so it passes. What you probably want is:
if Y in ['A', 'a', '1']:
Related
This is a password generator, I couldn't really determine where the problem is, but from the output, I could say it's around turnFromAlphabet()
The function turnFromAlphabet() converts an alphabetical character to its integer value.
The random module, I think doesn't do anything here as it just decides whether to convert a character in a string to uppercase or lowercase. And if a string is in either, when sent or passed to turnFromAlphabet() it is converted to lowercase first to avoid errors but there are still errors.
CODE:
import random
import re
#variables
username = "oogisjab" #i defined it already for question purposes
index = 0
upperOrLower = []
finalRes = []
index2a = 0
#make decisions
for x in range(len(username)):
decision = random.randint(0,1)
if(decision is 0):
upperOrLower.append(True)
else:
upperOrLower.append(False)
#Apply decisions
for i in range(len(username)):
if(upperOrLower[index]):
finalRes.append(username[index].lower())
else:
finalRes.append(username[index].upper())
index+=1
s = ""
#lowkey final
s = s.join(finalRes)
#reset index to 0
index = 0
def enc(that):
if(that is "a"):
return "#"
elif(that is "A"):
return "4"
elif(that is "O"):
return "0" #zero
elif(that is " "):
# reduce oof hackedt
decision2 = random.randint(0,1)
if(decision2 is 0):
return "!"
else:
return "_"
elif(that is "E"):
return "3"
else:
return that
secondVal = []
for y in range(len(s)):
secondVal.append(enc(s[index]))
index += 1
def turnFromAlphabet(that, index2a):
alp = "abcdefghijklmnopqrstuvwxyz"
alp2 = list(alp)
for x in alp2:
if(str(that.lower()) == str(x)):
return index2a+1
break
else:
index2a += 1
else:
return "Error: Input is not in the alphabet"
#real final
finalOutput = "".join(secondVal)
#calculate some numbers and chars from a substring
amount = len(finalOutput) - round(len(finalOutput)/3)
getSubstr = finalOutput[-(amount):]
index = 0
allFactors = {
};
#loop from substring
for x in range(len(getSubstr)):
hrhe = re.sub(r'\d', 'a', ''.join(e for e in getSubstr[index] if e.isalnum())).replace(" ", "a").lower()
print(hrhe)
#print(str(turnFromAlphabet("a", 0)) + "demo")
alpInt = turnFromAlphabet(hrhe, 0)
print(alpInt)
#get factors
oneDimensionFactors = []
for p in range(2,alpInt):
# if mod 0
if(alpInt % p) is 0:
oneDimensionFactors.append(p)
else:
oneDimensionFactors.append(1)
indexP = 0
for z in oneDimensionFactors:
allFactors.setdefault("index{0}".format(index), {})["keyNumber"+str(p)] = z
index+=1
print(allFactors)
I think that you are getting the message "Error: input is not in the alphabet" because your enc() change some of your characters. But the characters they becomes (for example '#', '4' or '!') are not in your alp variable defined in turnFromAlphabet(). I don't know how you want to fix that. It's up to you.
But I have to say to your code is difficult to understand which may explain why it can be difficult for you to debug or why others may be reluctant to help you. I tried to make sense of your code by removing code that don't have any impact. But even in the end I'm not sure I understood what you tried to do. Here's what I understood of your code:
import random
import re
#username = "oogi esjabjbb"
username = "oogisjab" #i defined it already for question purposes
def transform_case(character):
character_cases = ('upper', 'lower')
character_to_return = character.upper() if random.choice(character_cases) == 'upper' else character.lower()
return character_to_return
username_character_cases_modified = "".join(transform_case(current_character) for current_character in username)
def encode(character_to_encode):
translation_table = {
'a' : '#',
'A' : '4',
'O' : '0',
'E' : '3',
}
character_translated = translation_table.get(character_to_encode, None)
if character_translated is None:
character_translated = character_to_encode
if character_translated == ' ':
character_translated = '!' if random.choice((True, False)) else '_'
return character_translated
final_output = "".join(encode(current_character) for current_character in username_character_cases_modified)
amount = round(len(final_output) / 3)
part_of_final_output = final_output[amount:]
all_factors = {}
for (index, current_character) in enumerate(part_of_final_output):
hrhe = current_character
if not hrhe.isalnum():
continue
hrhe = re.sub(r'\d', 'a', hrhe)
hrhe = hrhe.lower()
print(hrhe)
def find_in_alphabet(character, offset):
alphabet = "abcdefghijklmnopqrstuvwxyz"
place_found = alphabet.find(character)
if place_found == -1 or not character:
raise ValueError("Input is not in the alphabet")
else:
place_to_return = place_found + offset + 1
return place_to_return
place_in_alphabet = find_in_alphabet(hrhe, 0)
print(place_in_alphabet)
def provide_factors(factors_of):
for x in range(1, int(place_in_alphabet ** 0.5) + 1):
(quotient, remainder) = divmod(factors_of, x)
if remainder == 0:
for current_quotient in (quotient, x):
yield current_quotient
unique_factors = set(provide_factors(place_in_alphabet))
factors = sorted(unique_factors)
all_factors.setdefault(f'index{index}', dict())[f'keyNumber{place_in_alphabet}'] = factors
print(all_factors)
Is near what your wanted to do?
Why doesn't this work? I input windows/meterpreter/reverse_tcp and it returns the error...again
def shellcode():
os.system("clear")
print style
print green + " [+]Your Choose 4 | C Type Format - ShellCode Generate"
print style
print payload_types
print ' '
payload_choose = raw_input(time + white + "Choose Payload > ")
while (payload_choose != "windows/meterpreter/reverse_tcp" or "linux/x86/meterpreter/reverse_tcp"):
print "[-]error"
payload_choose = raw_input(time + white + "Choose Payload > ")
print "ok"
This line:
while (payload_choose != "windows/meterpreter/reverse_tcp" or "linux/x86/meterpreter/reverse_tcp"):
probably doesn't do what you want. I think you probably meant this?
while payload_choose != "windows/meterpreter/reverse_tcp" and payload_choose != "linux/x86/meterpreter/reverse_tcp":
Further explanation
This expression:
a or b
means "a is true or b is true".
This expression:
foo != 'hello' or 'goodbye'
means "(foo != 'hello') is true or 'goodbye' is true". In Python, a non-empty string is considered "truthy", so your original while loop condition is always true.
# Kinematics clculator
print('Kinematics Calculator')
print('If either one of the three values(s,v,t) is not given then put its value = 1')
s = float(input('Enter your distance = '))
print(s)
t = float(input('Enter your time = '))
print(t)
v = float(input('Enter your velocity = '))
print(v)
if 'v == 1' :
print('velocity = '+ str(s/t))
elif 't == 1' :
print('time = '+ str(s/v))
else :
's == 1'
print('distance = '+ str(v*t))
Help me correct this code. Whenever I try to calculate anything else than "velocity" it always uses the first print command i.e
print('velocity = '+ str(s/t))
'v == 1' always evaluates to true, because it's a non-empty string. You should use
if v == 1:
print('velocity = '+ str(s/t))
elif t == 1:
print('time = '+ str(s/v))
else:
print('distance = '+ str(v*t))
I would like to use a function in my code that would justify the string. I'm stuck please look at my code.
Thanks in advance.
def justify(s, pos): #(<string>, <[l]/[c]/[r]>)
if len(s)<=70:
if pos == l:
print 30*' ' + s
elif pos == c:
print ((70 - len(s))/2)*' ' + s
elif pos == r:
print (40 - len(s)*' ' + s
else:
print('You entered invalid argument-(use either r, c or l)')
else:
print("The entered string is more than 70 character long. Couldn't be justified.")
you missed a bracket at second elif. corrected code below -
def justify(s, pos):
if len(s)<=70:
if pos == l:
print 30*' ' + s
elif pos == c:
print ((70 - len(s))/2)*' ' + s
elif pos == r:
#you missed it here...
print (40 - len(s))*' ' + s
else:
print('You entered invalid argument-(use either r, c or l)')
else:
print("The entered string is more than 70 character long. Couldn't be justified.")
def justify2(s, pos):
di = {"l" : "%-70s", "r" : "%70s"}
if pos in ("l","r"):
print ":" + di[pos] % s + ":"
elif pos == "c":
split = len(s) / 2
s1, s2 = s[:split], s[split:]
print ":" + "%35s" % s1 + "%-35s" % s2 + ":"
else:
"bad position:%s:" % (pos)
justify2("abc", "l")
justify2("def", "r")
justify2("xyz", "c")
:abc :
: def:
: xyz :
I am a beginner python learner. I created this simple program but won't display any error message neither does it work. After the input it stops working. What am I doing wrong? [ Python 3.2]
import math
print('''
|.
| .
a| . c
| .
|________.
b
''')
def robot():
a = float(input('Enter side a, 0 for unknown \n: '))
b = float(input('Enter side b, 0 for unknown \n: '))
c = float(input('Enter hypotenuse c, 0 for unknown \n: '))
if a == 0:
print = ('a = ', (math.sqrt((c**2)-(b**2))))
if b == 0:
print = ('b = ', (math.sqrt((c**2)-(a**2))))
if c == 0:
print = ('a = ', (math.sqrt((a**2)+(b**2))))
input()
robot()
robot()
Thanks
print = ('b = ', (math.sqrt((c**2)-(a**2))))
^
Delete the assignment operator after the print. print is a function, so to call it you only have to provide the arguments in the parenthesis, like this:
print('b = ', (math.sqrt((c**2)-(a**2))))