How to make function loop on its own separate line? - python

I have written for a coding problem assigned to me essentially there is a scratch and win ticket and I have to figure out what prizes I could win. I will be given 10 inputs and each output after running through should be on its own line. However Every time I run the code with 10 inputs all of the inputs just appear on one line.
How do I make sure that each output appears on its own line?
Although to be noted my code does output the correct answer its just the formatting that is troubling I want each answer to be on its own line instead of just being on one line.
from collections import Counter
def Winner(L):
zz = Counter(L)
if zz["63"] == 9:
print("No Prizes Possible")
elif zz["63"] == 0:
for T in zz:
if zz[T] >= 3:
print("$" + T, end=" ")
else:
for V in zz:
KK = zz[V] + zz["63"]
if KK >= 3:
if V != "63":
print("$" + V, end=" ")
for d in range(10):
z = [input() for i in range(9)]
yy = []
for g in z:
if g == "?":
yy.append(ord(g))
else:
yy.append(g.replace("$", ""))
yy = [int(i) for i in yy]
yy.sort()
yy = [str(i) for i in yy]
Winner(yy)
Here is a sample input of what I mean:
$10
$100
?
$10
$1
$50
$50
$1000
$1
essentially having 10 inputs like these.

If you add \n (the newline character) at the end of your string, you will add a newline after each time your program prints. For example, you could have this loop which would print "hello world" 10 times, each on its own separate line.
for i in range (10):
print('hello world', '\n')
Or more conveniently, you can get rid of the end = " ", and Python will automatically add a new line.

You are using end=" " in your print function.
Just leave it as print("$" + T) and print("$" + V) so it appends newline by default.

Related

No iteration in nested while statement

How the loop should iterate. I'm a beginner trying to create a Python program to print a word backwards based on old knowledge from a few years ago. It does a few other things but they are just printed statements are don't pose a problem. Here is my code:
count = 0
while count < 100:
word_var = input("Enter ONE word with NO spaces:")
def split(word_var):
return list(word_var)
word_array = split(word_var)
m = 0
i = len(word_array)-1-m
print("The number of letters in your word is:", i)
while m < len(word_array):
if m < i:
word_array[m], word_array[i - m] = word_array[i - m], word_array[m]
m = m + 1
else:
break
m = m + 1
print(''.join(word_array))
count = count + 1
print("You've typed:",count,"word(s).")
Here is the problem section:
if m < i:
word_array[m], word_array[i - m] = word_array[i - m], word_array[m]
m = m + 1
else:
break
m = m + 1
My main problem is that it seems like the second while loop is not iterating when the word is more than five letters long. For example, if I input the word "should" into the program I get back out dhouls. It seems as if only one interchange of letters is being performed. I figure this is a problem with the if statement in that nested while loop, but I can't seem to find what is wrong with it. I carefully sketched out how I think the if statement works in the photo attached.
Your if condition is wrong. You want to compare the two indices that you will use in the list, but the second one is not i, but i-m. So change it to:
if m < i - m:
This corrects your issue. It should be noted that in Python you can reverse string just like this:
print(word_var[::-1])
There are two issues:
The counting of the letters isn't correct. You should just output the length of word_array.
You're iterating the while loop too many times. You should terminate it when m equals or exceeds len(word_array) // 2. Otherwise, you'll unreverse the letters and get the original word back.
i = len(word_array)-1
print("The number of letters in your word is:", len(word_array))
while m < len(word_array) // 2:
word_array[m], word_array[i - m] = word_array[i - m], word_array[m]
m = m + 1
This outputs:
Enter ONE word with NO spaces:should
The number of letters in your word is: 6
dluohs
You've typed: 1 word(s).
I like your project and appreciate your efforts.
This a another way to reverse a string using a list variable and the insert() method.
word_array = []
word_var = input('Your word : ')
word_array = []
for c in word_var:
word_array.insert(0, c)
word_reversed = ''.join(word_array)
print(word_var, '->', word_reversed)
output :
should -> dluohs

how to split the output of the Python code?

I have following code, which should print an output of k numbers around n number, and instead the n number the code should replace by *:
def numbers_around(n, k):
for cislo in range(n-k, n+k+1):
if cislo == n:
print("*", end=" ")
else:
print(cislo, end=" ")
numbers_around(8, 3)
numbers_around(10, 2)
The output should be:
5 6 7 * 9 10 11
8 9 * 11 12
But my output is all in one line:
5 6 7 * 9 10 11 8 9 * 11 12
You are using the parameter end = " " in the print function, which replaces the default end used by python which is starting new line; if you want to start new line after each printing, just add print() at the end.
the full function should be
def numbers_around(n, k):
for cislo in range(n-k, n+k+1):
if cislo == n:
print("*", end=" ")
else:
print(cislo, end=" ")
print()
Using end=" " tells the print function to output a space at the end, instead of the line break that it would normally output.
Therefore the output of the second function call starts on the same line as the output of the first function call ends.
You need to output an additional line break at the end of the numbers_around function.
To do that, just add an empty print() after the for loop:
def numbers_around(n, k):
for ...:
# ...
print()
The problem is that you're telling print() to put a space at the end instead of the newline character '\n' it normally uses. You could fix this by just adding another call to print() at the end, but actually, if you redesign the function a little bit, you can make it a lot simpler. By using the splat operator, you can print everything at once.
Option 1: Use a generator expression or list comprehension instead of a for-loop.
def numbers_around(n, k):
r = range(n-k, n+k+1)
out = ('*' if i==n else i for i in r)
print(*out)
Option 2: Instead of replacing n, get the two ranges around n and put a '*' in the middle.
def numbers_around(n, k):
r1 = range(n-k, n)
r2 = range(n+1, n+k+1)
print(*r1, '*', *r2)

Print dynamically in just one line

Been trying to improve my Fibonacci script. Made a few changes regarding actually how it visually looks (has like a minimalist "menu") and some other stuff to avoid it breaking, like not allowing text to be given as input to the amount of numbers it should generate. One of the things I wanted to change was the output to show all in just one line, but kinda been having a hard time doing so.
My code:
count = int(input("How many numbers do you want to generate?"))
a = 0
b = 0
c = 1
i = 0
while i < count:
print(str(c))
a = b
b = c
c = a + b
i = i+1
What I also tried:
Instead of
print(str(c)) I've tried, without any luck:
print("\033[K", str(c), "\r", )
sys.stdout.flush()
Desired output:
1, 1, 2, 3 ,5
Output:
1
1
2
3
5
Use the end parameter of the print function, specifically in your example:
while i < count:
print(c, end=", ")
...
To prevent the trailing comma after the last print:
while i < count:
print(c, end=("" if i == count - 1 else ", "))
...
You can specifiy the ending of print:
print(*[1,2,3], end=", ")
The default ending is a new line
You can also specifiy a different separator with sep=", "

Print out the items which went through For loop? python 2.7

I am new in python. I have a for loop inside which I have if ...: condition.
I want to print out the (list) of items which went through the for loop.
Ideally, items should be separated by spaces or by commas. This is a simple example, intended to use with arcpy to print out the processed shapefiles.
Dummy example:
for x in range(0,5):
if x < 3:
print "We're on time " + str(x)
What I tried without success inside and outside of if and for loop:
print "Executed " + str(x)
Expected to get back (but not in list format), maybe through something like arcpy.GetMessages() ?
Executed 0 1 2
phrase = "We're on time "
# create a list of character digits (look into list comprehensions and generators)
nums = [str(x) for x in range(0, 5) if x < 3]
# " ".join() creates a string with the elements of a given list of strings with space in between
# the + concatenates the two strings
print(phrase + " ".join(nums))
Note. A reason for the downvotes could help us new users understand how things should be.
Record your x's in a list and print out this list in the end:
x_list = []
for x in range(0,5):
if x < 3:
x_list.append(x)
print "We're on time " + str(x)
print "Executed " + str(x_list)
If you use Python3 you could just do something like this..
print("Executed ", end='')
for x in range(0,5):
if x < 3:
print(str(x), end=' ')
print()

Join two for loops, separated by a print statement into one

In the following code, everything is working as expected.
It gets a 4 character long user input that ends with 0.
And simply adds stores in a dictonary the occurances of vowels and consonants.
input ="" #get input from user
while 4 < len(input) or 4 > len(input) or input[-1] != "0": #string has to be 4 char long and end in 0
input = raw_input("insert code:")
occurrences = {"a":0,"e":0,"i":0,"o":0,"u":0,"consonants":0} #store the vouel count
for x in input:
if x in occurrences.keys():
occurrences[x] += 1 #count cowels
elif x != "0":
occurrences["consonants"] += 1 #count consonants
for x in occurrences:
if occurrences[x] > 0 and x != "consonants":
print x + ",",
print "were inserted",
for x in occurrences:
if occurrences[x] > 0 and x != "consonants":
print str(occurrences[x]) + ",",
print "times respectively"
if occurrences["consonants"] == 1:
print "there was %d consonant"%occurrences["consonants"]
else:
print "there was %d consonants"%occurrences["consonants"]
For the input "aef0" the program will print:
e, a, were inserted 1, 1, times
respectively there was 1 consonant
My questions is about this particular lines.
I know there must be a better way to do:
for x in ocurrances:
if ocurrances[x] > 0 and x != "consonants":
print x + ",",
print "were inserted",
for x in ocurrances:
if ocurrances[x] > 0 and x != "consonants":
print str(ocurrances[x]) + ",",
print "times respectively"
It just feels sloppy.
What I don't like about it is that I'm calling twice the same for loop and I feel this could be only one move in a much more elegant way, but I'm not finding the way to do so.
A pseudo code (or whatever) of what I'm trying to achieve would be the following.
loop the dictionary
print all key with values >= 1
print "were inserted" only once
print all the respective vales.
print "times respectively"
As I said I want the same output, but expressed in a more elegant way, I'm assuming the elegant would imply only one for loop but any other (more elegant) options are welcome!
I thought about doing something like this, but it's obviously not working. (Don't worry about it, it's just plain wrong, but the approach shows what I was aiming for)
Thanks in advance!
Another way to write your code might be something like this:
print ", ".join(k for k, v in occurrences.items() if k != "consonants" and v > 0),
print "were inserted"
print ", ".join(str(v) for k, v in occurrences.items() if k != "consonants" and v > 0),
print "times respectively"
You can shorten this a bit more by factoring out the search:
a = [(k, str(v)) for k, v in occurrences.items() if k != "consonants" and v > 0]
print ", ".join(x[0] for x in a), "were inserted",
print ", ".join(x[1] for x in a), "times respectively"
You have a few more problems with elegance and other things that matter more. For a start your users would revolt against having to type a 0 that you don't do anything meaningful with. In fact you need to dedicate code to ignoring it! Keeping the count of consonants in the dict is rather inelegant. You don't check whether the user typed all letters. You don't handle uppercase.
Here's some code that addresses those issues plus a few verbosities:
input = "" # get input from user
while len(input) != 3 or not input.isalpha():
input = raw_input("insert code:").lower()
ocurrances = {"a":0, "e":0, "i":0, "o":0, "u":0}
nconsonants = 0
for x in input:
if x in ocurrances:
ocurrances[x] += 1 #count vowels
else:
nconsonants += 1 #count consonants
for x in ocurrances:
if ocurrances[x]:
print x + ",",
print "were inserted",
for x in ocurrances:
if ocurrances[x]:
print str(ocurrances[x]) + ",",
print "times respectively"
if nconsonants == 1:
print "there was 1 consonant"
else:
print "there were %d consonants" % nconsonants
and you might like to change "ocurrances" to "occurrences". By the way, if the number of vowels is less than 2, the output is not very pretty.

Categories