Multiple if statements under one code, with multiple conditons [duplicate] - python

This question already has answers here:
How do boolean operators work in 'if' conditions?
(3 answers)
"or" condition causing problems with "if"
(4 answers)
Closed 9 years ago.
French countries names are feminine when they end with the letter E, masculine otherwise. There are 6 exceptions.(belize, cambodge, mexique, mozambique, zaire, zimbabwe) I am to write a program that takes in an input and adds le, or la infront depending on if it masculine or feminine.
Also, if the country names starts with a vowel it needs to print l' infront instead of le, or la.
One more condition. If the input is one of these two plural countries it is to print les infront.(etats-unis, pays-bas)
Here is my current code
vowels=("aeiouAEIOU")
word=input("Enter a french country :")
if word==("belize")or("cambodge")or("mexique")or("mozambique")or("zaire")or("zimbabe"):
print("le",word)
elif word==("etats-unis")or("pays-bays"):
print("les",word)
elif word.endswith("e"):
print("le",word)
else:
print("la",word)
if word.startswith(vowels):
print("l'",word)
The problem Im having is no matter what input I use it always prints le infront.
For example: Input Canada; Output le Canada.
Why is it not testing the other conditions?

It's because:
if word == "A" or "B":
isn't the same as
if word == "A" or word == "B":
The first evaluates (is word == "A") logical_or ("B")
So the first version always evaluations to true. Here's an example:
>>> X = "asdf"
>>> if(X):
... print("hurray")
...
hurray
>>>

Give this a shot
exceptions = set("belize cambodge mexique mozambique zaire zimbabwe".split())
vowels = set('aeiou')
plurals = set("etats-unis pays-bas".split())
word, sentinel = "", "quit"
while word != sentinel:
word = input("Enter the name of a country: ")
if word == sentinel:
continue
male = word in exceptions or word[-1].lower() not in vowels
plurality = word in plurals
apo = word[0].lower() in vowels
if apo:
print("l'%s" %word)
elif plurality:
print("les", word)
else:
print("le" if male else "la", word)

use:
if word in ["belize", "cambodge", "mexique", "mozambique", "zaire", "zimbabe"]:
print("le",word)
The problem here is that word==("belize")or("cambodge")or("mexique") is not doing what you think. There are lots of explanations of this around, but to get it to work, you either need to do what I have above or something like:
if word=="belize" or word=="cambodge" or word=="mexique": # etc

Related

Multiple strings in one variable

Say, for example, I have some code that goes like this:
sentence = input("Enter input: ")
target_letter = "a" or "b" or "c"
print(sentence.index(target_letter))
My main aim is to get the program to print any of the target letters' minimum index in the sentence. However when the Boolean "or" operators are used here it only recognizes the first string in the variable. For example: If I type
Ice cream
The program should recognize the 'c' as the first valid string in the index and print "1" but it skips to 'a' and prints "7".
The same sort of problem arises with the "and" operator:
sentence = input("Enter input: ")
target_letter = "a" and "b" and "c"
print(sentence.index(target_letter))
This time the program only recognizes the last string in the variable instead, if I type:
Exactly
The program throws back "3" becuase c's index is 3 but the first letter is actually 'a' with index 2. And when the input had only a "b" in it out of the strings, the program threw an error because it was neither the first string or the last string.
How would this problem be fixed so that I could place multiple possible strings in a variable so that one of the strings in the variable would be recognized later in the program?
Let's examine the target_letter = "a" or "b" or "c" first.
>>> target_letter = "a" or "b" or "c"
>>> target_letter # will always return 'a' because 'a' is true.
'a'
>>> # The only string which will return false is the empty string '' or "".
A proposed solution
sentence = input("Enter input: ")
target_letters = ["a", "b", "c"]
for letter in sentence:
if letter in target_letters:
print(letter, 'was found at location in ',sentence.index(letter))
else:
print(letter, "was not found in sentence,", sentence)
Output
Enter input: Ice creeam
I was not found in sentence, Ice creeam
c was found at location in 1
e was not found in sentence, Ice creeam
was not found in sentence, Ice creeam
c was found at location in 1
r was not found in sentence, Ice creeam
e was not found in sentence, Ice creeam
e was not found in sentence, Ice creeam
a was found at location in 8
m was not found in sentence, Ice creeam
Process finished with exit code 0
One way to do this is with a regular expression that matches any of those characters.
import re
pattern = r'[abc]' # define regex that matches 'a' OR 'b' OR 'c'
sentence = 'Exactly'
m = re.search(pattern, sentence)
if m:
print(m.start())
Based on what I understood from your description, I guess, this should help.
sentence = input("Enter input: ")
for i in sentence:
if i in "abc":
print(i, " : ", sentence.index(i))
We can achieve this using next and a generator expression along with enumerate.
>>> s = "ice cream"
>>> next((i for i, ch in enumerate(s) if ch in "abc"), None)
1
enumerate gives us the index as we iterate over the string. The generator returns indices where the corresponding character is in "abc". Then we call next to get the first match or None is a match is not found.

How to find if the given strings can be found inside the second strings [duplicate]

This question already has answers here:
Does Python have a string 'contains' substring method?
(10 answers)
How do I do a case-insensitive string comparison?
(15 answers)
Closed last month.
I would like to know how to write a function that returns True if the first string, regardless of position, can be found within the second string by using two strings taken from user input. Also by writing the code, it should not be case sensitive; by using islower() or isupper().
Example Outputs:
1st String: lol
2nd String: Hilol
True
1st String: IDK
2nd String: whatidk
True
My code:
a1 = str(input("first string: "))
a2 = str(input("second string: "))
if a2 in a1:
print(True)
else:
print(False)
It outputs:
1st String: lol
2nd String: lol
True
1st String: lol
2nd String: HIlol
False #This should be true, IDK why it is false.
I only came this far with my code. Hoping someone could teach me what to do.
Is this what you're looking for?
string_1 = input("first string: ")
string_2 = input("second string: ")
if string_1.lower() in string_2.lower():
print(True)
else:
print(False)
A "function" would be:
def check_occuring(substring, string):
if substring.lower() in string.lower():
return True
else:
return False
string_1 = input("first string: ")
string_2 = input("second string: ")
print(check_occuring(string_1, string_2))
Please note that you can also just print or return substring.lower() in string.lower()
If you want the Program to be case sensitive, just make everything lowercase
substring = input("substring: ").lower()
text = input("text: ").lower()
To check if a substring can be found in another string can be done by using the keyword in
>>> "lol" in "HIlol"
True
maybe check your inputs here. The whole program would be
substring = input("substring: ").lower()
text = input("text: ").lower()
print(substring in text)
note: <str> in <str> gives you a boolean so you can use it in if conditions. In this case you can just print the boolean directly.

How to count words that end with a letter? (python)

I am a beginner and this is what I came up with so far. However, it does not output the correct number of words that end with "a" or "b." Any tips on how to correct this code?
names = input("Enter list of names: ")
name = names.split(" ")
num = len(name)
ab = ""
print("Number of words:", num)
for i in range(num):
if name[i] == ' ':
if name[i-1] == a:
ab.append() + " "
elif name[i-1] == b:
ab.append() + " "
a_b = ab.split(' ')
print("Number of words that end with a or b: ",len(a_b))
In Python boolean (True and False) are the same as the integers 1 and 0. This means you can use sum() to count True booleans. str.endswith() returns a boolean. This means you can just do this:
words = ["stab", "drama", "hello", "magma", "test"]
a_b = sum(word.endswith(('a', 'b')) for word in words)
# 3
z_c = sum(word.endswith(('z', 'c')) for word in words)
# 0
Any tips on how to correct this code?
Others have answered alternative, working solutions, but I want to try to point out the specific things wrong in your code snippet and tips to correct.
First here's a copy of your snippet with some simple debugging prints along with their output (running in python 3.10).
names = "Barry Lima Bab"
name = names.split(" ")
print(f"{name=}") # name=['Barry', 'Lima', 'Bab']
num = len(name)
print(f"{num=}") # num=3
ab = ""
print("Number of words:", num)
for i in range(num):
print(name[i]) # Barry -> Lima -> Bab
if name[i] == ' ':
if name[i-1] == a:
ab.append() + " "
elif name[i-1] == b:
ab.append() + " "
print(f"{ab=}") # ab=''
a_b = ab.split(' ')
print(f"{a_b=}") # a_b=['']
Breaking things down step by step like this is a great starting point for better understanding what's going on.
if name[i] == ' ': Notice the value of name[i] so this check never resolves to True meaning the code inside never runs
if the inner code did run, you'd hit a NameError: name 'a' is not defined. Did you mean: 'ab'? because a is undefined. Probably meant 'a' here. same for b
In my example, name[i-1] would be 'Bab' -> 'Barry' -> 'Lima' which is probably not what you're expecting. This is because you're getting the -1th, 0th, 1st items in name. to get the last letter from the name, you want name[i][-1] here
if you then get into either of the furthest inside conditions, you'd encounter AttributeError: 'str' object has no attribute 'append' which happens because append is for list not str. You couldchange ab to be a list to use this in which case you'd want ab.append(name[i]) or you can use string concatenation like ab += " " + name[i] or using str.concat
1 last note of interest, you may have noticed your code as-is really likes to return and say that there's 1 item. This is because the above issues always (if the program doesn't break) leaves ab == '' and ''.split(' ') => [''] and thus len(ab.split(" ")) => 1
1 tip that I think would help in code comprehension is that the name variable here is not a single name string like it implies. It's actually a list[str]. I'd probably denote the variables something more like names_str: str vs names: list[str] or raw_names vs names. Then just use something like for name in names: and not worry about indexes. You can also use name.endswith('a') instead of name[-1] == 'a' for better readability.
Eventually you can combine these into a list comprehension for maximal succinctness -> len([name for name in names if name.endswith('a') or name.endswith('b')]).
words = ["ab", "bab", "pa", "pap"]
result = 0
for word in words:
if word[-1] in "ab":
result += 1
print(result)
As a list comprehension:
words = ["word1a", "word2b", "word3", "word4", "word5a"] # ['word1a', 'word2b', 'word5a']
filtered_words = [word for word in words if word[-1] in "ab"]
filtered_words = [word for word in words if word.endswith(("a", "b"))] # better, if you have multiple endings you want to search for with different lengths
len(filtered_words) # 3
name[i-1] is the previous name in the list, not the last character of the current name in the loop.
There's no need to append the matching names to a string. If you just need the count of matches, increment a counter variable.
You need to put a and b in quotes to make them strings, not variables.
names = input("Enter list of names: ")
name = names.split(" ")
matches = 0
print("Number of words:", len(name))
for cur_name in name:
if cur_name.endswith('a') or cur_name.endswith('b'):
matches += 1
print("Number of words that end with a or b: ", matches)
Use the endswith string method to detect if the last letter is "a" or "b"
names = ["bob","boba","larry","curly","moe"]
count = 0
for name in names:
if name.endswith("a") or name.endswith("b"):
count += 1
print(f"{count=}") # count=2

Python: How to print results from conditions all in one line [duplicate]

This question already has answers here:
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed last month.
I'm new to coding, and I found this exercise problem in a Python practice website. The instructions go like this:
"Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".
So I inputted this code:
def translate(string):
vowels=['a','e','i','o','u']
for letter in string:
if letter in vowels:
print(letter)
else:
print(letter+'o'+letter)
print(translate('this is fun'))
and I got this:
tot
hoh
i
sos
o
i
sos
o
fof
u
non
None
So how do I put all these strings in one line? I've been scratching my head for so long. Please help and thank you:)
You can concatenate the strings iteratively. You should include a whitespace as part of the characters to exclude to avoid putting an 'o' in between whitespaces.
def translate(string):
notconsonant = ['a','e','i','o','u', ' ']
s = ''
for letter in string:
if letter in notconsonant:
s += letter
else:
s += letter+'o'+letter
return s
Or use join with a generator expression that returns the right letter combination via a ternary operator:
def translate(string):
notconsonant = {'a','e','i','o','u', ' '}
return ''.join(letter if letter in notconsonant else letter+'o'+letter for letter in string)
Note that you can speed up the lookup of letters that are not consonants if you made the list a set, as membership check for sets is relatively faster.
>>> translate('this is fun')
'tothohisos isos fofunon'
Just use the end parameter in print function. (I assumed that you are using python 3.x, with print being a function)
def translate(string):
vowels=['a','e','i','o','u']
for letter in string:
if letter in vowels:
print(letter, end='')
else:
print(letter+'o'+letter, end='')
print(translate('this is fun'))
Try to append it in a temporary string and to print it at the end ;)
print get's you to a new line. Use a concatenation and a new string instead (here the new string is called result) :
def translate(string):
vowels=['a','e','i','o','u']
# Use a new variable :
result = ''
for letter in string:
if letter in vowels:
result = result + letter
else:
result = result + letter + 'o' + letter
return result
print(translate('this is fun'))

Count vowels from raw input

I have a homework question which asks to read a string through raw input and count how many vowels are in the string. This is what I have so far but I have encountered a problem:
def vowels():
vowels = ["a","e","i","o","u"]
count = 0
string = raw_input ("Enter a string: ")
for i in range(0, len(string)):
if string[i] == vowels[i]:
count = count+1
print count
vowels()
It counts the vowels fine, but due to if string[i] == vowels[i]:, it will only count one vowel once as i keeps increasing in the range. How can I change this code to check the inputted string for vowels without encountering this problem?
in operator
You probably want to use the in operator instead of the == operator - the in operator lets you check to see if a particular item is in a sequence/set.
1 in [1,2,3] # True
1 in [2,3,4] # False
'a' in ['a','e','i','o','u'] # True
'a' in 'aeiou' # Also True
Some other comments:
Sets
The in operator is most efficient when used with a set, which is a data type specifically designed to be quick for "is item X part of this set of items" kind of operations.*
vowels = set(['a','e','i','o','u'])
*dicts are also efficient with in, which checks to see if a key exists in the dict.
Iterating on strings
A string is a sequence type in Python, which means that you don't need to go to all of the effort of getting the length and then using indices - you can just iterate over the string and you'll get each character in turn:
E.g.:
for character in my_string:
if character in vowels:
# ...
Initializing a set with a string
Above, you may have noticed that creating a set with pre-set values (at least in Python 2.x) involves using a list. This is because the set() type constructor takes a sequence of items. You may also notice that in the previous section, I mentioned that strings are sequences in Python - sequences of characters.
What this means is that if you want a set of characters, you can actually just pass a string of those characters to the set() constructor - you don't need to have a list one single-character strings. In other words, the following two lines are equivalent:
set_from_string = set('aeiou')
set_from_list = set(['a','e','i','o','u'])
Neat, huh? :) Do note, however, that this can also bite you if you're trying to make a set of strings, rather than a set of characters. For instance, the following two lines are not the same:
set_with_one_string = set(['cat'])
set_with_three_characters = set('cat')
The former is a set with one element:
'cat' in set_with_one_string # True
'c' in set_with_one_string # False
Whereas the latter is a set with three elements (each one a character):
'c' in set_with_three_characters` # True
'cat' in set_with_three_characters # False
Case sensitivity
Comparing characters is case sensitive. 'a' == 'A' is False, as is 'A' in 'aeiou'. To get around this, you can transform your input to match the case of what you're comparing against:
lowercase_string = input_string.lower()
You can simplify this code:
def vowels():
vowels = 'aeiou'
count = 0
string = raw_input ("Enter a string: ")
for i in string:
if i in vowels:
count += 1
print count
Strings are iterable in Python.
for i in range(0, len(string)):
if string[i] == vowels[i]:
This actually has a subtler problem than only counting each vowel once - it actually only tests if the first letter of the string is exactly a, if the second is exactly e and so on.. until you get past the fifth. It will try to test string[5] == vowels[5] - which gives an error.
You don't want to use i to look into vowels, you want a nested loop with a second index that will make sense for vowels - eg,
for i in range(len(string)):
for j in range(len(vowels)):
if string[i] == vowels[j]:
count += 1
This can be simplified further by realising that, in Python, you very rarely want to iterate over the indexes into a sequence - the for loop knows how to iterate over everything that you can do string[0], string[1] and so on, giving:
for s in string:
for v in vowels:
if s == v:
count += 1
The inner loop can be simplified using the in operation on lists - it does exactly the same thing as this code, but it keeps your code's logic at a higher level (what you want to do vs. how to do it):
for s in string:
if s in vowels:
count += 1
Now, it turns out that Python lets do math with booleans (which is what s in vowels gives you) and ints - True behaves as 1, False as 0, so True + True + False is 2. This leads to a one liner using a generator expression and sum:
sum(s in vowels for s in string)
Which reads as 'for every character in string, count how many are in vowels'.
you can use filter for a one liner
print len(filter(lambda ch:ch.lower() in "aeiou","This is a String"))
Here's a more condensed version using sum with a generator:
def vowels():
string = raw_input("Enter a string: ")
print sum(1 for x in string if x.lower() in 'aeiou')
vowels()
Option on a theme
Mystring = "The lazy DOG jumped Over"
Usestring = ""
count=0
for i in Mystring:
if i.lower() in 'aeiou':
count +=1
Usestring +='^'
else:
Usestring +=' '
print (Mystring+'\n'+Usestring)
print ('Vowels =',count)
The lazy DOG jumped Over
^ ^ ^ ^ ^ ^ ^
Vowels = 7

Categories

Resources