i want this result.
---input---
"""
* name
- jon
* age
- 20
* hobby
- walk
"""
--- output ---
* name
- jon
* age
- 20
* hobby
- walk
----------------
I want to print as it is entered
Here is the code I wrote.
val = ""
vals = []
while True:
val = input()
if val == 'q':
break
else:
vals.append(val)
print(vals)
result
['* name', ' - jon', '* age', ' - 20', '* hobby', ' - walk']
help me!!!!
A number of ways to do this.
Print each item in a for loop.
for val in vals:
print(val)
Join the list items into a string, each item separated by newlines, then print that.
print("\n".join(vals))
Treat the items of the list as separate arguments to print() and use a newline as a separator.
print(*vals, sep="\n")
I like #3 because it`s short and it doesn't create a temporary string containing all the items like #2.
Related
error message screenshotI'm quite new to Python and I need to create a nested loop for excel parsing. I have a spreadsheet with 4 columns ID, Model, Part Number, Part Description, Year and I need a parser to go through each line and to return in format:
Part Number, Toyota > Model > Year | Toyota > Model > Year etc...
so that part number is returned only once listing all of the multiple fitting models and years.
I was able to achieve the same through the code below but it is not switching to the second part Part Number
import pandas as pd
import xlrd
workbook = pd.read_excel('Query1.xls')
workbook.head()
i = 0
l = int(len(workbook))
a = workbook['Part Number'].iloc[i]
while i < l:
b = 0
c = workbook['Part Number'].iloc[b]
print(a)
while c == a:
#print(c)
print(b, 'TOYOTA >', workbook['Model'].iloc[b], ' > ', workbook['Year'].iloc[b], ' | ', end = ' ')
b = b + 1
print()
i = i + b
Your code gets stuck in an infinite loop, because you do not update the value c as you iterate through the rows. Here's how you could implement this better:
part_number_group = None
for i in range(len(df)): # or `for i, row in df.iterrows():`
part_number = df.loc[i, "Part Number"]
if part_number != part_number_group:
if part_number_group is not None:
print()
print(part_number)
part_number_group = part_number
print(i, 'TOYOTA >', df.loc[i, 'Model'], ' > ', df.loc[i, 'Year'], ' | ', end = ' ')
But instead, you should use groupby, which saves the need to iterate through rows at all:
df["Model-Year"] = df.index.astype(str) + " TOYOTA > " + df["Model"] + " > " + df["Year"].astype(str)
for part_number, group in df.groupby("Part Number"):
print(part_number)
print(*group["Model-Year"], sep=" | ")
Trying to reuse some of your code, you may go over all unique part numbers using a for loop. For loops make it easier to no get stuck in an infinite loop because you specify the start and stop conditions upfront. Then you can query all entries with that same part number and print them with your suggested print function:
import pandas as pd
import xlrd
workbook = pd.read_excel('Query1.xls')
for num in pd.unique(workbook["Part Number"]):
print('\n', num)
part_df = workbook.query("`Part Number` == #num")
for i in range(len(part_df)):
print(i, 'TOYOTA >', part_df['Model'].iloc[i], ' > ', part_df['Year'].iloc[i], ' | ', end=' ')
What is the reason why I cannot access a specific line number in the already split string?
a = "ABCDEFGHIJKLJMNOPRSTCUFSC"
barcode = "2"
import textwrap
prazno = textwrap.fill(a,width=5)
podeli = prazno.splitlines()
Here the output is correct:
print(podeli)
ABCDE
FGHIJ
KLJMN
OPRST
CUFSC
However, when I want to split one of the lines e.g podeli[2] by 3 characters the python just ignores that and gives the same output like that split of podeli[2] (line 2) has not occured.
if barcode[0] == '1':
podeli[1] += ' MATA'
elif barcode[0] == '2':
podeli[1] += ' MATA'
for podeli[2] in podeli:
textwrap.fill(podeli[2], width=3)
podeli[2].splitlines()
podeli[2] += ' MATA'
The expected output would be:
ABCDE MATA
FGH MATA
IJ
KLJMN
OPRST
CUFSC
Is there a way to split the line by a certain length and its order number?
Thank you, guys!
You can solve your immediate problem by rebuilding the list, but I fear you have a more general problem that you haven't told us.
if barcode[0] == '1':
podeli[1] += ' MATA'
elif barcode[0] == '2':
podeli[1] += ' MATA'
line2 = textwrap.fill(podeli[2], width=3).splitlines()
podeli = podeli[0:2] + line2 + podeli[3:]
podeli[2] += ' MATA'
Try this, it should split a string you specified by a width of 3:
n = 3
[((podeli[2])[i:i+n]) for i in range(0, len(podeli[2]), n)]
I'm looking for a code that runs, i.e:
int(input) = 2565
Printed Output should be like:
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
I wrote the code that gives final answer "9". But I couldn't managed to write it with every digit separated "+" sign. Assuming that I need to use while loop but how can I write the code so it will be like the output above?
You can use something like this:
def sum_of_digits(s):
if s < 10:
return s
return sum_of_digits(sum(int(c) for c in str(s)))
> sum_of_digits(2565)
9
It recursively checks if the numerical value is less than 10. If it does, it returns this value. If not, it adds the digits, then recursively calls itself on the result.
Edit
To print out the steps as it goes along, you could do something like this:
def sum_of_digits(s):
if s < 10:
print(s)
return s
print(' + '.join(c for c in str(s)) + ' = ')
return sum_of_digits(sum(int(c) for c in str(s)))
First, initiate an empty string output_str.
With a while loop which contniues when our integer is > 9:
[s for s in str(x)] would create a list of the digits (as strings) of our integer. It's called a list comprehension, is very useful, and my advice is to read a bit about it.
With " + ".join() we create a string with " + " between the
digits. Add this string at the end of output_str.
Add " = " to the end of output_str.
Calculate the sum of the digits (we cannot use sum(lst_of_digits) because it's a list of strings. sum([int(s) for s in lst_of_digits]) converts the string list into an inter list, which can be summed using sum()). Store the sum into x.
Add the new x + " = " to output_string.
At the end of the string, we have a redundant " = " (because the last (5) was not needed), let's just remove the last 3 chars (=) from it.
x = 2565
output_str = ""
while x > 9:
lst_of_digits = [s for s in str(x)]
output_str += " + ".join(lst_of_digits)
output_str += " = "
x = sum([int(s) for s in lst_of_digits])
output_str += f"{x} = "
output_str = output_str[:-3]
outputs:
output_str = '2 + 5 + 6 + 5 = 18 = 1 + 8 = 9'
You can play around with the end keyword argument of the print function which is the last character/string that print will put after all of its arguments are, well, printed, by default is "\n" but it can be change to your desire.
And the .join method from string which put the given string between the given list/iterable of strings to get the desire result:
>>> " + ".join("123")
'1 + 2 + 3'
>>>
Mixing it all together:
def sum_digit(n):
s = sum(map(int,str(n)))
print(" + ".join(str(n)),"=",s, end="")
if s<10:
print()
return s
else:
print(" = ",end="")
return sum_digit(s)
Here we first get the sum of the digit on s, and print it as desire, with end="" print will not go to the next line which is necessary for the recursive step, then we check if done, and in that case print a new empty line if not we print an additional = to tie it for the next recursive step
>>> sum_digit(2565)
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
9
>>>
This can be easily be modify to just return the accumulated string by adding an extra argument or to be iterative but I leave those as exercise for the reader :)
I am a noob but this should do what you want.
Cheers,
Guglielmo
import math
import sys
def sumdigits(number):
digits = []
for i in range( int(math.log10(number)) + 1):
digits.append(int(number%10))
number = number/10
digits.reverse()
string = ''
thesum = 0
for i,x in enumerate(digits):
string += str(x)
thesum += x
if i != len(digits)-1: string += ' + '
else: string += ' = '
if thesum > 10:
return string,thesum,int(math.log10(number))+1
else:
return string,thesum,0
def main():
number = float(sys.argv[1])
finalstring = ''
string,thesum,order = sumdigits(number)
finalstring += string
finalstring += str(thesum)
while order > 0:
finalstring += ' = '
string,thesum,order = sumdigits(thesum)
finalstring += string
finalstring += str(thesum)
print 'myinput = ',int(number)
print 'Output = ',finalstring
if __name__ == "__main__":
main()
For homework I have been set the following:
Build a dictionary with the names from myEmployees list as
keys and assign each employee a salary of 10 000 (as value). Loop over the dictionary
and increase the salary of employees which names have more than four
letters with 1000 * length of their name. Print the dictionary contents before
and after the increase.
I can't figure out how to do it.
This is what I've come up with so far.
employeeDict = {"John":'10,000', "Daren":"10,000", "Graham":"10,000", "Steve":"10,000", "Adren":"10,000"}
say = 'Before increase'
print say
print employeeDict
say1 = 'After increase'
print say1
for x in employeeDict:
x = len(employeeDict)
if x > 5:
print employeeDict[x]
First, change the values to integers/floats.
employeeDict = {"John":10000, "Daren":10000, "Graham":10000, "Steve":10000, "Adren":10000}
After doing this, as you know, you need to loop over the items in the dict.
for x in employeeDict:
x = len(employeeDict)
if x > 5:
print employeeDict[x]
In the code above, your "x" will be the employee name. And as you know, to asign a value to a key in dict, you have to use dict[key] = value, so try to do it in the if x > 5: block statement. Im not trying to give you the full answer, but to push you in to the right direction.
You have some indentation problems, clearly, but the main problems are that you are taking the length of the dictionary (getting the number of keys) not taking the length of the key. You also have some bad logic.
employeeDict = {"John":'10,000', "Daren":"10,000", "Graham":"10,000", "Steve":"10,000", "Adren":"10,000"}
say = 'Before increase'
print say
print employeeDict
say1 = 'After increase'
print say1
for x in employeeDict:
length = len(employeeDict) # <---- indent this
if length >= 5: # <--- greater than 4
# convert string to number, add money, convert back to string
employeeDict[x] = str(int(employeeDict[x]) + 1000 * (length))
print employeeDict[x]
This should give you what your looking for.
employeeDict = {"John":10000, "Daren":10000, "Graham":10000, "Steve":10000, "Adren":10000}
print "Before increase"
print employeeDict
for name, salary in employeeDict.items():
if len(name) > 4:
employeeDict[name] = salary + len(name) * 1000
print "After increase"
print employeeDict
You had a few problems in your version.
Your idention for your for-loop was not correct
You were getting the length of the dictionary and not the length of the keys in the dictionary.
You should make the values in your dictionary floats/integers.
Also note, I believe your homework said if the name was longer than four characters. So i used 4 instead of five.
Give this a try and analyse it :
employees = {"John":10000, "Daren":10000, "Graham":10000}
for name in employees:
if len(name) > 5:
employees[name] += 1000 * len(name)
If you have to stick with the string values you can do this :
employees = {"John":"10000", "Daren":"10000", "Graham":"10000"}
for name in employees:
if len(name) > 5:
employees[name] = str(int(employees[name]) + 1000 * len(name))
For example, if I entered I love dogs, it would need to look like this:
I l o v e d o g s
This code does not do what I need it to do:
def spaceitout(source):
pile = ""
for letter in source:
pile = pile+letter
print pile
print pile
Simple answer would be:
def spaceitout(source):
pile = ""
for letter in source:
pile = pile + letter + " "
pile = pile[:-1] #Strip last extraneous space.
print pile
def evenly_spaced(string_,space_= 1):
import re
return (' '*space_).join([c for c in re.split(r'(\w)',string_) if c.isalpha()])
print(evenly_spaced(" This a long story ",2))
T h i s a l o n g s t o r y
Spaces between letters:
def spaceitout(source, count):
return (' '*count).join([letter for letter in source.replace(' ','')])
Spaces between words:
def spaceitout(source, count):
return (' '*count).join(source.split())
Spaces between all chars:
def spaceitout(source, count):
return (''.join([c + (' '*count) for c in source]).strip())
Allows you to specify spaces between words, and spaces between characters. Based on the answers provided by BigOldTree
def space_it(text, word_space=1, char_space=0):
return (' '*word_space).join([(' '*char_space).join(x) for x in text.split(' ')])
Note: This will treat two spaces in the input text as having an "invisible word" between them, change text.split(' ') to text.split() if this isn't desired.
Does this do what you need?
pile = ' '.join(source)
This takes the elements of "source" and joins them with a single space as the connector.
If you need only the letters separated, then build the list of letters only, and join that:
pile = ' '.join([c for c in source if c.isalpha()])
i think that this is what you was looking for:
line = 'I love dogs'
for i in line:
if i != ' ':
print i,
else:
print '',
using itertools:
import itertools
def space_word(word, spaces_count=1):
if spaces_count < 1:
raise ValueError("spaces_count < 1")
def space_word_wrapped(word, spaces_count):
letters = itertools.chain.from_iterable(zip(word, itertools.cycle(" ")))
skipped = 0 # have to keep track of how many letter skips
# or else from_word starts breaking!
# TODO : better implementation of this
for i, lett in enumerate(letters, start=1):
from_word = (i + skipped) % 2
if lett.isspace() and from_word:
if spaces_count == 1:
next(letters)
skipped += 1
continue # and skip the space itself
elif spaces_count == 2:
continue # just count the space
elif spaces_count == 3:
pass # count everything
else: # spaces_count >= 4
yield from [" "] * (spaces_count - 3)
yield lett
return ''.join(space_word_wrapped(word, spaces_count)).rstrip()
It's probably cheaper to just use an iterator here, but I like the generator in a nested function approach. So sue me! :)
This lists your word( 'his' = ['h','i','s'] and then joins it with a space instead of a comma.
def space(word):
return ' '.join(list(word))