What does '+ +' mean in python? - python

I'm reading a python book. It's explaining for loops and range() function.
But I don't understand what does '+ and +' mean.
for i in range(7):
print('hello('+str(i)+')')

Actually it should read as:
string_a + string_b + string_c
It is not about "+ xxx +".
It literally concatenate string_a, string_b and string_c together albeit it is not pythonic.
A more pythonic way may be:
print( "hello({my_var})".format(my_var=i) )

Related

simpler way of checking multiple conditions in if statements python

if char != ' ' and char != '\n'
is there a simpler / shorter way of doing this, like something like this:
if char != (' ' and '\n')
but this doesn't work apparently
This is briefer
if not char in ' \n':
if not char in 'abcd':
You can build a list(for higher speed, use set instead) of strings to check, something like
if char not in [' ', '\n']:
Since the example you gave are all 1 in length, you can replace the list with a longer string of those minor strings
" \n"

How to make last element of list finish with a dot and the others with a comma?

I made this list with a for loop that points errors when yoy choose a name. I'd like to know how can I make it so that the last line finishes with '.' and the others finish with ';'.
while True:
if len(errors_list) != 0:
print("Your name has thesse errors::")
for i in errors_list:
print(" " + str(errors_list.index(i) + 1) + "- " + i + ".")
print("Try again.")
errors_list.clear()
name = input("My name is ").title()
choose_name(name)
else:
print("Nice to meet you, " + fname + " " + sname + ".")
break
Result when I type a name like '--- ':
Your name has these errors:
1- It has no letters.
2- It has symbols.
3- The last letter is a space.
Try again.
My name is
I'd like to make it so that 1 and 2 finish with ';' and 3 with '.'. Thanks!
All the existing solutions so far seem pretty poor, this is as print is expensive to call.
errors_list.index(i) runs in O(n) time making your solution run in O(n^2) time. You can improve this, to O(n) time, by using enumerate.
You can also think of what you're doing simply as concatenating values of a list and adding a period.
I would use:
errors = [f' {i}- {error}' for i, error in enumerate(errors_list, 1)]
print(';\n'.join(errors) + '.')
Extending Roman Perekhrest's answer, enumerate has an optional parameter start:
errors_list = ['It has no letters', 'It has symbols', 'The last letter is a space']
for i, err in enumerate(errors_list, start=1):
print("\t{}- {}{}".format(i, err, ';' if i < len(errors_list) else '.'))
additionaly with Python 3.6+ you can use f-strings instead of format:
errors_list = ['It has no letters', 'It has symbols', 'The last letter is a space']
for i, err in enumerate(errors_list, start=1):
print(f"\t{i}- {err}{';' if i < len(errors_list) else '.'}")
Instead of:
for i in errors_list:
print(" " + str(errors_list.index(i) + 1) + "- " + i + ".")
do
s = len(errors_list)
for e, i in enumerate(errors_list):
ending = ";" if e + 1 < s else "."
print(" " + str(errors_list.index(i) + 1) + "- " + i + ending)
EDIT:
to those jumping to the gun - OP did write in a title comma, but he used semicolon (;) twice (!) in a question itself.
Simply with enumerate function:
errors_list = ['It has no letters', 'It has symbols', 'The last letter is a space']
...
for i, err in enumerate(errors_list):
print(" {}- {}{}".format(i+1, err, ';' if i+1 != len(errors_list) else '.'))
The crucial loop will output:
1- It has no letters;
2- It has symbols;
3- The last letter is a space.

Add period to python statement without a space

I am only three weeks into my Intro to Programming course, so bear with me!
I am writing a code as follows:
number1 = input('Enter the first number: ')
number1 = int(number1)
number2 = input('Enter the second number: ')
number2 = int(number2)
number3 = input('Enter the third number: ')
number3 = int(number3)
ratio12 = int(number1 / number2)
ratio13 = int(number1 / number3)
ratio23 = int(number2 / number3)
print('The ratio of', + number1, '+', + number2,'is', + ratio12, '.')
print('The ratio of', + number1, '+', + number3,'is', + ratio13, '.')
print('The ratio of', + number2, '+', + number3,'is', + ratio23, '.')
The code is functional (finally), but I can't seem to get rid of the space before the period on the print statements. Is there a way that I can do that?
The reason why this happens is because you are using commas in your print statements. In python there are a few ways to give the print statement multiple variables, you seem to be mixing two of them together. The ways are as follows.
Concatenate the string.
print('The ratio of ' + str(number1) + ' + ' + str(number2) + ' is ' + str(ration12) + '.')
This way is probably the most basic way. It will join the strings without adding any characters in between them (e.g. no spaces in between unless you add them explicitly.) Also note, that string concatenation won't automatically cast the integers to a string for you.
Pass print multiple arguments.
print('The ratio of', number1, '+', number2, 'is', ration12, '.')
This will automatically add spaces between each argument and is what is happening in your case. The separator (which defaults to a space) can be changed by passing a keyword argument to the print function. For example, print('i = ', i, sep='')
Use string formatting.
print('The ratio of {} + {} is {}.'.format(number1, number2, ratio12))
This way is the most readable and often the best way. It will replace the '{}' sections in you 'template' string with the arguments based into the format function. It does this in order, however you can add an index like this '{0}' to explicitly use an argument by index.
Some string formating makes your live easier:
number1 = 1
number2 = 2
ratio12 = number1 / number2
print('The ratio of {} + {} is {}.'.format(number1, number2, ratio12))
Output:
The ratio of 1 + 2 is 0.5.
You can control the "separator" using the sep argument to print:
print('The ratio of', + number1, '+', + number2,'is', + ratio12, '.', sep='')
Note that this will change the spacing between the other items as well.
Also -- You don't need the extra + operators in there. Here's a version without the spaces and with explicit spaces added where I think you want them:
print('The ratio of ', number1, ' + ', number2, ' is ', ratio12, '.', sep='')
You're confused about the concatenation function and print fields. If you're going to concatenate all those strings, just use concatenation. The comma includes the default separator.
print('The ratio of', number1, '+', number2,'is', str(ratio12) + '.')
Try to write to it this way:
print('The ratio of %d + %d is %d.' %(number1, number2, ratio12))
print('The ratio of %d + %d is %d.' %(number1, number3, ratio13))
print('The ratio of %d + %d is %d.' %(number2, number3, ratio23))
That's the way print works when you give it multiple comma separated arguments. The logic behind that is that when you quickly want to print a bunch of variables, it's a pain to manually add widespace.
Well, one thing to try: Get rid of all the , in the print statement. You can just chain strings using the + sign.
So,
print('The ratio of ' + str(number1) + ' ' + str(number2) + ' is ' + str(ratio12) + '.')
If you need even greater control over formatting, you'd want to look into the format function.
print("The ratio of {} + {} is {}.".format(number1, number2, ratio12))

Python Printing and multiplying strings in Print statement

I am trying to write a simple python program that prints two ##, then # #, and increases the number of spaces in between the #'s each time. Here is the code I tried:
i=0
while (i<=5):
print ("#" (" " * i) "#")
#print (" " * i)
#print ("#" "#")
The multiplication works in the first line of code I tested then commended out, I see it in the shell each time it prints one more space.
Printing two #'s works also.
I can't figure out how to combine it into one statement that works, or any other method of doing this.
Any help would be appreciated, thanks.
i=0
while (i<=5):
print( "#" +(" "*i)+ "#")
i=i+1
You need to add the strings inside the print statement and increment i.
You want to print a string that depends an a variable. There are other methods to build a string but the simplest, most obvious one is adding together some fixed pieces and some computed pieces, in your case a "#", a sequence of spaces and another "#". To add together the pieces you have to use the + operator, like in "#"+" "+"#".
Another problem in your code is the while loop, if you don't increment the variable i its value will be always 0 and the loop will be executed forever!
Eventually you will learn that the idiom to iterate over a sequence of integers, from 0 to n-1 is for i in range(n): ..., but for now the while loop is good enough.
This should do it:
i=0
while (i<=5):
print ('#' + i * ' ' + '#')
i = i + 1
Try this:
def test(self, number: int):
for i in range (number)):
print('#' +i * ''+ '#')
i+=1
return

Annoying spaces that won't disappear. What should I do?

I am currently making a game with Python.
I want the code to read:
[00:00:00] Name|Hello!
Here is my code:
print(Fore.YELLOW + Style.BRIGHT + '['),
print strftime("%H:%M:%S"),
print ']',
print(Style.BRIGHT + Fore.RED + ' Name'),
print(Fore.BLACK + '|'),
print(Fore.WHITE + Style.DIM + 'Hello!')
time.sleep(5)
Instead - for some reason - it becomes like this:
[ 00:00:00 ] Name | Hello!
I have no idea what's wrong with this code, or how to fix it.
I would really appreciate all the help I can get! Thank you.
Printing with a single print statement and a comma always prints a trailing space.
Either use one print statement with everything concatenated, or use sys.stdout.write() to write to the terminal directly without the extra spaces:
print Fore.YELLOW + Style.BRIGHT + '[' + strftime("%H:%M:%S") + ']',
or
sys.stdout.write(Fore.YELLOW + Style.BRIGHT + '[')
sys.stdout.write(strftime("%H:%M:%S"))
sys.stdout.write(']')
or use string formatting:
print '{Fore.YELLOW}{Style.BRIGHT}[{time}] {Style.BRIGHT}{Fore.RED} Name {Fore.BLACK}| {Fore.WHITE}{Style.DIM}Hello!'.format(
Style=Style, Fore=Fore, time=strftime("%H:%M:%S"))
Another option is to use the end="" option to print(). This prints no linefeed and also does not add the extra space at the end.
print(Style.BRIGHT + Fore.RED + ' Name', end="")
print(Fore.BLACK + '|', end="")
print(Fore.WHITE + Style.DIM + 'Hello!')
The caveat being that the end option is only available with Python 3. It's also available in Python 2.6-ish if you from __future__ import print_function

Categories