Reversing a string is not matching with the expected output in Python - python-3.x

I have written a python program to reverse the string.
For Example input string is "I am Human" the output will be "namuH ma I"
I have again passed the output to the same function as an input so that the output will be the same string which we have given as input earlier.
Then I am trying to match the given input string to the output but it is not working could you please help.
Program:
def reverse(string):
input_words=string.split(" ")
temp=input_words[::-1]
final=[]
for i in temp:
x=i[::-1]
x=x.strip()
final.append(x)
output=" ".join(final)
return(output)
if __name__ == "__main__":
string="I am Human"
print(reverse(string))
output1=reverse(string)
output2=reverse(output1)
print(string)
print(output2)
output2=output2.strip()
if(output1 == output2):
print("Its maching")
else:
print("\n \n there is some issue please check")
Output:
namuH ma I
I am Human
I am Human
there is some issue please check

You are comparing output1 which "namuH ma I" with output2 which I am Human
So it is not obvious will not match.
One more to notice,you using output2.strip() which will eliminate "whitespace character" on it
Read more at: https://www.tutorialspoint.com/python/string_strip.htm

The output2 variable always have reverse value as output1. So obvious it will not match.
Also there is no use of output2=output2.strip() this line
You might wan't to do like this:
if(string == output2):
print("Its maching")
else:
print("\n \n there is some issue please check")

Related

Code not checking if inputted answer is correct

I am trying to create a multiple choice quiz that takes questions from an external .txt file and prints it in python. The text file is laid out like this:
1,Who was the first man to walk on the moon?,A.Michael Jackson,B.Buzz Lightyear,C.Neil Armstrong,D.Nobody,C
When I run the code and input the right answer it still says incorrect but continues to say the answer I inputted.
In the code I split each line in the text file by a ',' so the correct answer in the text file is always detail[6]. In the code I have put:
if answer.upper() == detail[6]:
print("Well done, that's correct!")
score=score + 1
print(score)
elif answer.upper() != detail[6]:
print("Incorrect, the correct answer is ",detail[6])
print(score)
I thought this would work as it is checking the inputted answer against detail[6] but it always comes out as incorrect.
import random
score=0
with open('space_quiz_test.txt') as f:
quiz = f.readlines()
questions = random.sample(quiz, 10)
for question in questions:
detail = question.split(",")
print(detail[0],detail[1],detail[2],detail[3],detail[4],detail[5])
print(" ")
answer=input("Answer: ")
while True:
if answer.upper() not in ('A','B','C','D'):
print("Answer not valid, try again")
else:
break
if answer.upper() == detail[6]:
print("Well done, that's correct!")
score=score + 1
print(score)
elif answer.upper() != detail[6]:
print("Incorrect, the correct answer is ",detail[6])
print(score)
I would like the code to be able to check if the inputted answer is correct by checking it against detail[6] within the text file, instead of always coming out as incorrect, the correct answer is detail[6].
The problem is that readlines() retains the newline character at the end of each line.
Your detail[6] is something like 'C\n' rather than 'C' itself. To fix that, use
detail = question.strip().split(",")

checking a word in the text and print() a command once

Using these commands I get the three sentences.
AnyText = driver.find_elements_by_xpath('AnyXpath')
for AnyText1 in AnyText:
print(AnyText1.text)
In the console, I get something like that:
**
1) Hello my name is John
**
2) Hello my name is Mark
**
3) Hello my name is Alex..
How can I check that all three sentences have the word "name"
and print("OK") if the word is in the sentence (element) and print("ERROR") if not.
Im try:
AnyText = driver.find_elements_by_xpath('AnyXpath')
Text = 'name'
if all(Text in AnyText1 for two in AnyText1):
print('OK')
else:
print('ERROR')
but this method only checks the first element (first sentence). I also tried something like this
AnyText = driver.find_elements_by_xpath('AnyXpath')
Text = 'name'
for AnyText1 in AnyText:
if all(Text in AnyText1):
print('OK')
else:
print('ERROR')
but I get many times OK or ERROR
UPD:
With a question on the text, I figured out with your help. Now I want to understand the numbers)
I have a loop that checks the next number more or less. If more, writes ERROR, if less, writes OK
sort_month=driver.find_element_by_xpath('/html/body/div[6]/div[2]/div/div[1]/div/div[13]/table/thead/tr/th[3]/a[4]').click()
month2=driver.find_element_by_xpath('//*[starts-with(#id, "td_")]/td[3]/span[3]')
month2=month2.text.replace("'", "").replace(" ", "")
buffer = 0
if int(month2) > buffer:
print()
buffer = int(month2)
month1=driver.find_elements_by_xpath('//*[starts-with(#id, "td_")]/td[3]/span[3]')
for spisok_month in month1:
spisok_month = spisok_month.text.replace("'", "").replace(" ", "")
if int(spisok_month) > buffer:
print('ERROR')
elif int(spisok_month) < buffer:
print('OK')
else:
print('==')
buffer = int(spisok_month)
here I would also like to see OK or ERROR only once.
Any ideas?
The problem seems to be with the short form for loop in your first snippet. Basically it should look like the below:
AnyText = driver.find_elements_by_xpath('AnyXpath')
Text = 'name'
if all(Text in AnyText1.text for AnyText1 in AnyText):
print('OK')
else:
print('ERROR')
UPDATE:
On the updated part of your question, this is a different implementation as you have to update the condition in each iteration. For readability, it probably makes sense to keep this expanded:
outcome = 'OK'
for spisok_month in month1:
spisok_month = spisok_month.text.replace("'", "").replace(" ", "")
if int(spisok_month) > buffer:
outcome = 'ERROR'
elif outcome == 'OK' and int(spisok_month) == buffer:
outcome = '=='
buffer = int(spisok_month)
print(outcome)
Note: The update is almost a separate question. this means that either your first question was not representative of the actual problem or you should ask in a separate post
In you code AnyText1 is a WebElement, not a text. You should use AnyText1.text to get text and then it will work:
AnyText = driver.find_elements_by_xpath('AnyXpath')
Text = 'name'
# AnyText1 is a WebElement and you should get text
if all(Text in AnyText1.text for AnyText1 in AnyText):
print('OK')
else:
print('ERROR')
Please check coding conventions to improve code style.

Checking a string in user input using if statement always end up returning the same output. How can it be fixed?

I'm trying to get the user input and check whether it has 'heads' or 'tails' in it using if statement. But I end up getting the same output.
user_input = input('Heads? or Tails? \n')
if 'HEADS' or 'TAILS' in user_input.upper():
print ('you have chosen', user_input)
else:
print ('wrong!')
Input:
random text
Expected output:
wrong!
Output that I get:
you have chosen random text
or does not work that way
if 'HEADS' in user_input.upper() or 'TAILS' in user_input.upper():
When using the OR operator, you have to treat the latter expression as it's own condition to satisfy:
if "HEADS" in user_input.upper() or "TAILS" in user_input.upper():
print("you have chosen", user_input)
else:
print("wrong")

check string by iterate

str1=input()
for i in str1:
if i=='a'
print('word:a')
else:
continue
print('without:a')
I input one word. And i want to check if the word content letter:'a'.
use print() in the end.
The problem is I do not know how to excute the code after continue
The result i want like this:
ex1:
apple
word:a
ex2:
home
without:a
Assuming you are required to use a for loop rather than just check 'a' in str1, use a for-else
str1=input()
for i in str1:
if i=='a'
print('word:a')
break
else:
print('without:a')
if 'a' in input():
print('word:a')
else:
print('without:a')
print("word:a" if 'a' in input() else "without a")

What did I do wrong

import sys
super_heroes = {'Iron Man' : 'Tony Stark',
'Superman' : 'Clark Kent',
'Batman' : 'Bruce Wayne',
}
print ('Who is your favorite Superhero?')
name = sys.stdin.readline()
print ('Do you know that his real name is', super_heroes.get(name))
I'm doing a simple code here that should read an input in a dictionary and print it out after a string of letters, but when ran it prints out
"
Who is your favorite Superhero?
Iron Man
Do you know that his real name is None
"
Even Though the input is in my dictionary.
Your input is having a newline at the end of the line.
I have tried it online REPL. Check it
try following to resolve it.
name = sys.stdin.readline().strip()
After stripping Check here
sys.stdin.readline() returns the input value including the newline character, which is not what you expect. You should replace sys.stdin.readline() with input() or raw_input(), which are really more pythonic ways to get input values from the user, without including the newline character.
raw_input() is preferable to ensure that the returned value is of string type.
To go a little bit further, you can then add a test if name in super_heroes: to perform specific actions when the favorite superhero name is not in your dictionary (instead of printing None). Here is an example:
super_heroes = {'Iron Man' : 'Tony Stark',
'Superman' : 'Clark Kent',
'Batman' : 'Bruce Wayne',
}
print ('Who is your favorite Superhero?')
name = raw_input()
if name in super_heroes:
print ('Do you know that his real name is', super_heroes[name], '?')
else:
print ('I do not know this superhero...')
sys.std.readline() appends a line break at the end of user input you may want to replace it before getting your Super Hero:
name = name.replace('\n','')

Resources