I have a python program which works as a calculator.
import re
value = 0
run = True
while run:
if value == 0:
equation = input('Enter the equation ')
else:
equation=input(str(value))
# print(equation + ' ')
if equation == 'quit':
run = False
else:
equation = re.sub("[a-zA-Z""]",'',equation)
if value ==0:
# equation=eval(equation)
value=eval(equation)
else:
value=eval(str(value)+equation)
print(equation + ' ')
The program works without problem , but when reading the input after the first iteration , the terminal is as below
python3 file.py
Enter the equation 10+10
20+30
The next input can be provided next to 20. I want to add a space before reading the input , so the output will be as shown below
python3 file.py
Enter the equation 10+10
20 +30
How can I add a space before reading the next input so the cursor will create a space
Example
input=input('Enter the input ')
Python Version : 3.7.7
You may simply append a space to the string given to input.
In your example, changing the line equation=input(str(value)) to equation=input(str(value) + ' ') will produce your desired output.
IMHO, this line is not what you want:
equation=input(str(value))
Outputting the result of the calculation should be separate from the next input because of semantics. The argument to input() is the prompt to tell the user what to do. "20" (or whatever intermediate result) is not a good instruction for the user.
So the code becomes
print(value, end=" ") # end=" " prevents a newline and adds a space instead
equation=input() # don't give any prompt, if there's no need to
Related
I'm just learning Python and have to create a program that has a function that takes as arguments a first and last name and creates a username. The username will be the first letter of the first name in lowercase, the last 7 of the last name in lowercase, and the total number of characters in the first and last names. For example, Jackie Robinson would be jobinson14. I have to use sys.argv.
This is my code:
import sys
def full_name(first, last):
first = input(first)
last = input(last)
username = lower((first[0] + last[:7])) + len(first+last)
return username
first = sys.argv[1]
last = sys.argv[2]
username = full_name(first, last)
print ("Your username is",username)
When entering Darth Vader
Expected output:
Your username is dvader10
Actual output:
Darth
Please help!
Actual output:
Darth
Not exactly. You are using input(first), which is waiting for you to type something...
Using sys.argv means you need to provide the arguments when running the code
python app.py Darth Vader
And if you remove the input() lines, this would return without prompting for input, and not show Darth
As shown, you are trying to read from arguments and prompt for input.
If you did want to prompt, then you need to remove the import
def full_name(first, last):
return (first[0] + last[-7:] + str(len(first+last))).lower()
first = input('First Name: ')
last = input('Last Name: ')
username = full_name(first, last)
print("Your username is",username)
And just run the script directly. But you say you have to use sys.argv, so the solution you're looking for is to not use input() at all.
When you call the input() function and assign it to first, like this:
first = input(first)
what you're doing is printing first (so "Darth"), waiting for the user to enter something, and then assigning that to first. That's why your script prints Darth -- it's waiting for you to tell it what first is.
But since you already passed the first and last name via the command line, you don't want to do that -- so just remove those two input lines. Make sure to convert the len to a str before you add it to the other strings!
def full_name(first, last):
return (first[0] + last[:7] + str(len(first+last))).lower()
You ask to input names even if they are in sys.argv.
Input("Enter name: ") accepts string that help to understand what you should input.
As OneCricketeer commented, you trying to get first 7 letters instead of last.
Here is an example that accepts names from command line otherwise prompt to input.
import sys
def full_name(_first, _last):
return f"{(_first[0] + _last[-7:])}{len(_first + _last)}"
if __name__ == '__main__':
first = last = ""
if len(sys.argv) == 3:
if sys.argv[1]:
first = sys.argv[1].lower()
if sys.argv[2]:
last = sys.argv[2].lower()
if not first:
first = input("Input first name: ").lower()
if not last:
last = input("Input last name: ").lower()
username = full_name(first, last)
print("Your username is", username)
I want to print two labels that have the same numbers on them. I am using ZPL. I have already made my print format in ZPL and it works properly. I am trying to print a data range. For example:
"What is the first number in the range?" User inputs 100
"What is the second number in the range?" User inputs 120
I would then get 40 labels in order.
I then want it to export that data into a notepad file and then print it to my default printer. My problem is that to print with ZPL I have to "tag" my data range with my ZPL code. I cant figure out how to get my data range to go into my print statement correctly. Please help. Thank you in advance!
import os
import sys
start = int(input("Enter the start of range: "))
end = int(input("Enter the end of range: "))
with open('TestFile.txt', 'a') as sys.stdout:
print('^XA')
print('^PQ2')
for labelRange in range(start, end + 1):
print('^FO185,50^A0,300^FD')(labelRange, end = " ")('^FS')
#print('\n')
print('^XZ')
os.startfile("C:/Users/joe.smith/desktop/TestFile.txt", "print")
exit()
here is something to get you started, but I doubt it is complete. You will need to provide a valid ZPL file for making the changes.
I also made the program use fixed numbers for now and so it just runs and outputs.You can change it back once you have it working.
start = 110
end = 111
notepad = ''
# these are header lines that go once (if windows you might need \r\n instead of \n)
notepad += '^XA\n'
notepad += '^PQ2\n'
for label in range(start, end + 1):
# use f-strings
notepad += f'^FO185,50^A0,300^FD{label}^FS\n'
# if you need some of those other numbers to increment
# then setup a counter and do the math here inside the f-string
notepad += f'^FO185,50^A0,300^FD{label}^FS\n'
notepad += '^XZ\n'
# with open('tf.txt', 'w') as sys.stdout:
# print(notepad)
print(notepad)
exit()
outputs:
^XA
^PQ2
^FO185,50^A0,300^FD110^FS
^FO185,50^A0,300^FD110^FS
^FO185,50^A0,300^FD111^FS
^FO185,50^A0,300^FD111^FS
^XZ
interactive input prompt to open browsers...(will print something instead for now).
chrm = ['Google Chrome', 'Chrome']
input("type a browser..: ")
if chrm[0:1] == input():
print("starting: " + chrm)
What my intention is for this little thing is for a person to write one of the two possible input options..."Google Chrome" or "Chrome" to get a certain response. like openfile or printing something. but I can't seem to get it right.
You should assign the returning value of input() to a variable, and use the in operator to test if it is one of the values in the chrm list:
chrm = ['Google Chrome', 'Chrome']
i = input("type a browser..: ")
if i in chrm:
print("starting: " + i)
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()))
#!usr/bin/python
listofnames = []
names = input("Pls enter how many of names:")
x = 1
for x in range(0, names):
inname = input("Enter the name " + str(x))
listofnames.append(inname)
print listofnames
error
inname = input("Enter the name " + str(x))
File "", line 1, in
NameError: name 'Jhon' is not defined
Use raw_input instead. See http://docs.python.org/library/functions.html#raw_input. input will do the same thing as eval(raw_input(prompt)), so entering in Jhon will try to find the symbol Jhon within the file (which doesn't exist). So for your existing script you'd have to input 'Jhon' (notice the set of quotes) in the prompt so the eval will convert the value to a string.
Here's the excerpt warning from the input documentation.
Warning
This function is not safe from user
errors! It expects a valid Python
expression as input; if the input is
not syntactically valid, a SyntaxError
will be raised. Other exceptions may
be raised if there is an error during
evaluation. (On the other hand,
sometimes this is exactly what you
need when writing a quick script for
expert use.)
Below is the corrected version:
#!usr/bin/python
# The list is implied with the variable name, see my comment below.
names = []
try:
# We need to convert the names input to an int using raw input.
# If a valid number is not entered a `ValueError` is raised, and
# we throw an exception. You may also want to consider renaming
# names to num_names. To be "names" sounds implies a list of
# names, not a number of names.
num_names = int(raw_input("Pls enter how many of names:"))
except ValueError:
raise Exception('Please enter a valid number.')
# You don't need x=1. If you want to start your name at 1
# change the range to start at 1, and add 1 to the number of names.
for x in range(1, num_names+1)):
inname = raw_input("Enter the name " + str(x))
names.append(inname)
print names
NOTE: This is for Python2.x. Python3.x has fixed the input vs. raw_input confusion as explained in the other answers.
input gets text from the user which is then interpreted as Python code (hence it's trying to evaluate the thing you entered, Jhon). You need raw_input for both of them and you'll need to convert the number entered (since it's a string) to an integer for your range.
#!usr/bin/python
listofnames = []
names = 0
try:
names = int(raw_input("Pls enter how many of names:"))
except:
print "Problem with input"
for x in range(0, names):
inname = raw_input("Enter the name %d: "%(x))
listofnames.append(inname)
print listofnames
In python3, input() now works like raw_input(). However to get your code to work with Python3 a couple of changes are still required
#!usr/bin/python3
listofnames = []
names = int(input("Pls enter how many of names:"))
x = 1
for x in range(0, names):
inname = input("Enter the name " + str(x))
listofnames.append(inname)
print(listofnames)