Why is the output forcing a new line on the result when there isn't a \n after print (message_2.capitalize())?
# Input example python script
# Apparently in python 3.6, inputs can take strings instead of only raw values back in v2.7
message_0 = "good morning!"
message_1 = "please enter something for my input() value:"
message_2 = "the number you entered is ... "
message_3 = "ok, now this time enter value for my raw_input() value:"
message_final1 = "program ended."
message_final2 = "thank you!"
print ("\n\n")
print (message_0.capitalize() + "\n")
input_num = input(message_1.capitalize())
print ("\n")
# This line is obsoleted in python 3.6. raw_input() is renamed to input() .
# raw_input_num = raw_input(message_3.capitalize())
# data conversion
print ("Converting input_num() variable to float...\n")
input_num = float(input_num)
print ("\n")
print (message_2.capitalize())
print (input_num)
print ("\n")
print (message_final1.capitalize() + " " + message_final2.capitalize())
Output is as follows:
Good morning!
Please enter something for my input() value:67.3
Converting input_num() variable to float...
The number you entered is ...
67.3
Program ended. Thank you!
print(), by default, will add a newline. So the two statements:
print (message_2.capitalize())
print (input_num)
will put a newline in between the message and the number.
Either pass in both objects to print to one print() call:
print(message_2.capitalize(), input_num)
or tell print() not to add a newline by setting the end argument to an empty string:
print(message_2.capitalize(), end='')
print(input_num)
Python's print() function's default behavior is to print a newline follwing the input string.
You can change this behavior by adding the optional parameter end:
print("My message", end="")
I've asked my friends around, and rather than just deleting my question I thought to add value to this site by sharing the answer :
# , operator here removes an unexpected newline. the print statement has a built in newline. That's why!
print (message_2.capitalize(),(input_num),"\n")
# Alternative way to display the answer
print (message_2.capitalize() + " " + str(input_num))
So the key is to use a comma operand or do a string operator on the answer.
Related
print "Question?",
answer = raw_input()
The error:
Brians-Air:PythonFiles Ghost$ python ex11.py
File "ex11.py", line 1
print "How old are you?
^
SyntaxError: EOL while scanning string literal
I removed the "," and the interpreter gave an error. My thought was that removing the "," would give a new-line and request input on this new-line.
My question is why is the "," after the print statement necessary? Is this just the syntax coded into Python?
here is what you need to write:
while True:
print 'Question?'
answer = raw_input(' >')
if answer == ('done'):
break
print answer
I'm trying to print a single row, but this line of code is always causing me a syntax error.
Here's my code:
for a in range(0,3):
for x in range(0,3):
index = random.randrange(0,len(word_List))
print(" ", word_List[index], end= ' ',) # prints in a single row
first_Grid.append(word_List.pop(index))
You're probably looking for something like this:
print(" {}".format(word_List[index]), end= ' ')
Also note that if you're using Python 2.x instead of 3.x, you either need to add:
from __future__ import print_function
To the top of your file, or use this instead:
print " {}".format(word_List[index]), end=" "
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to print in Python without newline or space?
How to print a string without including ā\nā in Python
I have a code that looks like this:
print 'Going to %s'%href
try:
self.opener.open(self.url+href)
print 'OK'
When I execute it I get two lines obviously:
Going to mysite.php
OK
But want is :
Going to mysite.php OK
>>> def test():
... print 'let\'s',
... pass
... print 'party'
...
>>> test()
let's party
>>>
for your example:
# note the comma at the end
print 'Going to %s' % href,
try:
self.opener.open(self.url+href)
print 'OK'
except:
print 'ERROR'
the comma at the end of the print statement instructs to not add a '\n' newline character.
I assumed this question was for python 2.x because print is used as a statement. For python 3 you need to specify end='' to the print function call:
# note the comma at the end
print('Going to %s' % href, end='')
try:
self.opener.open(self.url+href)
print(' OK')
except:
print(' ERROR')
In python3 you have to set the end argument (that defaults to \n) to empty string:
print('hello', end='')
http://docs.python.org/py3k/library/functions.html#print
Use comma at the end of your first print: -
print 'Going to %s'%href,
I'm a technical writer learning python. I wanted to write a program for validating the Name field input,as a practise, restricting the the user entries to alphabets.I saw a similar code for validating number (Age)field here, and adopted it for alphabets as below:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
print raw_input("Your Name:")
x = r
if x == r:
print x
elif x != r:
print "Come on,'", x,"' can't be your name"
print raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
I intend this code block to do two things. Namely, display the input prompt until the user inputs alphabets only as 'Name'. Then, if that happens, process the length of that input and display messages as coded. But, I get two problems that I could not solve even after a lot of attempts. Either, even the correct entries are rejected by exception code or wrong entries are also accepted and their length is processed.
Please help me to debug my code. And, is it possible to do it without using the reg exp?
If you're using Python, you don't need regular expressions for this--there are included libraries which include functions which might help you. From this page on String methods, you can call isalpha():
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
I would suggest using isalpha() in your if-statement instead of x==r.
I don't understand what you're trying to do with
x = r
if x == r:
etc
That condition will obviously always be true.
With your current code you were never saving the input, just printing it straight out.
You also had no loop, it would only ask for the name twice, even if it was wrong both times it would continue.
I think what you tried to do is this:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
x = raw_input("Your Name:")
while not r.match(x):
print "Come on,'", x,"' can't be your name"
x = raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
Also, I would not use regex for this, try
while not x.isalpha():
One way to do this would be to do the following:
namefield = raw_input("Your Name: ")
if not namefield.isalpha():
print "Please use only alpha charactors"
elif not 4<=len(namefield)<=10:
print "Name must be more than 4 characters and less than 10"
else:
print "hello" + namefield
isalpha will check to see if the whole string is only alpha characters. If it is, it will return True.
I am very new to Python programming (15 minutes) I wanted to make a simple program that would take an input and then print it back out. This is how my code looks.
Number = raw_input("Enter a number")
print Number
How can I make it so a new line follows. I read about using \n but when I tried:
Number = raw_input("Enter a number")\n
print Number
It didn't work.
Put it inside of the quotes:
Number = raw_input("Enter a number\n")
\n is a control character, sort of like a key on the keyboard that you cannot press.
You could also use triple quotes and make a multi-line string:
Number = raw_input("""Enter a number
""")
If you want the input to be on its own line then you could also just
print "Enter a number"
Number = raw_input()
I do this:
print("What is your name?")
name = input("")
print("Hello" , name + "!")
So when I run it and type Bob the whole thing would look like:
What is your name?
Bob
Hello Bob!
# use the print function to ask the question:
print("What is your name?")
# assign the variable name to the input function. It will show in a new line.
your_name = input("")
# repeat for any other variables as needed
It will also work with: your_name = input("What is your name?\n")
in python 3:
#!/usr/bin/python3.7
'''
Read list of numbers and print it
'''
def enter_num():
i = input("Enter the numbers \n")
for a in range(len(i)):
print i[a]
if __name__ == "__main__":
enter_num()
In the python3 this is the following way to take input from user:
For the string:
s=input()
For the integer:
x=int(input())
Taking more than one integer value in the same line (like array):
a=list(map(int,input().split()))