I want to increment the variable inside the print statement, so it would not take 2 lines of code.
I have the following code:
yearCount += 1
print("Year ",yearCount,":",sep = "")
How can I do something like:
print("Year",yearCount+=1,":",sep = "")
For printing only, you can use f-strings, available in v3.6+:
print(f'Year {yearCount+1}:')
If you also need to increment the variable itself, I would stick with the two-liner; it's best to be clear and differentiate between calculations and printed output.
A not recommended answer to your question would be:
yearCount += 1; print(f'Year {yearCount}:')
Use format to format the string for printing and not actually incrementing the value
print("Year {}".format(yearCount+1))
You can go through official doc for print function Documentation.
a = 2
print("Sum is :", a+3)
output is :
Sum is :5
It is not possible to initialize variable(s) within print(). The best thing that you could do is call a function via f-string. Use that called function to increment the variable that you want.
yearCount = 2018
def yearInc():
global yearCount
yearCount+=1
return yearCount
print(f"Year {yearInc()}")
print(f'Year {yearCount}')
The output is:
Year 2019
Year 2019
This solution may be wasteful if you just to call this function once.
Related
Below is my work. I did the printline function before, and this question required to call the function printline above for printing each line. I try to print 3 lines, each line has 4 symbols, but I only can get 2 lines, each line comes with 12 symbols. Can someone help me correct my code?
def printline(num,sym):
for i in range(num):
a = (num*sym)
return a
a = printline(5,'*')
print(a)
def printrectangle(num,height,sym):
for i in range(height):
a = printline(num,sym)*height
print(a)
return a
c = printrectangle(3,4,'*')
print(c)
A few things here:
Your printline function works, but overcomplicates the problem.
In other programming languages, in order to repeat the same string multiple times it is common to create a loop of the form:
String s = "";
for(int i = 0; i < num; i++)
s += sym;
return s;
Since this is equivalent to just concatenating the same string num times, in python there is a simpler way to do this:
s = sym*num
Your solution works because you are overwriting the value in the variable a for num times before returning it.
You misinterpreted your testcase.
You said printrectangle(3, 4, '*') should print 3 lines with 4 symbols. But as you wrote it, the first variable num=3, and the second variable height=4.
The output here is in fact:
***
***
***
***
Your code does not currently do that, but let's not get ahead of ourselves.
Indentation error
The return statement in the printrectangle function is inside the loop. This means that during the first iteration of the loop, the function will return a value.
Easy fix, just backspace until the indentation of the return lines up with that of the loop.
Actually solving the problem.
From part 1, I introduced here that in python to concatenate the same string multiple times you may simply multiply the string by the number of times you want it to show up.
Here we want the string printline(num, sym) to show up height times with an enter key after each time.
The enter key sends the command of \n. In other words, a string such as 'a\nb' is printed as:
a
b
For our purposes, we can concatenate the string printline(num, sym) with \n first, and then multiply the resulting string by height to get the result of printrectangle(num, height, sym)
def printrectangle(num, height, sym):
a = (printline(num, sym)+'\n')*height
return a
Though this code will give you what you are looking for, I still doubt by mistake you swapped num and height values in the call printrectangle(3,4,'*') itself
def printline(h,sym):
a = h*sym # removed unnessary loop
return a
def printrectangle(num,height,sym):
for i in range(num): # swap height with num in your code
a = printline(height,sym) #swap num with height in your code
yield a
for row in printrectangle(3,4,'*'):
print(row)
I'm making a method that takes a string, and it outputs parts of the strings on separate line according to a window.
For example:
I want to output every 3 letters of my string on separate line.
Input : "Advantage"
Output:
Adv
ant
age
Input2: "23141515"
Output:
231
141
515
My code:
def print_method(input):
mywindow = 3
start_index = input[0]
if(start_index == input[len(input)-1]):
exit()
print(input[1:mywindow])
printmethod(input[mywindow:])
However I get a runtime error.... Can someone help?
I think this is what you're trying to get. Here's what I changed:
Renamed input to input_str. input is a keyword in Python, so it's not good to use for a variable name.
Added the missing _ in the recursive call to print_method
Print from 0:mywindow instead of 1:mywindow (which would skip the first character). When you start at 0, you can also just say :mywindow to get the same result.
Change the exit statement (was that sys.exit?) to be a return instead (probably what is wanted) and change the if condition to be to return once an empty string is given as the input. The last string printed might not be of length 3; if you want this, you could use instead if len(input_str) < 3: return
def print_method(input_str):
mywindow = 3
if not input_str: # or you could do if len(input_str) == 0
return
print(input_str[:mywindow])
print_method(input_str[mywindow:])
edit sry missed the title: if that is not a learning example for recursion you shouldn't use recursion cause it is less efficient and slices the list more often.
def chunked_print (string,window=3):
for i in range(0,len(string) // window + 1): print(string[i*window:(i+1)*window])
This will work if the window size doesn't divide the string length, but print an empty line if it does. You can modify that according to your needs
The code is supposed to take a 5 digit zip code input and convert it to bar codes as the output. The bar code for each digit is:
{1:'...!!',2:'..!.!',3:'..!!.',4:'.!..!',5:'.!.!.',6:'.!!..',7:'!...!',8:'!..!.',9:'!.!..',0:'!!...'}
For example, the zip code 95014 is supposed to produce:
!!.!.. .!.!. !!... ...!! .!..! ...!!!
There is an extra ! at the start and end, that is used to determine where the bar code starts and stops. Notice that at the end of the bar code is an extra ...!! which is an 1. This is the check digit and you get the check digit by:
Adding up all the digits in the zipcode to make the sum Z
Choosing the check digit C so that Z + C is a multiple of 10
For example, the zipcode 95014 has a sum of Z = 9 + 5 + 0 + 1 + 4 = 19, so the check digit C is 1 to make the total sum Z + C equal to 20, which is a multiple of 10.
def printDigit(digit):
digit_dict = {1:'...!!',2:'..!.!',3:'..!!.',4:'.!..!',5:'.!.!.',6:'.!!..',7:'!...!',8:'!..!.',9:'!.!..',0:'!!...'}
return digit_dict[digit]
def printBarCode(zip_code):
sum_digits=0
num=zip_code
while num!=0:
sum_digits+=(num%10)
num/=10
rem = 20-(sum_digits%20)
answer=[]
for i in str(zip_code):
answer.append(printDigit(int(i)))
final='!'+' '.join(answer)+'!'
return final
print printBarCode(95014)
The code I currently have produces an output of
!!.!.. .!.!. !!... ...!! .!..!!
for the zip code 95014 which is missing the check digit. Is there something missing in my code that is causing the code not to output the check digit? Also, what to include in my code to have it ask the user for the zip code input?
Your code computes rem based on the sum of the digits, but you never use it to add the check-digit bars to the output (answer and final). You need to add code to do that in order to get the right answer. I suspect you're also not computing rem correctly, since you're using %20 rather than %10.
I'd replace the last few lines of your function with:
rem = (10 - sum_digits) % 10 # correct computation for the check digit
answer=[]
for i in str(zip_code):
answer.append(printDigit(int(i)))
answer.append(printDigit(rem)) # add the check digit to the answer!
final='!'+' '.join(answer)+'!'
return final
Interesting problem. I noticed that you solved the problem as a C-style programmer. I'm guessing your background is in C/C++. I's like to offer a more Pythonic way:
def printBarCode(zip_code):
digit_dict = {1:'...!!',2:'..!.!',3:'..!!.',4:'.!..!',5:'.!.!.',
6:'.!!..',7:'!...!',8:'!..!.',9:'!.!..',0:'!!...'}
zip_code_list = [int(num) for num in str(zip_code)]
bar_code = ' '.join([digit_dict[num] for num in zip_code_list])
check_code = digit_dict[10 - sum(zip_code_list) % 10]
return '!{} {}!'.format(bar_code, check_code)
print printBarCode(95014)
I used list comprehension to work with each digit rather than to iterate. I could have used the map() function to make it more readable, but list comprehension is more Pythonic. Also, I used the Python 3.x format for string formatting. Here is the output:
!!.!.. .!.!. !!... ...!! .!..! ...!!!
>>>
I would first like to apologize for how much of a beginner I am, however I have hit this wall after many other hurdles. The basis of this is to retrieve a value from a website, modify it using variables and print the final value. My knowledge of classes and objects is very very minimal. I just cannot figure out how I can take the value numTotal from my function getPlays and use it later to print as Final. The value prints correctly from within the function I just need to store that value for later use as a variable.
class GetPlaycount(object):
def getPlays(self):
print "Working"
browser = webdriver.PhantomJS('C:\Python27\phantomjs-2.0.0-windows\phantomjs.exe')
browser.get('https://osu.ppy.sh/u/4973241')
time.sleep(1)
Plays = browser.find_element_by_xpath('//*[#id="general"]/div[8]').text
numPlays = int(re.sub('[^0-9]', '', Plays))
numTime = int(numPlays) * int(numLength)
numTotal = int(numTime) * float(numVar)
print int(numTotal)
return numTotal
myClassObject = GetPlaycount()
myClassObject.getPlays()
Final = ????
print Final
raw_input("wait")
Thank you for your help and patience.
If I understand the question correctly
final = myClassObject.getPlays()
print final
Should be all you need.
I'm doing an assignment in which I have to move a simulated robot across the screen in a loop - I've got that part down, however, between loops, I also have to print the percentage of area covered with each movement - that's my issue.
I googled a bit and even found someone with the same problem, however, I'm not sure if I'm doing it properly.
This code was offered:
percent_complete = 0
for i in range(5):
percent_complete += 20
print('{}% complete'.format(percent_complete))
However, after an error, further googling revealed that only worked with certain versions
so I used this code:
percent_complete = 0
for i in range(5):
percent_complete += 20
print '% complete' % (percent_complete)
And, at the very least, it now executes the code, however, the output when printing is the following:
Here we go!
hello
omplete
hello
(omplete
hello
<omplete
hello
Pomplete
hello
domplete
What is the cause of this? I assume because one of the codes had to be edited, the other parts do as well, but I'm not sure what needs to be done.
for i in range(5):
percent_complete += 20
print '%d complete' % (percent_complete)
You were missing the d specifier.
The first version only works in Python 3 because it uses print as a function. You're probably looking for the following:
percent_complete = 0
for i in xrange(5):
percent_complete += 20
print '{0} complete'.format(percent_complete)
Your other code doesn't do what you intend to do because it now display the number as a string. What you want is that the number is properly converted to a string first and then displayed in the string. The function format does that for you.
You can also use Ansari's approach which explicitly specifies that percent_complete is a number (with the d specifier).
To add to/correct above answers:
The reason your first example didn't work isn't because print isn't a function, but because you left out the argument specifier. Try print('{0}% complete'.format(percent_complete)). The 0 inside the brackets is the crucial factor there.