How to continue a loop on a new line? - python

I'm new to python and have a problem that asks to output "#"a certain number of times based upon the value that the user entered. However it also asks to do it twice on two different lines.
I understand that I need to utilize a loop to output the "#" character.
num = int(input())
counter = 0
while counter != num:
print("#", end='')
counter = counter + 1
In the case of num = 3, the output I receive is ### however, it is supposed to be
###
###

This looks like a bit of a trick question. You are on the right path requiring a loop but you need to loop the required number of times eg
NUMBER_OF_LINES = 2
num = int(input())
# Loop the required number of lines
for _ in range(NUMBER_OF_LINES):
# Print the number of "#" symbols. Multiplying a string duplicates it.
print("#" * num)
That will produce the required results.

Is this what you want:
num = int(input())
num_of_lines = 2
for i in range(num_of_lines):
counter = 0
while counter != num:
print("#", end='')
counter = counter + 1
print()

Related

count letters in a loop and break with a special char

I have a small problem here, i´m developing a program for children with special care so can they learn the ABC and a basic math with first contact with a PC, this one requests the user to input a string in a loop and counts the times that we insert a word, in my case i provide the letter "a". and sums every letter in the final
So the problem is that my code isn't breaking the loop if we input the "." it doesn't stop and not counting correctly, does it misses a sum ? i cant figure it out what is wrong and not understand why it´s not stopping
thank you for all the help
while True:
string = input("Insert the text :> " )
count = 0
for x in string :
if x == "a":
count = count + 1
continue
if x == ".":
break
print("the count is" +str(count))
when the program is running i input the examples under
> Insert the text :> banana
1 1 1
Insert the text :> after
1
Insert the text :> .
the count is 0
the expected is to sum all the letters at the end, and gives to me when i put a word e returns the number of A´
for example
input banana 3
input after 1
the count is 4
Like Oliver said, you need to put everything in the while loop. However, you also need to break out of the while loop. I would do it with a variable like so.
running = True
while running:
string = input("Insert the text :> " )
count = 0
for x in string :
if x == "a":
count = count + 1
continue
if x == ".":
running = False
print("the count is" + str(count))
The following code should work:
searchLetter = "a"
stopLetter = "."
totalCount = 0
while True:
string = input("Insert the text :> ")
subCount = string.count(searchLetter)
totalCount += subCount
if string.count(stopLetter) != 0:
break
print(subCount)
print("The count is " + str(totalCount))
We're using built-in str.count() function to see how many times a letter appears in a given word or line.
If the stopLetter (in this case .) appears, we instantly break out of the while loop. Otherwise, we keep accepting input.
You need to put all of your code inside the while loop:
while True:
string = input("Insert the text :> " )
count = 0
for x in string :
if x == "a":
count = count + 1
continue
if x == ".":
break
print("the count is" +str(count))
If you are considering counting every alphabet and asking the user to input a letter to find out how many times it appears, you can use a built-in function called Counter from the collections library.
from collections import Counter
while True:
string = input("Insert the text :> " )
if string == ".":
break
dictionary = Counter(string.lower())
answer = input("Press 'y' to start counting!")
while answer.lower() == 'y':
letter = input("What letter do you want to check? ")
print("the count is" , dictionary[letter])
answer = input("Do you wish to continue to check the letter? [y/n]")
The range of answers is all struggling with exit-condition and char-counting, including UI-improvements and case-sensitivity.
Divide and Conquer
I thought it would help to split you project into small isolated and testable functions. This way you can:
find bugs easier next time
easily extend for new features
Solution
def count_char(s, char, stop_char):
count = 0
for letter in s:
if letter == stop_char:
return None
elif letter == char:
count = count + 1
return count
def ask_and_count(letter, stop_char):
s = input("Counting '{letter}'s for your input (enter {stop_char} to quit):")
counted = count_char(s, letter, stop_char)
if counted is None:
return None
print(f"Counted {counted} 'a's.")
return counted
letter = 'a'
stop_char = '.'
runs = 0
while runs >= 0:
# debug-print: print(f"Run #: {runs}")
count = ask_and_count(letter, stop_char)
if count is None:
break # alternatively set runs = -1
{total}")
total += counted
# debug-print: print(f"Run #: {runs} + Counted: {count} = Total:
# Loop exited because user entered stop_char
print(f"Runs: {runs}, Total sum of '{letter}'s counted: {total}.")
This was the console dump for a test-run:
Counting 'a's for your input (enter . to quit): a
Counted 1.
Counting 'a's for your input (enter . to quit): aa
Counted 2.
Counting 'a's for your input (enter . to quit): bcdaaa
Counted 3.
Counting 'a's for your input (enter . to quit): a.a
Counted 2 when finding stop-char. Will quit without adding and display previous total.
Runs: 4. Total sum of 'a's counted: 6.
Useful patterns
defined a lot of functions (learn about def keyword arguments and return)
the exit-condition has now 2 alternatives: break # alternatively set runs = -1
plenty of informal printing done using f-strings (very useful, since Python 3.6)
added features: parameterised chars, run counter, improved UI

How to put a choice to try again to repeat the loop?

So after finishing the code, I would like to have an option where the user would like to try again by typing Y/n or N/n. How do I make it?
a=int(input('enter value of n: '))
i = 1
sum=0
while a < 1 or a > 300:
print(a, 'is not in the range 1-300')
exit()
for a in range(1,a+1):
print (a, end = ' ')
while i<=a:
if i%3==0 or i%5==0:
sum=sum+i
i=i+1
print('\nsum of all multiples of 3 and 5 is:',sum)
repeat=str(input('Would you like to try again? Y/N?'))
Here's a simple way to do it (keeping your code structure) without any functions or jargon (for beginners :]):
from sys import exit # Just something to exit your code
repeat = 'y' # So it starts the first time
while repeat.lower() == 'y': # repeat.lower() -> convert the string 'repeat' to lowercase, incase user inputs 'Y'. you could also use the or keyword here though
n = int(input("Enter value of n:\n>>> "))
if n < 1 or n > 300:
print("'n' must be between 1 - 300, not " + n) # You could use f-strings, check them out!
exit()
sum_of_multiples = 0
# I'm combining your for and while loop as shown below
for i in range(1, n + 1): # Don't name your 'i' and 'n' variables the same -> you did so with 'a'
print(i, end=', ') # There are cleaner ways to do this but I'm assuming this is what you want
if i % 3 == 0 or i % 5 == 0:
sum_of_multiples += i
# Printing output
print(f"\nSum of all multiples of 3 and 5 is: {sum_of_multiples}") # This is called an f-string
repeat = input("\nDo you want to go again?\n>>> ") # If you don't input Y/y, the outer while loop will break and terminate
print("Thank you for running me!") # Prints after the program finishes running
Note that you don't need the exit() when checking if n is within 1 - 300, you could also just use break.
EDIT (WITH BREAK)
Program without from sys import exit below:
repeat = 'y' # So it starts the first time
while repeat.lower() == 'y': # repeat.lower() -> convert the string 'repeat' to lowercase, incase user inputs 'Y'. you could also use the or keyword here though
n = int(input("Enter value of n:\n>>> "))
if n < 1 or n > 300:
print("'n' must be between 1 - 300, not " + n) # You could use f-strings, check them out!
break # This will mean that "Thank you for running me!" gets printed even if your input is wrong
sum_of_multiples = 0
# I'm combining your for and while loop as shown below
for i in range(1, n + 1): # Don't name your 'i' and 'n' variables the same -> you did so with 'a'
print(i, end=', ') # There are cleaner ways to do this but I'm assuming this is what you want
if i % 3 == 0 or i % 5 == 0:
sum_of_multiples += i
# Printing output
print(f"\nSum of all multiples of 3 and 5 is: {sum_of_multiples}") # This is called an f-string
repeat = input("\nDo you want to go again?\n>>> ") # If you don't input Y/y, the outer while loop will break and terminate
print("Thank you for running me!") # Prints after the program finishes running
Hope this helped!

how to print random number 10 times in one line [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 1 year ago.
I want to print 10 random number and I try this:
import random
number = 10
while number <= 10:
print(random.randint(0,9))
number += 1
but this print next number in the new line. I try below code to fix that but:
import random
number = 10
my_list = []
while number <= 10:
my_list.append(random.randint(0,9))
number += 1
print my_list
it display number with , and []
To print without a new line you should edit the end argument which is set to newline by default, in. You could edit the print command in your first attempt to:
print(random.randint(0,9), end = " ")
import random
randomlist = []
for i in range(0,5):
n = random.randint(1,30)
randomlist.append(n)
print(randomlist)
you can read more about it [here][1].
for the basics of printing:https://www.geeksforgeeks.org/print-without-newline-python/

how to solve this factorial

I've managed to get factors in a list but I can't finish because I'm doing something wrong in the end, the count variable is not updating with the products.
I want to solve it without using the factorial function.
Question:
Write a program which can compute the factorial of a given number.
The results should be printed in a comma-separated sequence on a single line.
Suppose the following input is supplied to the program:
8
Then, the output should be:
40320
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
user = int(input("Input a number: "))
factors = []
while user > 0:
n = user * (user - 1)
if user == 1:
factors.append(1)
break
else:
factors.append(user)
user -= 1
count = 0 # this should be updating but it's not
for f in range(factors[0]): # I'm not sure if this is the correct range
counting = factors[f] * factors[f + 1] # I'm not sure about this either
count = count + counting
f = f + 1
Just change the last part of your program to:
result = 1
for f in factors:
result *= f
print result
Finding the factorial of a number is simple. I'm no python expert, and it could probably be written simpler but,
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
I think #erip may be right in the comment section.
num = int(input("Input a number: "))
factorial = 1
for i in range(2,num+1): # range isn't inclusive
factorial*=i

iterating same number using while loop

I'm just starting to learn while loops.
I'm trying to iterate same number 10 times using a while loop.
I figured out how I can utilize while loop in order to stop at a certain point as it increases
But I can't figure out how to stop at a certain point without having to add 1 and setting a limit.
Here is my code
i = 1
total = 0
while i < 11:
print i
i += 1
total = i + total
print total
This prints
1,2,3,4,5,6,7,8,9,10,65
in a separate line
How could I modify this result?
1,1,1,1,1,1,1,1,1,1,10?
Just print a literal 1 and add 1 to the total:
while i < 11:
print 1
i += 1
total += 1
You need to keep track of how many times your loop is run, and using i for that is fine, but that does mean you need to increment it on each run through.
If, during each loop, you only want to add one to the total, just do that and don't use the loop counter for that.
i = 1
total = 0
res = []
while i < 11:
res.append(1)
i += 1
print ', '.join(res) +', '+ str(sum(res))
or with for:
vals = [1 for _ in range(10)]
print ', '.join(vals) +', '+ str(sum(vals))
The whole point of a while loop is to keep looping while a certain condition is true. It seems that you want to perform an action n times then display the number of times the action was performed. As Martijn mentioned, you can do this by printing the literal. In a more general sense, you may want to think of keeping your counter separate from your variable, e.g.:
count = 1
number = 3
while count <11:
print number*count
print "While loop ran {0} times".format(count)

Categories

Resources