How to properly use the print function - python

while index < len(diecount):
print(index)
for number in range(diecount[index]):
print('*')
index+=1
print("")
At the moment i am getting
1
**
2
3
**
i want the output to be
1 **
2
3 **

A more Pythonic way to write this:
for index, count in enumerate(diecount[1:], start=1):
print(index, '*' * count)
(Manually controlling loop indexes in a while is usually a sign you're trying to write C code in Python).

Each print function appends a newline at the end of whatever it currently prints.
You can append a space instead of newline after the first print using the 2nd argument:
print(index, end = " ")

Related

Increasing understanding of printing multiple variables [duplicate]

for example in this code below the with the end the integers stay on the same line but without the it does not.
num = 5
for i in range(1, num +1):
for j in range(num, i-1, -1):
print(j, end="")
print()
The end statement for printing in Python allows the programmer to define a custom ending character for each print call other than the default \n
For instance, if you have a function that is to print all values within a list on the same line, you do:
def value(l):
for items in l:
print(l, end=' ')
So if the list argued to this function contains the values [1, 2, 3, 4], it will print them in this manner: 1 2 3 4. If this new ending character parameter was not defined they would be printed:
1
2
3
4
The same principle applies for ANY value you provide for the end option.
In Python 3, the default ist end='\n' for the print function which is a newline after the string is printed.
To suppress this newline, one can set end='' so that the next print starts in the same line.
This is unrelated to the for loop.

Printing strings one letter at a time and adding onto them

I am new to Python 3 and programming in general. I am not sure how to word my question so I'll just give an example.
So the user inputs a string such as "home". The program should output:
h
ho
hom
home
This is what I have so far (I was just trying to get the numbering to work, but I thought I would add it just in case):
loopUpdate = 2
for i in range(1, len(mystery_string) + 1):
for x in range(1, loopUpdate):
print(x, end="")
loopUpdate += 1
print()
This is unnecessarily complicated. You don't have to have two loops to print out characters at each index in a loop. You should use string slicing instead:
>>> "home"[0:2]
'ho'
>>> "home"[0:3]
'hom'
A function that does this would look something like this:
def print_loop(word):
for i in range(1, len(word) + 1):
print(word[0:i])
Output:
>>> print_loop("word")
w
wo
wor
word

Counting the number of occurrences of a specific value in a text file

I have text file with 30 columns. and using python I want to count the number of rows based on the value in column 3. in fact how many times "cement" occurs in column 3. also columns do not have name (or header).
count = 0
with open('first_basic.txt') as infile:
for line in infile:
for j in (line.split()[3]):
if j == "cement":
count += 1
thanks
You are checking each character of 3rd column (word) of every line, to check if it equals cement:
'c' == 'cement' => False
'e' == 'cement' => False
etc.
You should replace
for j in (line.split()[2]):
if j == "cement":
count += 1
with
if line.split()[2] == "cement":
count += 1
Full code:
count = 0
with open('first_basic.txt') as infile:
for line in infile:
if line.split()[2] == "cement":
count += 1
print count
Arrays has the start position as 0 not as 1. So if you want to get the third element of ['DUMMY', 'DUMMY', 'CEMENT', 'NOT_CEMENT'] yoy have to take the [2] position. Because the [3] position is 'NOT_CEMENT'.
And the seccond for, is taking letter by letter, not row by row. The row you took in line.
So to fix your code change:
if line.split()[2] == "cement": #Change here for two
count += 1
But you can take a clean solution for that doing somthing like this:
with open('first_basic.txt') as infile:
map(lambda x: x.split()[2], infile).count('cement')
Let's explain the code.
The map() is responsible to do much like the same as for. It will iterates in all elements of an iterable object. And for each element it apply a function.
The function that was used is this:
lambda x: x.split()[2]
This is a functional way to do this:
def function(x):
return x.split()[2]
But why I used lambda? There is a simple answer, I will not call this function anymore. So I don't need to use space in my memory to this function so I used lambda AKA anonymous function in Python.
You can check about map function here and lambda functions here.
I hope that I helped.
Say you define a predicate function for your matches:
def match(line):
return line.split()[2] == 'cement'
You can use this predicate with a filter and calculate the count of matching lines:
with open('first_basic.txt') as infile:
print(len(list(filter(match, infile.readlines()))))
But this requires memory to build the list first. Using a generator may be faster and does not require the memory for the list:
print(sum(1 for line in infile if match(line))

Adding Loop in the File Command Python

ı wanna create a file which as :
X values:
1
2
3
4
5
.
.
.
999
to do that ı wrote that command but ;
error like :argument 1 must be string or read-only character buffer, not float,,
from numpy import *
c = open("text.txt","w")
count = 0
while (count < 100):
print count
count = count + 0.1
c.write (count)
c.close
When writing to a file, you must write strings but you are trying to write a floating point value. Use str() to turn those into strings for writing:
c.write(str(count))
Note that your c.close line does nothing, really. It refers to the .close() method on the file object but does not actually invoke it. Neither would you want to close the file during the loop. Instead, use the file as a context manager to close it automatically when you are d one. You also need to include newlines, explicitly, writing to a file does not include those like a print statement would:
with open("text.txt","w") as c:
count = 0
while count < 100:
print count
count += 0.1
c.write(str(count) + '\n')
Note that you are incrementing the counter by 0.1, not 1, so you are creating 10 times more entries than your question seems to suggest you want. If you really wanted to only write integers between 1 and 999, you may as well use a xrange() loop:
with open("text.txt","w") as c:
for count in xrange(1, 1000):
print count
c.write(str(count) + '\n')
also, you're closing your file on each iteration of the while loop, so this will write your first line and then crash.
Unindent your last line so that the file's only closed after everything's been written to it:
while (count < 100):
print count
count = count + 0.1
c.write(str(count))
c.close()
Multiple problems which I can see are :
1. You can only write character buffer to file. The solution to main question u asked.
c.write (count) should be c.write (str(count))
2. You need to close your file outside the loop. You need to unindent c.close
from numpy import *
c = open("text.txt","w")
count = 0
while (count < 100):
print count
count = count + 0.1
c.write (count)
c.close()
3. Even after these this code will print and save numbers incremented with 0.1 i.e 0.1,0.2,0.3....98.8,99.9 You can use xrange to solve your problem.
result='\n'.join([str(k) for k in xrange(1,1000)])
print result
c = open("text.txt","w")
c.write(result)
c.close()

How to print spaces between values in loop?

How to put spaces between values in a print() statement
for example:
for i in range(5):
print(i, sep='', end='')
prints
012345
I would like it to print
0 1 2 3 4 5
While others have given an answer, a good option here is to avoid using a loop and multiple print statements at all, and simply use the * operator to unpack your iterable into the arguments for print:
>>> print(*range(5))
0 1 2 3 4
As print() adds spaces between arguments automatically, this makes for a really concise and readable way to do this, without a loop.
>>> for i in range(5):
... print(i, end=' ')
...
0 1 2 3 4
Explanation: the sep parameter only affects the seperation of multiple values in one print statement. But here, you have multiple print statements with one value each, so you have to specify end to be a space (per default it's newline).
Just add the space between quotes after the end. It should be:
end = " "
In Python 2.x, you could also do
for i in range(5):
print i,
or
print " ".join(["%s"%i for i in range(5)])

Categories