What does "for letter in greeting" do in the given code? - python-3.x

greeting = 'Hello!'
count = 0
for letter in greeting:
count += 1
if count % 2 == 0:
print(letter)
print(letter)
print('done')

Strings in Python are sequences of individual characters, so what for letter in greeting does is to iterate through each character in the string greeting, and assign each character to the variable letter in each iteration.

Your answer will be :
!
!
done
Detailed Explanation :-
Your string is greeting='Hello!'
You have initialized Count to 0
In line, " for letter in greeting: " --> letter is not a property of for loop but simply a variable that will hold each alphabet of string in incrementing iterations. You can also use --> for i in greeting: --> then 'i' will contain each alphabet of string stored in variable 'greeting'.
Then Count+=1 , will execute for all letters in string "Hello!" i.e H,e,l,l,o,! --> Count = 6.
Then it will check that if Count is divisible by 2 or "is an even number" then it will display "letter" i.e. '!' because after complete execution of above 'for loop' the last value in variable letter is '!'. Since, if statement results in true, it will print '!' followed by '!' and finally 'done'.

Related

Counting the number of vowels in a string and returning the count Python?

I am a beginner and my objective is this - Write a function called count_vowels that accepts a string argument that represents a word and returns the number of vowels that are in the word.
Heres my code so far to explain:
string = 'oboe'
def count_vowels(string):
count = 0
if 'a' or 'A' in string:
count += 1
if 'e' or 'E' in string:
count += 1
if 'i' or 'I' in string:
count += 1
if 'o' or 'O' in string:
count += 1
if 'u' or 'U' in string:
count += 1
return count
print(count_vowels(string))
Where i am a bit lost is the output value. If you run this code with the word 'oboe' you get 5. makes no sense So i was wondering, do elif statements change the output? Besides that, what would I need to alter in my code to have it work properly. I feel like something is being iterated upon too many times.
thank you!
The if-conditions in form if 'a' or 'A' in string: etc. are always evaluating to True. It should be if ('a' in string) or ('A' in string):.
Also, it's necessary to evaluate these conditions in a loop, to get correct answer.
Here is example with sum() builtin:
def count_vowels(string):
return sum(ch in 'aeiou' for ch in string.lower())
print(count_vowels('oboe'))
Prints:
3

Check if the python string contains specific characters

I have to write a program that prompts user for input and should print True only if every character in string entered by the user is either a digit ('0' - '9') or one of the first six letters in the alphabet ('A' - 'F'). Otherwise the program should print False.
I can't use regex for this question as it is not taught yet, i wanted to use basic boolean operations . This is the code I have so far, but it also outputs ABCH as true because of Or's. I am stuck
string = input("Please enter your string: ")
output = string.isdigit() or ('A' in string or 'B' or string or 'C' in string or 'D' in string or 'E' in string or 'F' in string)
print(output)
Also i am not sure if my program should treat lowercase letters and uppercase letters as different, also does string here means one word or a sentence?
We can use the str.lower method to make each element lowercase since it sounds like case is not important for your problem.
string = input("Please enter your string: ")
output = True # default value
for char in string: # Char will be an individual character in string
if (not char.lower() in "abcdef") and (not char.isdigit()):
# if the lowercase char is not in "abcdef" or is not a digit:
output = False
break; # Exits the for loop
print(output)
output will only be changed to False if the string fails any of your tests. Otherwise, it will be True.

How to keep the vowel at the beginning of all the words in a string, but remove in the rest of the string

def shortenPlus(s) -> "s without some vowels":
for char in s:
if char in "AEIOUaeiou":
return(s.replace(char,""))
I have the taken it out of the entire string. But I can't figure out how to restrict the replace function to everything but the first letter of each word in a string.
Not sure exactly what you're looking for, can you clarify, perhaps give a simple example? None of the words you have in your example start with vowels!
But here you could remove all the vowels in a word except the first vowel of the first word. Hard coded but gives you an idea:
s="without some vowels"
for char in s[2:]:
if char in "AEIOUaeiou":
s=s.replace(char,"")
print(s)
Outputs
witht sm vwls
Alternatively, to get the first char of every word, you could use a sentinel value that flags each time a non-alpha char such as punctuation or a space is present, then keeps the next char but not the others.
s="without some vowels"
sent=2
for char in s:
if sent>0:
sent-=1
print(char)
continue
if not char.isalpha():
sent=2
continue
s=s.replace(char,"")
print(output)
Outputs
w s v
def shortenPlus(s):
counter = 0 # accepted character count
add_the_vowel = True # check if vowel came for the first time for the word
temp = " " # temp string to store the output
for letter in s:
if letter == " ":
add_the_vowel= True
if add_the_vowel == True and letter in "AEIOUaeiou":
temp += s[counter] # first vowel of the word
if letter in "AEIOUaeiou":
add_the_vowel = False # restrict second vowel appeared
else:
temp += s[counter]
counter += 1
print(temp)
s = "without some vowels frienis"
shortenPlus(s)
How to keep the vowel at the beginning of all the words in a string, but remove in the rest of the string
output :
witht som vowls frins

How to use a FOR loop check if a list of strings has letter a certain letter inside them?

for example,
if i were to use the list: List= ['hQTsk', 'MXqoP', 'FmErkX']
how would i use a FOR Loop to check if the strings in the list contain the letter 'k' and then display the string and weather or not it has the letter 'k'.
My first attempt was:
for strings in List:
if any('k' in strings):
print(str(strings) + " has the letter 'k'")
else:
print(str(strings) + " doesn't have the letter 'k'")
and i don't know why it's not working
You don't need any:
if 'k' in strings:

Counting the number of capital letters in an input?- in python

On python how do you make a program that asks for an input and the program works out the number of capital letters in that input and output the number of capital letters?
Loop through the string and use .isupper() to check if the letter is uppercase and increment the count. Finally print the count.
inpt = raw_input('Enter something: ')
c = 0
for i in inpt:
if i.isupper():
c += 1
print "No. of uppercase letters: ", c
len(filter(lambda x:isupper(x),list(input("Enter String"))))
Try the following function:
def capital(word):
num = 0
for char in word:
if char.isupper():
num+=1
return num
And incorporate it as such:
word = input('Enter: ')
print capital(word)

Resources