Two if statements on same line - python

Very new to this, and cant seem to get these two to print on the same line. Python 3
isCold= sys.argv[1] == 'True'
isRainy= sys.argv[2] == 'True'
if isCold:
print "cold and",
else:
print "warm and ",
if isRainy:
print('rainy')
else:
print('dry')
Keep getting:
cold and
rainy
I need:
cold and rainy

print has an end parameter whose default value is \n, a newline. Call the first prints with print("cold and", end="") and they won't skip to the next line.

on the end of each print statement there is a \n which means "enter" or "new line"
build your str with + signs and print the build-up string at the end.

Each call to print will result in the text being printed on its own line because a new line character is appended. This is mentioned in the documentation -
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
The default value for end is why you are seeing a new line after each call to print.
What you could do is build a string variable in your conditional statements and then only print once at the end -
output = ''
if isCold:
output += "cold and"
else:
output += "warm and "
if isRainy:
output += 'rainy'
else:
output += 'dry'
print output
In addition, I see you are assigning string values instead of boolean values. In python "True" is not the same as True. You should assign proper boolean values. Take the following example -
myBool = 'True'
if myBool:
print('Bool is truthy')
myBool = 'False'
if myBool:
print('Bool is STILL truthy')
myBool = False
if myBool:
print('This should not be printed')

The print() function in Python takes more than one argument. One of the arguments is the end.
Now usually, the print function has a default argument of end="\n", where \n is newline. This is the reason why your output comes as:
cold and
rainy - instead of:
cold and rainy
One solution to the many is to specify end. The end determines what the printed string will end with. For example:
>>> print("It is raining", end="!")
It is raining!
>>> print("What", end=",")
What,
So to get your output on the same line, you can try the following:
print("cold and", end="")
This will override the default argument of '\n' and you will get the desired output.

Rather than two print calls, you can create a single string and print once.
Consider:
print("{} and {}".format(("warm", "cold")[isCold], ("dry", "rainy")[isRainy]))
In this case you are using the boolean value of each iCold and isRainy to index a tuple of strings to create a single string with all combinations.
You can also use the Python ternary to accomplish the same:
print("{} and {}".format("cold" if isCold else "warm", "rainy" if isRainy else "dry"))

You can also try this:
if isCold:
a = "cold and "
else:
b = "warm and "
if isRainy:
print(a+'rainy')
else:
print(b+'dry')

Use a logical and:
if sys.argv[1] == 'True' and sys.argv[2] == 'True':
print("cold and rainy)

Related

Why is there no blank space printed when there is a print() after an end function?

print("where is", end = ' ')
print()
print("Blank line")
Why is there no blank space between these two lines of code? From what I have, heard, the print() prints a blank line, so why does having print() after the end function cause there to be no blank space?
I am aware that the end function means that the end character is defined by the last whitespace and not a new line.
print() works just the way you think it does.
However, the preceding line has a print statement that does not end with a newline character; instead it prints a space.
So this what is printed:
where is<space><newline>Blank line'
The <space> comes from the first print statement
The <newline> comes from the second print statement
You already know that Blank line comes from the third print statement
end = ' ' explicitly stops the first print from printing a newline. The output of the three statements is:
"where is " + "\n" + "Blank line\n"
i.e.
"where is \nBlank line\n"
Which results in:
where is
Blank line
In Python, print() function ends with a newline by default, however, the print() function has an option to modify that behavior. Using the end = ' ' replaces the \n with a blank space.
Python 3.9: Input and Output
Try using this
print("""where is
Blank line""")

difference between print(" str", a ) and print("str" + a )

I am a beginner with python3 and I use a lot print or the logging module to follow the code on the console. A simple example below: what's the difference between:
number = "seven"
print("I cooked " , number , " dishes")
and
number = "seven"
print("I cooked " + number + " dishes")
Internally the difference is that this example (no + sign):
number = "seven"
print("I cooked " , number , " dishes")
Is printing 3 separate string objects. "I cooked ", is object 1, number is object 2, and " dishes" is object 3. So this has 3 objects total.
In the second example (with the + sign):
number = "seven"
print("I cooked " + number + " dishes")
the 3 separate strings are first being concatted into 1 new string object before being printed to stdout. So this example has 4 objects total.
The print statement supports multiple ways of parsing values.
number = 'seven'
Examples: Different style of adding argument in print statement
print("I cooked " , number , " dishes")
C-Style formatting (old):
print("I cooked %s dishes" % number)
C-Style formatting (new) using fomat:
print("I cooked {} dishes ".format(number))
f-string style
print(f"I cooked {number} dishes")
String concatenating:
print("I cooked " + number + " dishes")
You don't necessary to stick with one style. You have various options of doing the same.
The operator + can be only used on strings.
The operator , can be used on any type, and adds a space before automatically.
In addition, + can be used not only in printing but to add one string to another while , cant.
(Note that in the two examples you have, by simply running them will show that the results are different, as the first one will have some words separated by double spaces.)
The print() function will take in strings, each string will be printed out with a ' ' between them:
print('hello', 'world')
Output:
hello world
That is because of the keyword argument, sep. By default, sep=' ', that is changeable by simply adding:
print('hello', 'world', sep='\n')
Output:
hello
world
The + operator will not add any separator, it will simply concatenate the strings:
print('hello' + 'world')
Output:
helloworld
As per PEP3105 print is considered as a function taking *args (several positional arguments).
To answer your question, the result is the same; however, your implementation is different. In the first case you give print multiple arguments to print, while in the second case you give print a concatenated string that you would like to print.
when using
number = "seven"
print("I cooked " , number , " dishes")
print gets 3 different objects (3 strings) as arguments, converts them to string and then prints.
However using
number = "seven"
print("I cooked " + number + " dishes")
means that first these three strings are concatenated and then passed as one object to print.
In reality, it means, that if you do for example
print('xxx' + 5 + 'yyy')
it will throw and error, as it is not possible to directly concatenate string and int types.
Also note following example:
#concatenating 3 strings and passing them as one argument to print
>>> print('xxx' + 'a' + 'yyy',sep=',')
xxxayyy
#passing 3 strings as 3 arguments to print
>>> print('xxx','a','yyy',sep=',')
xxx,a,yyy
You can notice, that in first example, although sep is used (thus it should separate 3 strigns with given separator) it does not work, because these strings are concatenated first and then passed as one argument to print. In the second example however, strings are passed as separated arguments, therefore sep=',' works, because print just knows that it should pass the separator between each given string.
Lets say a = "how are you" and b = "goodbye" which are 2 string variables.
If we do print(a, b):
The statement will print first a then b as separate strings outputted on one line:
Output:
> how are you goodbye
If we do print(a + b) the statement will concatenate these two variables a and b together:
Output:
> how are yougoodbye
(here there's no spacing due no white spacing in the print statement or the variables)

Why does my code print twice the amount of spaces I expect?

Python provides a built-in function called len that returns the length of a string, so the value of len('allen') is 5. Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.
Author's solution:
def right_justify(s):
print (' '*(70-len(s))+s)
>>> right_justify('allen')
My solution:
def right_justify(s):
space_count=70-len(s)
for i in range(0,space_count,1):
print " ",
print s
strng=raw_input("Enter your desired string:")
print len(strng)
right_justify(strng)
The output of my code is different than the output of author's code: I am getting twice as many spaces, e.g. 130 instead of 65.
But it seems to me that the two pieces of code are logically equivalent. What am I overlooking?
The problem is with your print statement
print " ",
will print two spaces for each iteration of the loop. When terminating the print statement with a comma, subsequent calls will be delimited by a space.
On a side note, another way to define your right_justify function would be
def right_justify(s):
print '%70s' % s
The print " ", line actually prints two spaces (one from the " ", one from the ,). You could replace it with print "", to have your function work identically to the original.
Your code has 130 spaces, the author's code has 65 spaces. This is because
print " ",
...adds a space. What you want is:
print "",
I would prefer the function str.rjust(70," ") which does the trick, I think, like so:
strng.rjust(70," ")

File Inout Output multiple delimiters

i am trying to construct a dictionary based on a file that is seperated by different delimiters. For example i the file im reading is structured the following way, i need the line as a variable for demonstrative purposes
g = "ENGL 1301,preprofessional,MATH 2413,"
if ","and "," in g :
print "yay"
if "," and "," and "," in g:
print "nay"
the file can have multiple commas which means different things so im trying to diffinterate between the amount of commas in the line. I want the above program to only print "nay" since there are 3 commas in the string and not 2. How can i accomplish this since the above program failed and printed both "yay" and "nay"
Use str.count:
g = "ENGL 1301,preprofessional,MATH 2413,"
commas = g.count(",") # I put this up here so it isn't called multiple times
if commas == 2:
print "yay"
elif commas == 3: # I used `elif` here since `commas` cannot equal 2 and 3
print "nay"
Also, your current code doesn't work because non-empty strings evaluate to True in Python. So, this:
if "," and "," in g :
print "yay"
if "," and "," and "," in g:
print "nay"
becomes like this:
if True and ("," in g):
print "yay"
if True and True and ("," in g):
print "nay"
As you can guess, each of those if-statements will always pass.

Python Checking a string's first and last character

can anyone please explain what is wrong with this code?
str1='"xxx"'
print str1
if str1[:1].startswith('"'):
if str1[:-1].endswith('"'):
print "hi"
else:
print "condition fails"
else:
print "bye"
The output I got is:
Condition fails
but I expected it to print hi instead.
When you say [:-1] you are stripping the last element. Instead of slicing the string, you can apply startswith and endswith on the string object itself like this
if str1.startswith('"') and str1.endswith('"'):
So the whole program becomes like this
>>> str1 = '"xxx"'
>>> if str1.startswith('"') and str1.endswith('"'):
... print "hi"
>>> else:
... print "condition fails"
...
hi
Even simpler, with a conditional expression, like this
>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
hi
You should either use
if str1[0] == '"' and str1[-1] == '"'
or
if str1.startswith('"') and str1.endswith('"')
but not slice and check startswith/endswith together, otherwise you'll slice off what you're looking for...
You are testing against the string minus the last character:
>>> '"xxx"'[:-1]
'"xxx'
Note how the last character, the ", is not part of the output of the slice.
I think you wanted just to test against the last character; use [-1:] to slice for just the last element.
However, there is no need to slice here; just use str.startswith() and str.endswith() directly.
When you set a string variable, it doesn't save quotes of it, they are a part of its definition.
so you don't need to use :1

Categories

Resources