Python newbie here- could you please explain the following
greeting = 'Hello!'
count = 0
for letter in greeting:
count += 1
if count % 2 == 0:
print(letter)
print(letter)
print('done')
greeting = 'Hello!' <-- set greeting variable.
count = 0 <-- set count variable.
for letter in greeting: <-- this loop will loop six times because greeting contains of six character.
count += 1 <-- each times of loop will increase value of count by one.
if count % 2 == 0: <-- this line will print a index of character that % 2 = 0 (eg. 2%2 = 0, 4%2 = 0, ...)
print(letter)
print(letter) <-- this line will print any index of character of greeting. (ps. this line will error because indentation errors.)
print('done') <-- print 'done'.
So the result will be like this:
H e e l l l o ! ! done
Avoiding the indentation error, I am explaining what your code does.
In your program, you have initialized a variable named greeting with value "Hello!" and also a count with value 0.
greeting = 'Hello!'
count = 0
Thereafter a for loop us used which loop through the greeting i.e. till the end of each word Hello!. However, if you wanted to check it by yourself you can print the letter.
for letter in greeting:
print(letter)
Now coming to your problem where you've also incremented the value of count by 1 where the value increases by 1 on each loop execution.
Then you have a condition to check whether the number is even or not count % 2 == 0 followed by the print statement which executes upon the success of condition. This means the letter at the even position will only get printed.
That is what your program does.
greeting = 'Hello!' <-- set greeting variable.
count = 0 <-- set count variable.
for letter in greeting: <-- this loop will loop six times because greeting contains of six character.
count += 1 <-- each times of loop will increase value of count by one.
if count % 2 == 0: <-- this line will print a index of character that % 2 = 0 (eg. 2%2 = 0, 4%2 = 0, ...)
print(letter)
print(letter) <-- this line will print any index of character of greeting. (ps. this line will error because indentation errors.)
print('done') <-- print 'done'.
Related
I'm trying to polish my Python skills and this made me confused. Here's the code:
greeting = 'Hello!'
count = 0
for letter in greeting:
count += 1
if count % 2 == 0:
print(letter)
print(letter)
print('done')
I don't understand what the count does.
this exact code doubles letters which position number is even.
count is for counting letter position.
condition count % 2 == 0 to know which position is divided by 2 without leftovers (check if position is even number)
Let's comment up the code with explanations of what each line does and then examine the output.
# assign the string 'Hello!' to the name greeting
greeting = 'Hello!'
# assign the number 0 to the name count
count = 0
# assign letter to each character in greeting one at a time.
# in the first run of the loop, letter would be 'H', then 'e',
# etc.
for letter in greeting:
# add one to count. count starts at 0, so after this line
# on the first run of the loop, it becomes 1, then 2, etc.
count += 1
# use the modulo operator (%) to get the remainder after
# dividing count by 2, and compare the result to 0. this
# is a standard way of determining if a number is even.
# the condition will evaluate to True at 0, 2, 4, etc.
if count % 2 == 0:
# when count is even, print letter once followed by a
# new line. note that to not print a new line, you can
# write print(letter, end="")
print(letter)
# print letter once followed by a new line regardless of the
# value of count
print(letter)
# print 'done' followed by a new line
print('done')
So, based on all that, what should we expect the output to be? Well, we know that every character of greeting will be printed in the last line of the loop. We also know that every even character of greeting will be printed twice, once inside the if block, and once at the end of the loop. Finally, we know that "done" will be printed after the loop is complete. Therefore, we should expect the following output:
H
e
e
l
l
l
o
!
!
done
This this is very simple see:
greeting = 'Hello!'
In this line you assigned the variable greeting a string value Hello!.
count = 0
In this line you assigned the variable count a integer value 0.
Now the next code is:
for letter in greeting:
count += 1
if count % 2 == 0:
print(letter)
print(letter)
As you may know strings are iterable. See this code before understanding the above:
for letter in greeting:
print(letter)
Forget the count. At each iteration of the loop the loop is printing every character of the greeting.
so the output is:
H
e
l
l
o
!
But why there a newline after each letter. The answer is that print has an optional argument end If the above code is like this:
for letter in greeting:
print(letter, end = '')
Then the output will be:
Hello!
Now there comes the count term. It is also simple. when the count is even it prints the letter iterating at that time in loop twice due to twice print statement. And the count is even or not is checked by if count % 2 == 0.
Write a program to input the lines of text, print them to the screen after converting them to lowercase. The last line prints the number of input lines.
The program stops when it encounters a line with only zero.
Requirements: use infinite loop and break . statement
here's my code but it's saying Input 9 is empty
a = 1
l = 0
while a != 0:
a = input()
a.lower()
print(a)
l+=1
example inputs
TbH
Rn
ngL
bRb
0
I'd suggest this, it's a combination of these 2 comments, sorry
count = 0
while True:
a = input()
if a == '0':
break
else:
print(a.lower())
count += 1
print(count)
This may accomplish what you are trying to achieve:
def infinite_loop():
while True:
user_input = input('enter a value:\n> ')
if user_input == '0':
break
else:
print(user_input.lower())
if __name__ == '__main__':
infinite_loop()
There a few errors in your original code, here is some suggestions and fixes. This post is try to follow your code as much as it can, and point the changes needed.
Please see the comments and ask if you have any questions.
count = 0 # to count the lines
while w != '0': # input's string
w = input().strip() # get rid of \n space
word = w.lower() # convert to lower case
print(word)
count += 1
# while-loop stops once see '0'
Outputs: (while running)
ABBA
abba
Misssissippi
misssissippi
To-Do
to-do
0
0
I'm designing a system that allows users to input a string, and the strength of the string to be determined by the amount of non alphanumeric characters. Points should be awarded like so: +1 for every non-alnum character to a maximum of 3 non-alnum characters.
def non_alnum_2(total,pwd):
count = 0
lid = 3
number = 0
if pwd[count].isalnum():
if True:
print "Nope"
if False:
print "Good job"
count = count + 1
number += 1
if number > lid:
number = lid
return number
total = 0
number = 0
pwd = raw_input("What is your password? ")
non_alnum_2(total, pwd)
print total
total += number
I've only just started coding, so I'm sorry if this seems like a very junior question.
You can simply try:
bonus = min(sum(not c.isalnum() for c in pwd), 3)
If you want to count the number of non-alpha strings you could say
def strength(string):
'''Computes and returns the strength of the string'''
count = 0
# check each character in the string
for char in string:
# increment by 1 if it's non-alphanumeric
if not char.isalpha():
count += 1
# Take whichever is smaller
return min(3, count)
print (strength("test123"))
There are multiple problems with this code.
First, if True: is always true, so the "Nope" will always happen, and if False: is never true, so none of that stuff will ever happen. I think you wanted this:
if pwd[count].isalnum():
print "Nope"
else:
print "Good job"
count = count + 1
number += 1
Also, I think you want to increment count always, not just if it's a symbol, so:
if pwd[count].isalnum():
print "Nope"
else:
print "Good job"
number += 1
count = count + 1
Meanwhile, you need some kind of loop if you want this to happen over and over. For example:
while count < len(pwd):
if pwd[count].isalnum():
# etc.
However, you really don't need to maintain count yourself and keep doing pwd[count]; you can use a for loop for this:
for ch in pwd:
if ch.isalnum():
# etc.
Meanwhile, while you do return a value from the end of the function, you don't do anything with that returned value when you call the function. What you need is:
number = non_alnum_2(total, pwd)
Also, there's no reason to pass total to non_alnum_2 here. In fact, it doesn't do anything useful at all.
So, putting it all together:
def non_alnum_2(pwd):
lid = 3
number = 0
for ch in pwd:
if ch.isalnum():
print "Nope"
else:
print "Good job"
number += 1
if number > lid:
number = lid
return number
pwd = raw_input("What is your password? ")
number = non_alnum_2(pwd)
print number
def non_alnum(s):
temp=[]
for i in s:
if i.isalnum():
continue
else:
temp.append(i)
if temp==[]:
print("The string doesn't contain any non_alphanumeric chars")
else:
print("The string contains non_alphanumeric chars: ",temp)
str1="ABCDEFabcdef123450"
str2="ABCDEF;abcdef'1234!50"
str3="*&%#!}{"
non_alnum(str1)
non_alnum(str2)
non_alnum(str3)
I'm using Python (3.x) to create a simple program for an assignment. It takes a multiline input, and if there is more than one consecutive whitespace it strips them out and replaces it with one whitespace. [That's the easy part.] It must also print the value of the most consecutive whitespaces in the entire input.
Example:
input = ("This is the input.")
Should print:
This is the input.
3
My code is below:
def blanks():
#this function works wonderfully!
all_line_max= []
while True:
try:
strline= input()
if len(strline)>0:
z= (maxspaces(strline))
all_line_max.append(z)
y= ' '.join(strline.split())
print(y)
print(z)
if strline =='END':
break
except:
break
print(all_line_max)
def maxspaces(x):
y= list(x)
count = 0
#this is the number of consecutive spaces we've found so far
counts=[]
for character in y:
count_max= 0
if character == ' ':
count= count + 1
if count > count_max:
count_max = count
counts.append(count_max)
else:
count = 0
return(max(counts))
blanks()
I understand that this is probably horribly inefficient, but it seems to almost work. My issue is this: I would like to, once the loop is finished appending to all_lines_max, print the largest value of that list. However, there doesn't seem to be a way to print the max of that list without doing it on every line, if that makes sense. Any ideas on my convoluted code?
Just print the max of all_line_max, right where you currently print the whole list:
print(max(all_line_max))
but leave it at the top level (so dedent once):
def blanks():
all_line_max = []
while True:
try:
strline = input()
if strline:
z = maxspaces(strline)
all_line_max.append(z)
y = ' '.join(strline.split())
print(y)
if strline == 'END':
break
except Exception:
break
print(max(all_line_max))
and remove the print(z) call, which prints the maximum whitespace count per line.
Your maxspaces() function adds count_max to your counts list each time a space is found; not the most efficient method. You don't even need to keep a list there; count_max needs to be moved out of the loop and will then correctly reflect the maximum space count. You also don't have to turn the sentence into a list, you can directly loop over a string:
def maxspaces(x):
max_count = count = 0
for character in x:
if character == ' ':
count += 1
if count > max_count:
max_count = count
else:
count = 0
return max_count
I'm trying to create a function where you can put in a phrase such as "ana" in the word "banana", and count how many times it finds the phrase in the word. I can't find the error I'm making for some of my test units not to work.
def test(actual, expected):
""" Compare the actual to the expected value,
and print a suitable message.
"""
import sys
linenum = sys._getframe(1).f_lineno # get the caller's line number.
if (expected == actual):
msg = "Test on line {0} passed.".format(linenum)
else:
msg = ("Test on line {0} failed. Expected '{1}', but got '{2}'.".format(linenum, expected, actual))
print(msg)
def count(phrase, word):
count1 = 0
num_phrase = len(phrase)
num_letters = len(word)
for i in range(num_letters):
for x in word[i:i+num_phrase]:
if phrase in word:
count1 += 1
else:
continue
return count1
def test_suite():
test(count('is', 'Mississippi'), 2)
test(count('an', 'banana'), 2)
test(count('ana', 'banana'), 2)
test(count('nana', 'banana'), 1)
test(count('nanan', 'banana'), 0)
test(count('aaa', 'aaaaaa'), 4)
test_suite()
Changing your count function to the following passes the tests:
def count(phrase, word):
count1 = 0
num_phrase = len(phrase)
num_letters = len(word)
for i in range(num_letters):
if word[i:i+num_phrase] == phrase:
count1 += 1
return count1
Use str.count(substring). This will return how many times the substring occurs in the full string (str).
Here is an interactive session showing how it works:
>>> 'Mississippi'.count('is')
2
>>> 'banana'.count('an')
2
>>> 'banana'.count('ana')
1
>>> 'banana'.count('nana')
1
>>> 'banana'.count('nanan')
0
>>> 'aaaaaa'.count('aaa')
2
>>>
As you can see, the function is non-overlapping. If you need overlapping behaviour, look here: string count with overlapping occurrences
You're using the iteration wrong, so:
for i in range(num_letters): #This will go from 1, 2, ---> len(word)
for x in word[i:i+num_phrase]:
#This will give you the letters starting from word[i] to [i_num_phrase]
#but one by one, so : for i in 'dada': will give you 'd' 'a' 'd' 'a'
if phrase in word: #This condition doesnt make sense in your problem,
#if it's true it will hold true trough all the
#iteration and count will be
#len(word) * num_phrase,
#and if it's false it will return 0
count1 += 1
else:
continue
I guess, str.count(substring) is wrong solution, because it doesn't count overlapping substrings and test suite fails.
There is also builtin str.find method, which could be helpful for the task.
Another way :
def count(sequence,item) :
count = 0
for x in sequence :
if x == item :
count = count+1
return count
A basic question rais this times.
when u see a string like "isisisisisi" howmany "isi" do u count?
at first state you see the string "isi s isi s isi" and return 3 as count.
at the second state you see the string "isisisisisi" and counts the "i" tow times per phrase like this "isi isi isi isi isi".
In other word second 'i' is last character of first 'isi' and first character of second 'isi'.
so you have to return 5 as count.
for first state simply can use:
>>> string = "isisisisisi"
>>> string.count("isi")
3
and for second state you have to recognize the "phrase"+"anything"+"phrase" in the search keyword.
the below function can do it:
def find_iterate(Str):
i = 1
cnt = 0
while Str[i-1] == Str[-i] and i < len(Str)/2:
i += 1
cnt += 1
return Str[0:cnt+1]
Now you have many choice to count the search keyword in the string.
for example I do such below:
if __name__ == "__main__":
search_keyword = "isi"
String = "isisisisisi"
itterated_part = find_iterate(search_keyword)
c = 0
while search_keyword in String:
c += String.count(search_keyword)
String = String.replace(search_keyword, itterated_part)
print c
I do not know if a better way be in python.but I tried to do this with help of Regular Expressions but found no way.