How to avoid line break after user input in Python? - python

How to change below code and remove unnecessary new line?
#"Please guess a number!"
choice = input ("Is it ")
print ("?")
Is it 10
?
So that result will look like
Is it 10?

To "remove" the newline in your code snippet you would need to send cursor control commands to move the cursor back to the previous line. Any concrete solution would depend on the terminal you're using. Strictly speaking, there are no unnecessary newlines in the sample above. The user provided the newline that follows 10, not Python. I suppose you could try to rewrite the input processor so that user input isn't echoed similar to getpass.getpass().

If someone looking for a solution, I found one-liner:
print('Is it ' + input('Please guess a number: ') + '?')
Firstly, with above line user input requested as
Please guess a number:
Then user enter the value
Please guess a number: 10
After input confirmation (Pressing Enter) next line appears as
Is it 10?

you mean something like that?
choice = input ("enter somthing...")
print ("Is it "+str(choice)+"?")

If you need it to be longer then the above one you could drag it out.
Choice = input("Number:")
answer = "Is it %s ?" % choice
print(answer)
I like Shohams tho, more pythonic imho

Very similar to the accepted answer in this question: remove last STDOUT line in Python
But here it is tailored to your solution. A little hackish admittedly, would be interested in a better way!
choice = input ("Is it ")
CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'
print CURSOR_UP_ONE + ERASE_LINE + 'Is it ' + str(choice) + '?'

I do deep you cannot.Because if the procedure is "choice = input("Is it ")",you must be to what end the enter,the line must be is new line.you can the change the express.
choice = input("Please input the number:")
print "Is it " + str(choice) + " ?"

Related

error when user entering dot in python input

im wondering why is
File "<string>", line 1
.
^
SyntaxError: unexpected EOF while parsing
coming when i execute following script and including dot in input.
answer = input('enter 1: ')
if answer == 1:
print('nice')
else:
print('please enter "1"')
return
I have been wondering this pretty long, and now im trying to ask here if someone could help me.
So i can't include dots or anything else that basic letters and numbers my input.
I thought there could be easy way to find this thing out.
There is other code i need to fix below, with same error.
email = str(input('required* Your mail: '))
print('your mail is : ' + email)
now, it needs to include dot and at mark.
The code here seems ok, except for the fact you're using return without a function.
And the code wouldn't work when I put I type 1, because you need to cast the var "aswer".
The code should be like this:
answer = int(input('enter 1: '))
if answer == 1:
print('nice')
else:
print('please enter "1"')
You are putting a string and you are checking if is this a number, that is your error, so if you want to ask every time if the answer is wrong you could do this:
while True:
answer = input('enter 1: ')
if answer == "1":
print('nice')
break
else:
print('please enter "1"')

I have a weird issue of python when i am trying to use pycharm

I wrote a length converter with python,
here are the codes:
active = True
while active:
option = input('please choose:\na:centimetre to inch \nb:inch to centimetre:')
if option == "a":
centimetre = input('Please enter centimetre:')
centimetre= float (centimetre)
inch = centimetre / 2.54
print(str(centimetre) + ' centimetre equals' + str(inch) + ' inches')
elif option == "b":
inch = input('Please enter inch:')
inch = float ( inch )
centimetre = inch * 2.54
print(str(inch) + ' inch equals ' + str(centimetre) + ' centimetre')
else:
print("sorry you entered wrong option。please enter 'a'or'b': ")
continue
status = input('continue? yes/no :')
if status == 'no':
active = False
It's ok when these codes run with notepad++ and
http://www.pythontutor.com/
but when I try to use pycharm, it got error:
line 6, in <module>
centimetre= float (centimetre)
ValueError: could not convert string to float:
not sure where is the problems. Has anyone met this issue?
You could try checking if the input is able to be converted into a float, using try:.
And, also, if it's an issue with Python not recognizing commas as a decimal point, and maybe periods as a thousands separator, then you could check for if the number with commas and periods swapped (using the .replace() method).
An example of this is:
x = '2.3'
y = '3,4'
def isnumber(num):
try:
float(num)
return True
except ValueError:
try:
float(num.replace(',', 'A').replace('.', 'B').replace('A', '.').replace('B', ','))
return True
except ValueError:
return False
if isnumber(x):
print(f'The number {x} is valid.')
else:
print(f'The number {x} is not valid.')
print()
if isnumber(y):
print(f'The number {y} is valid.')
else:
print(f'The number {y} is not valid.')
You are probably using wrong decimal separator on input. Perhaps comma "," instead of full stop "."
You need to replace that or catch the error (or both together). I suggest:
try:
centimetre = float(centimetre.replace(',', '.'))
except ValueError:
print('Input is not a valid number or in invalid format!')
i tried days to fix it and have solved this issue
i created a brand new project in pycharm and put the code in a new file.
it works now
if you just copy and paste the code to existed pycharm project, it might not work
not sure why, but at least it's not my codes' fault and it works now.
Try this:
centimetre = float(input('Please enter centimetre:'))

How to fix a print error in python for a multiple choice quiz?

I apologize in advance if a topic like this has already been made, if so, please link me to it, thank you.
So, I have been trying to create a multiple choice quiz in python (yes, very iconic) but when I try to run it, I get a syntax error which is common I suppose, however, it seems to have an issue with the print variable:
print ('QUESTION 1: WHAT IS A NON-MOVING OBJECT CALLED?\n')
print ('A. Solid')
print ('B. Still object')
print ('C. Stationery')
print ('D. not moving')
print ('E. Stationary')
print ('')
Q1answer = "E"
Q1response= input('Your answer : ')
if (Q1response != Q1answer):
print ('Sorry! It appears that your answer is incorrect! A non-moving object is called Stationary.')
print ('Better luck next time!' , answer)
else:
print ('Well done! ' + Q1response + ' is correct!')
score = score + 1
print ("Even I got that one right!"
**print("Your current score is ' str(score) + ' out of 10")**
print ('\n-----------------------------------------------------------\n')
the print variable for showing the score you get out of 10 doesn't seem to work.
Am I doing something wrong?
It'd be a great help if someone could tell me, I'm not very good at coding.
print("Your current score is %d out of 10" %score)
Take a look at printf-style string formatting for details on formatting and inserting other types of data into a printed string.

Issue in code to guess random number

I am trying to write a simple python code to guess a random number between 1 and 20. For the incorrect guess, the system shows intended message but for the correct guess it is not giving the proper output.
Could someone help me understand the issue in the below code
import random
import sys
answer=random.randint(1,20)
nt=0
cg=0
while cg!=answer:
nt=nt+1
print('Guess the correct number')
cg=input()
if cg==answer:
print('Congrats! You have guessed correctly in' + str(nt) + ' tries')
sys.exit()
print('Guess is incorrect. Please try again. Answer is ' + str(answer) + ' in ' + str(nt) + ' tries')
continue
In cg=input(), input() return type in 'str'. So the condition cg==answer will always be false.
Use:
cg=int(input())
instead of
cg=input()
read more about input() here

loop prints a error message multiple times

edited for clarity. When a loop prints an error message multiple times, it is usually caused by poor control flow. In this case, adding a Breakafter print solved the problem.
Following a simple loop structure with some control flow, is generally a good starting point.
for ...:
if ...:
print ...
break
input_seq = "";
#raw_input() reads every input as a string
input_seq = raw_input("\nPlease input the last 12 nucleotide of the target sequence
before the PAM site.\n\(The PAM site is by default \"NGG\"\):\n12 nt = ")
#print "raw_input =", input_seq
for bases in input_seq:
if not (bases in "ACTGactg"):
print "\nYour input is wrong. Only A.T.C.G.a.t.c.g are allowed for
the input!\n\n";
break
Use break. I am using regular expressions to avoid using a for loop.
input_seq = ""
import re
while True:
#raw_input() reads every input as a string
input_seq = raw_input("\nPlease input the last 12 nucleotide of the target sequence
before the PAM site.\n\(The PAM site is by default \"NGG\"\):\n12 nt = ")
#print "raw_input =", input_seq
if len(input_seq)==12:
match=re.match(r'[ATCGatcg]{12}',input_seq)
if match:
break
else:
print "\nYour input is wrong. Only A.T.C.G.a.t.c.g are allowed for the input!\n\n"
continue
else:
print "\nYour input should be of 12 character"
Add a break after your print statement. That will terminate your loop.
Using a flag to check if there were atleast one wrong input is one way to do it. Like this:
invalid = False
for bases in input_seq:
if not (bases in "ACTGactg"):
invalid = True
if invalid:
print "\nYour input is wrong. Only A.T.C.G.a.t.c.g are allowed for the input!\n\n";
You could alternately use a break statement as soon as you find the first wrong input.
Place a break after the print:
for ...:
if ...:
print ...
break

Categories

Resources