check string by iterate - python-3.x

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")

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 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")

Reversing a string is not matching with the expected output in Python

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")

Python - Check if a user input is in another user input

Python 3.5
I am writing a program that essentially asks the user to input a sentence (no punctuation). Then it will ask for the user to input a word. I want the program to identify whether or not that word is in the original sentence (I refer to the sentence as string 1 (Str1) and the word as string 2 (Str2)). With the current code I have, it will only ever tell me that the word has been found and I can't seem to find a way to fix it.
str1 = input("Please enter a full sentence: ")
print("Thank you, You entered:" , str1)
str2 = input("Now please enter a word included in your sentence in any way you like: ")
if (str2,str1):
print("That word was found!")
else:
print("Sorry, that word was not found")
If anyone has any advice on that might help me and anyone else interested in this topic then that would be greatly appreciated! :)
Although as this is a learning process for me, i don't really want straight forward "here's the code you should have..." but if that is all that can be offered then i would be happy to take it.
if str2 in str1:
print("That word was found!")
else
print("Sorry, that word was not found")
Is this what you are looking for ?
The in checks if str2 is literally in str1. Since str1 is a list of words it checks if str2 is inside str1.
The answer provided works ok, but if you want word matching, will provide a false positive given:
EDIT: just spotted the prompt asks for a word in the sentence... In my experience, these sorts of things are most prone to breakage when they interact with a human, so I try to plan accordingly.
str1 = "This is a story about a man"
str2 = "an"
where:
broken_string = str1.split()
if str2.lower() in [x.lower() for x in broken_string]:
print("The word {} was found!".format(str2))
else:
print("{} was not found in {}.".format(str2, str1))
Gets a little more complicated (fun) with punctuation.

How can I match variable with cellObj value and verify the two are the same?

jurisdiction == "Brazil"
if jurisdiction == "Brazil":
for rowOfCellObjects in sheet['A2':'A5']:
for cellObj in rowOfCellObjects:
if cellObj.value == 'Germany':
print(cellObj.value)
else:
print("No")
else:
print("Try Again")
I know for sure that "Germany" is a string in those selected cells in the sheet. When you print the cellObj.value it returns "Germany". However, when I ask it to match, "if cellObj.value == "Germany"", it always returns no. Any help would be appreciated.
If you think your code is correct but somehow the library or computer is trying to trick you then you should investigate further.
For example, adding debugging code to print or log the cell coordinate and its value would help you isolate problems such as trailing spaces or unicode / byte confusion.
Have you tried using iter_rows()?
I've never iterated over a sheet like you are trying to do, but I've done this instead:
if jurisdiction == "Brazil":
for rowOfCellObjects in sheet.iter_rows('A2:A5'):
for cellObj in rowOfCellObjects:
if cellObj.value == 'Germany':
print(cellObj.value)
else:
print("No")
else:
print("Try Again")

Resources