Python - while input doesn't work - python

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.

Related

if, elif & !=, == boolean operations only return "false" with inputs

I am creating an Among Us ripoff (for fun!) and the while True & if/elif/else statements will only return false (not An Impostor) with the inputs. I had created a list for the names and 2 random elements from the list will be chosen as An Impostor. However, whenever I input a name that is The Impostor, it will only return
(player) was not An Impostor.
Here is my code;
import sys, time, random
names = ["player1", "player2", "player3", "player4", "player5", "player6", "player7", "player8", "player9", "player10"]
print("Players: ")
for x in names:
print(x)
print('—————————————————————————')
impostor1 = random.choice(names)
impostor2 = random.choice(names)
crewmates = 8
impostors = 2
tries = 6
while True:
talk = input("Guess who The Impostor(s) are. " + str(crewmates) + " Crewmates are left. " + str(impostors) + " Impostors are left. You have " + str(tries) + " tries left.")
if talk in names:
print(talk + " was voted for.")
time.sleep(0.1)
if talk != impostor1 or talk != impostor2:
notimp = talk + " was not An Impostor. "
names.remove(talk)
for y in notimp:
sys.stdout.write(y)
sys.stdout.flush()
time.sleep(0.05)
crewmates -= 1
tries -= 1
elif talk == impostor1 or talk == impostor2:
wasimp = talk + " was An Impostor. "
names.remove(talk)
for v in wasimp:
sys.stdout.write(v)
sys.stdout.flush()
time.sleep(0.1)
impostors -= 1
else:
print("That player was either ejected or is not a valid player.")
However, whenever I put the Impostor in the input, it says it isn't An Impostor?
I think this line is the source of the problem:
if talk != impostor1 or talk != impostor2:
Let's say impostor1 is player1 and impostor2 is player2 and someone input in player1, according to Python Boolean expression operator or that if statement will evaluate like this:
if player1 != impostor1 evaluated to False because player1 is indeed equals to impostor1.
So far so good, but because the first test is a False, Python simply evaluates and returns the right side operand which may be either True or False. In your case Python will evaluate if talk != impostor2 and return True, thereafter executes the nested block.

i there a way to rewrite the code?,i can not seem to get it right, i can not seem to get the input correctly

I have to edit the code i previously wrote to make it work with a input, I will attach the problem. I can not seem to get it to work.
it has to be some sort of input,
string =" "
reversed_string = string[::-1]
result_string = " ".join(string)
for a in range (0 ,3):
result_string += chr(ord('a')+a)
for a in range(0 , 2)[::-1]:
result_string += chr(ord('a')+a)
print result_string
string =" "
add this to input from keyboard
input( 'type a letter from a to z')
This is the shortest I could make the answer
character = 97
char_list = []
con = True
a = 0
for interger in range(26):
char = chr(character)
char_list.append(char)
character = character+1
get_char = input("Enter a letter from a-z")
while con == True:
if get_char == char_list[a]:
b = char_list[:a+1]
char_list.reverse()
print(b+char_list[-a:])
con = False
else:
a = a+1

Can't convert 'int' object to str implicitly. Python Error

This is my code trying to convert a sentence to camel case whenever a '-' or '_' appears.
def to_camel_case(text):
for i in text:
if text[0].isupper():
text[0] = text[0].upper()
elif i == '_' or i == '-':
text[i] = text[i].upper()
return text
On executing the code it says the mentioned error. I know the error is somewhere in the line text[i] = text[i].upper() but I can't figure it out. Thanks.
IIUC you can use string.title having replaced both - or _ to spaces with re.sub:
import re
s = "hello_world"
re.sub('_|-',' ',s).title()
# 'Hello World'
A Non-Regex / Crude-Logic(:D) version:
def to_camel_case(text):
pos_list = [x+1 for x,c in enumerate(text) if ((c == '_' or c == '-') and (x!=len(text)))]
new_text_list = []
for i, c in enumerate(text):
if (c == '-' or c == '_'):
continue
if i in pos_list:
new_text_list.append(c.upper())
else:
new_text_list.append(c)
return "".join(x for x in new_text_list)
print to_camel_case("hey_there")
print to_camel_case("-In_this_World_")
print to_camel_case("hello_world")
Output:
heyThere
InThisWorld
helloWorld

implement my own strip method in Python

I am trying to implement my own strip method in Python, so without using the built-in method, I'd like my function to strip out all the whitespace from the left and the right.
Here, what I am trying to do is create a list, remove all the blank character before the first non-space character, then do it reverse way, finally return the list to a string. But with what I wrote, it doesn't even remove one whitespace.
I know what I am trying to do might not even work, so I would also like to see the best way to do this. I am really new to programming, so I would take any piece of advise that makes my program better. Thanks!
# main function
inputString = input("Enter here: ")
print(my_strip(inputString))
def my_strip(inputString):
newString = []
for ch in inputString:
newString.append(ch)
print(newString)
i = 0
while i < len(newString):
if i == " ":
del newString[i]
elif i != " ":
return newString
i += 1
print(newString)
Instead of doing a bunch of string operations, let's just get the beginning and ending indices of the non-whitespace portion and return a string slice.
def strip_2(s):
start = 0
end = -1
while s[start].isspace():
start += 1
while s[end].isspace():
end -= 1
end += 1
return s[start:end or None]
How about using regular expression?
import re
def my_strip(s):
return re.sub(r'\s+$', '', re.sub(r'^\s+', '', s))
>>> my_strip(' a c d ')
'a c d'
What you seem to be doing is an ltrim for spaces, since you return from the function when you get a non-space character.
Some changes are needed:
# main function
inputString = input("Enter here: ")
print(my_strip(inputString))
def my_strip(inputString):
newString = []
for ch in inputString:
newString.append(ch)
print(newString)
i = 0
while i < len(newString):
if i == " ": # <== this should be newString[i] == " "
del newString[i]
elif i != " ": # <== this should be newString[i] == " "
return newString
i += 1 # <== this is not needed as the char is deleted, so the next char has the same index
print(newString)
So the updated code will be:
# main function
inputString = input("Enter here: ")
print(my_strip(inputString))
def my_strip(inputString):
newString = []
for ch in inputString:
newString.append(ch)
print(newString)
i = 0
while i < len(newString):
if newString[i] == " ":
del newString[i]
elif newString[i] != " ":
return newString
print(newString)
Good luck with the rest of the exercise (implementation of rtrim).

Python: If condition appears to be met but isn't triggering

I know this seems like it should be very simple, but at this point I'm at my wit's end trying to figure this out. I've coded up a calculator in python, but for some reason the ending if-else statement is only firing the else segment.
import sys
import re
#setting values
x = 0
n = '+'
y = 0
#valid input flag
valid = True
#continue operations flag
run = True
again = "k"
#addition function
def add(x, y):
return x + y
#subtraction function
def subtract(x, y):
return x - y
#multiplication function
def multiply(x, y):
return x * y
#division function
def divide(x, y):
return x / y
#continuation loop
while run == True:
#Prompt for and accept input
equation = raw_input("Please insert a function in the form of 'operand' 'operator' 'operand' (x + y): ")
equation.strip()
#Divide input into 3 parts by spaces
pieces = re.split('\s+', equation)
#set part 1 = x as float
x = pieces[0]
try:
x = float(x)
except:
print "x must be a number"
valid = False
#set part 2 = operator
if valid == True:
try:
n = pieces[1]
except:
print "Please use valid formating (x [] y)."
valid = False
#set part 3 = y as float
if valid == True:
y = pieces[2]
try:
y = float(y)
except:
print "y must be a number"
valid = False
#If input is valid, do requested calculations
while valid == True:
if n == '+' :
print equation + " =", add(x,y)
elif n == '-' :
print equation, " =", subtract(x,y)
elif n == '*' :
print equation, "*", y, " =", multiply(x,y)
elif n == '/' :
if y == 0:
print "You cannot divide by zero."
else:
print equation, " =", divide(x,y)
else:
print "Please use an appropriate operator ( + - * / )."
#play again
again = raw_input("Play again? ")
print again
if again == ("yes", "y", "YES", "Yes","yes"):
run = True
print "yes'd"
else:
print "no'd"
run = False
When I run this code, I get two different problems:
If I enter a valid input (ie: 2 + 2), then my output is
"2 + 2 = 4.0"
"2 + 2 = 4.0"
"2 + 2 = 4.0"
repeating forever.
If I enter an invalid input, I get the "Play again? " Prompt, but
no matter what I enter, the else statement fires.
(for instance, in the case that I enter "yes" into "Play again? ", it will print:
"yes" (<-- this is from "print again" line )
"no'd" (<-- this is from "else: print "no'd" )
I dont know how to solve either of these problems at this point, so any help would be greatly appreciated.
Edit: Thank you everyone, I wish I could check mark all of you for helping me understand different things about what I did wrong.
In while valid == True:, you never change the value of valid, so it's always True and the loop is infinite. I don't see why it's even a loop - change it to if like the blocks above it and it will behave as expected.
Also, in if again == ("yes", "y", "YES", "Yes","yes"):, change == to in and it will behave as expected.
Perhaps you should replace this code:
while valid == True:
if n == '+' :
print equation + " =", add(x,y)
elif n == '-' :
print equation, " =", subtract(x,y)
elif n == '*' :
print equation, "*", y, " =", multiply(x,y)
elif n == '/' :
if y == 0:
print "You cannot divide by zero."
else:
print equation, " =", divide(x,y)
else:
print "Please use an appropriate operator ( + - * / )."
With this...
if valid:
Or...
while valid == True:
# Insert your previous code here.
break
You could also just simply set valid to false at the bottom of your loop too. That would work.
I think valid is constantly true in this case. You have also written while valid is true, which means it will keep iterating over the loop until valid is equalled to false. It appears that within this block of code in the while loop, valid isn't switched to false.
while valid == True: should probably be if valid == True
and for your second problem:
if again == ("yes", "y", "YES", "Yes","yes"): should probably be:
again = again.lower();
if again == "yes" or again == "y":
Your answer is looping because of
while valid == True:
Replace the loop with the if statement
You get "no'd" because of
if again == ("yes", "y", "YES", "Yes", "yes"):
Here you are equating string with a tuple, instead of checking whether the string is contained within a tuple. Try this instead:
if again in ("yes", "y", "YES", "Yes""):

Categories

Resources