I'm making a script that show you a question, you give the answer ("y" or "n") and the line is restarted, and appears another question. I've tried this (assuming that the number is the question)
import sys
for i in range (10):
sys.stdout.write('\r'+str(i))
label = input()
if label=='n':
doSomething
if label=='y':
doSomethingElse
but in this cases, I get this
0n
1n
2y
3n
and I want that if I have
0
I give my answer and press Enter, the currently line disappear and the new number appears
1
and then I give an answer again, and so on.
I've already check this question and this. I'm using python 3.5.
Edit:
Thanks to an answer, now I know that I need to avoid the '\n' of the input() function.
When you use input(),there always have a output with '\n'. This '\n' changed to a new line,then the '\r' can't work as you wanted.
So, Maybe you should break through here(the input()).
Maybe a \n like in (see Part 1) and you can use an elif (see Part 2)
for i in range (10):
sys.stdout.write(str(i) + '\n') # Part 1
label = input()
if label == 'n':
doSomething
elif label =='y': # Part 2
doSomething
Related
How to print variable name by input, Example:
a = 1
b = 2
what_variable = input('Which Variable?: ') #User for example introduces 'b'
Console: 2
You can write
print(globals()[what_variable])
but it's not a good approach. Use a dict instead
You can use exec:
var = input('Which Variable?: ')
exec("print(" + var + ")")
Output:
Which Variable?: b
2
>>
Just do the following:
print(eval(input('Which Variable?: ')))
You can also do
print(globals()[input('Which Variable?: ')])
While the other answers seem to address the obvious solution, it's not very 'Pythonic'. The main issues with these is, by far, safety. Let's say that your user inputs apiKey, and you happen to have a variable by that name... let's just say your bank statement is probably looking at a slight increase in magnitude. What most people in these answers don't realise is that using .globals()[input()] is no safer than eval(input()), because, shockingly, people store private info in variables. Alternatively, if it points to a method, e.g
a = print
b = os.system
eval(input())()
I could enter any function name there, and the damage would be done before the second () executes.
Why? Well, let's take a look at how exec and eval work (I won't go into the difference here, see this question for that). All they do is evaluate the string as Python code, and (simplifying here) return the value of the evaluation:
var1 = 3
print(eval("var1"))
# ====is equal to====
var1 = 3
print(var1)
(where var1 as a string obviously comes from the input typed in)
But if someone enters something malicious, this is essentially the basis of an SQL injection:
(where userInput is substituted by a user's input into an input())
userInput = "a + os.system('reboot now')"
print(eval(userInput))
# ====is equal to====
print(a + os.system('shutdown now')
and you suddenly find your computer's off.
Therefore, we'd either use a:
Dictionary (or object): x={a:1, b:2}, then do x[input()]
Array x=[1, 2], then do x[["a", "b"].index(input())]
Simply don't. Find a way to work around it. What's wrong with an if/else set? It's not good practise, because of the safety concerns outlined above. What most people seem to miss about dictionaries (or my array option) is that if you enter a malformed input (i.e not a or b), it would result in either uncaught errors being thrown, or undefineds being thrown around. And if you're going to do input validation, you're using an if statement anyway, so why not do it from the onset?
I am new to python and trying to learn by doing small projects.
I am trying to write a program that displays the names of the four properties and
asks the user to identify the property that is not a railroad. The user should be informed if the selection is correct or not.
properties = "Reading,","Pennsylvania","B & O","Short Line"
question = str(input("Which is not a railroad?")) **Short Line**
if properties == "Short Line":
print("correct")
else:
print("incorrect")
However, my final output shows as "incorrect", what am i doing wrong?
The four railroad properties
are Reading, Pennsylvania,
B & O, and Short Line.
Which is not a railroad? Short Line
Correct.
Short Line is a bus company.
Couple things I see with this code you have posted.
First, not sure if you actually have **Short Line** in your actual code but if you are trying to comment use # That way it won't be interpreted at run time.
Second as mentioned in other answers you are checking against properties which is pulling in your array. You should be checking against your input which is stored at question.
properties = "Reading,","Pennsylvania","B & O","Short Line"
question = str(input("Which is not a railroad?")) # **Short Line**
if question == "Short Line": # replaced properties with question
print("correct")
else:
print("incorrect")
print(properties)
print(question)
I find that when I am having troubles understanding why something is not working I throw some print statements in to see what the variables are doing.
You may want to catch the user in a loop, otherwise you would have to constantly have to run the code to find the correct answer(unless that is the desired behavior, then you can leave it as you have it). Also, be aware that you may want to uppercase or lowercase because a user may provide the answer as "Short line" (lower case "L"), and the code will return as incorrect. Of course, that depends on what you will accept as an answer.
Sample
print ("Reading,Pennsylvania,B & O, or Short Line. Which is not a railroad?")
user_input = input("Please provide an answer: ")
# != the loop will close once the user inputs short line in any form
# The upper.() will convert a user_input string to all caps
while user_input.upper() != "SHORT LINE":
print ("Incorrect, Please try again.")
user_input = input("Which one is not a railroad? ")
print ("Correct")
Prettied it up for you
print( "Reading, Pennsylvania, B & O, and Short Line. Which is not a railroad?" )
print("Which is not a railroad?")
answer = input()
if answer == "Short Line":
print("correct")
else:
print("incorrect")
Forgive me if this comes out a bit scatter-brained, I'm not exaggerating when I say I've been working on this program for over 13 hours now and I am seriously sleep deprived. This is my 4th revision and I honestly don't know what to do anymore, so if anyone can help me, it would be greatly appreciated. My introduction to programming teacher wanted us to make a "flash card" study program from his template. I am using Idle 3.3.3 on a windows 7 machine.
#Flash Cards
#Uses parallel arrays to store flash card data read from file
#Quizzes user by displaying fact and asking them to give answer
import random
def main():
answer = [] #array to store answer for each card
fact = [] #array to store fact/definition for each card
totalTried = 0 #stores number of cards attempted
totalRight = 0 #stores number of correct guesses
loadCards(answer, fact) #call loadcards() and pass it both arrays
numCards = len(answer) #find number of cards loaded
keepGoing = "y"
while keepGoing == "y" or keepGoing == "Y":
#Enter your code below this line
# 2a. Pick random integer between 0 and numCards and store the
# number in a variable named randomPick.
randomPick = random.randint (0, numCards)
# 2b. Add one to the totalTried accumulator variable.
totalTried = totalTried + 1
# 2c. Print element randomPick of the fact array. This shows the
# user the fact/definition for this flashcard.
print (fact [randomPick] )
# 2d. Prompt the user to input their guess and store the string they
# enter in a variable named "userAnswer"
userAnswer = input ('What is your answer?' )
# 2e. Compare the user's guess -userAnswer- to element
# -randomPick- of the answer array.
if userAnswer == (answer [randomPick]):
# 2e-1 If the two strings are equal, tell the user they
# guessed correctly and add 1 to the totalRight
# accumulator variable.
print ('That is correct.')
totalRight == totalRight + 1
# 2e2. If the two strings are not equal, tell the user they guessed
# wrong and display the correct answer from the answer array.
else:
print ('That is incorrect.')
print (answer [randomPick])
#2f. Prompt the user the user to see if they want to continue and
#store their response in the keepGoing variable.
keepGoing = input ('Would you like to continue?')
#Enter your code above this line
print("You got", totalRight, "right out of", totalTried, "attempted.")
def loadCards(answer, fact):
#Enter your code below this line
# 1a. Open flashcards.txt in read mode & assign it var name "infile"
infile = open('flashcards.txt', 'r')
# 1b. Read 1st line from file and store in var. name "line1"
line1 = infile.readline ()
# 1c. Use while loop to make sure EoF has not been reached.
while line1 != '':
# 1c1. Strip newline escape sequence (\n)from variable's value.
line1 = line1.rstrip ('\n')
# 1c2. Append string to answer array.
answer.append (line1)
# 1c3. Read next line from file and store in var. name "line2"
line2 = infile.readline ()
# 1c4. Strip newline escape sequence (\n) from variable's value.
line2 = line2.rstrip ('\n')
# 1c5. Append the string to the fact array.
fact.append (line2)
# 1c6. Read next line from file and store it in var. name "line3".
line3 = infile.readline ()
# 1d. Close file.
infile.close()
#Enter your code above this line
main()
When I run the program nothing actually happens, but when I try to close the shell window afterwards, it tells me that the program is still running and asks if I want to kill it.
Debugger shows me no information when I try to check it, also.
However, if I copy the code into the shell and run it from there, I get "SyntaxError: multiple statements found while compiling a single statement". Neither file has changed, but earlier it was telling me there was a problem with "import random".
Thanks in advance for any help.
I took a quick look and it mostly seems okay to me. I changed input() to raw_input() (two of them in your code) and noticed you had a double equals when you probably meant a single one
line 36:
totalRight == totalRight + 1
changed to
totalRight = totalRight + 1
which fixes your correct answer counter and line 68:
line3 = infile.readline ()
changed to
line1 = infile.readline ()
else it gets caught in your while loop forever. And I just copied line 54:
line1 = infile.readline ()
and pasted it so it is there twice to add another readline() call, just a lazy way of skipping the first line in your text file, since it seems to be a comment and not part of the answers and questions. You probably don't want to do that and just remove the comment from your text file. =b
With those changes, it seems to work fine for me.
Since this is for a class (and I can't only comment, I can just answer) I want to add that there actually is such a thing as too many comments
These comments (and to be honest, most of your comments) are distracting and unnecessary
answer = [] #array to store answer for each card
fact = [] #array to store fact/definition for each card
totalTried = 0 #stores number of cards attempted
totalRight = 0 #stores number of correct guesses
loadCards(answer, fact) #call loadcards() and pass it both arrays
numCards = len(answer) #find number of cards loaded
Also, the whole point of putting your program inside of a function called main is so you can run that function only if you are calling that file directly and you should probably put
if __name__ == '__main__':
main()
at the bottom of your code instead of just
main()
Use of input() is generally considered dangerous (unless you're using Python3 or later where it is the same as raw_input()) due to the fact that it evaluates the input. You should handle the type yourself with something like, if you want an integer,
foo = int(raw_input('Input a number: '))
(Note that the return of raw_input is a string, so if you want a string you don't have to do anything)
I want to write a python program, first it asks you to enter two numbers, and then output all daffodil numbers between the two numbers, and it will continue run, until I enter a "q". I write a program, but it is wrong:
#coding=utf-8
while 1:
try:
x1=int(raw_input("please enter a number x1="))
x2=int(raw_input("please enter a number x2="))
except:
print("please enter only numbers")
continue
if x1>x2:
x1,x2=x2,x1
pass
for n in xrange(x1,x2):
i=n/100
j=n/10%10
k=n%10
if i*100+j*10+k==i+j**2+k**3:
print ("%-5d")%n
pass
Can somebody help? I think it should be simple, but I am not able to write it correctly.
I believe you've misunderstood the problem statement. Try this instead:
if i*100+j*10+k==i**3+j**3+k**3:
ref: http://en.wikipedia.org/wiki/Narcissistic_number
for n in xrange(x1,x2):
digits = map(int,str(n))
num_digits = len(digits)
if sum(map(lambda x:x**num_digits,digits)) == n:
print "%d is a magic number"%n
you will still have the issue of not being able to enter "q" since you force the input to be integers
I would like to address the quit event.
while True:
x1 = raw_input("please enter a number x1=")
x2 = raw_input("please enter a number x2=")
quit = ('q','Q')
if x1 in quit or x2 in quit:
break
else:
try:
x1, x2 = int(x1), int(x2)
except:
print("please enter only numbers")
continue
# The mathematical part... (for completeness) (not my code)
if x1>x2:
x1,x2=x2,x1
for n in xrange(x1,x2):
i=n/100
j=n/10%10
k=n%10
if i*100+j*10+k==i+j**2+k**3:
print "%-5d"%n
The pass statement is used only when you don't have anything to be executed in certain block of code. It does nothing more, so don't use it if not needed. It is there for the sake of the code looking clean & with correct indentation.
if some_thing: # don't do anything
else:
some_thing = some_thing_else
Note how the above if statement is syntactically incorrect. This is where pass comes handy. Say, you decide to write the if part later, till then you must provide pass.
if some_thing: # don't do anything
pass
else:
some_thing = some_thing_else
It's a bit tricky to know what's going on without more hints, but some issues I see right off:
You need to be consistent with indentation in Python. Your last if statement is less indented than statements above it (like the previous if and the for loop). This will cause an error. You're also using different amounts of indentation in other places, but since it's not inconsistent that's allowed (if a bad idea). Its usually best to pick one indentation standard (like four spaces) and stick with it. Often you can set your text editor to help you with this (turn on "Expand tabs to spaces" or something in the settings).
You've got two pass statements where they're unneeded or harmful. The first, after the line that has if x1>x2: x1,x2=x2,x1 is going to cause an error. You can't have an indented "suite" of code if you've put a series of simple statements on the end of your compound statement like an if. Either put the assignment on its own line, indented, or get rid of the pass. The last pass at the end of the code is not an error, just unnecessary.
You're missing a colon at the end of your try statement. Every statement in Python that introduces an indented suite ends with a colon, so it should be easy to learn where they're needed.
while True:
x1 = raw_input("please enter a number x1=")
x2 = raw_input("please enter a number x2=")
quit = ('q','Q')
if x1 in quit or x2 in quit:
break
else:
try:
x1, x2 = int(x1), int(x2)
except:
print("please enter only numbers")
continue
if x1>x2:
x1,x2=x2,x1
pass
for n in xrange(x1,x2):
i=n/100
j=n/10%10
k=n%10
if i*100+j*10+k==i+j**2+k**3:
print ("%-5d")%n
pass
i have it! thx to Ashish! it is exactly what i want! and i will quit wenn i enter q! thx a lot!
I want to print the result of the equation in my if statement if the input is a digit and print "any thing" if it is a letter.
I tried this code, but it's not working well. What is wrong here?
while 1:
print '\tConvert ciliuse to fehrenhit\n'
temp = input('\nEnter the temp in C \n\t')
f = ((9/5)*temp +32)
if temp.isdigit():
print f
elif temp == "quit" or temp == "q" :
break
elif temp.isalpha() :
print ' hhhhhhh '
You need to go through your code line by line and think about what type you expect each value to be. Python does not automatically convert between, for example, strings and integers, like some languages do, so it's important to keep types in mind.
Let's start with this line:
temp = input('\nEnter the temp in C \n\t')
If you look at the documentation for input(), input() actually calls eval() on what you type in in Python 2.x (which it looks like you're using). That means that it treats what you type in there as code to be evaluated, just the same as if you were typing it in the shell. So if you type 123, it will return an int; if you type 'abc', it will return a str; and if you type abc (and you haven't defined a variable abc), it will give you an error.
If you want to get what the user types in as a string, you should use raw_input() instead.
In the next line:
f = ((9/5)*temp +32)
it looks like you're expecting temp to be a number. But this doesn't make sense. This line gets executed no matter what temp is, and you're expecting both strings containing digits and strings containing letters as input. This line shouldn't go here.
Continuing on:
if temp.isdigit():
isdigit() is a string method, so here you're expecting temp to be a string. This is actually what it should be.
This branch of the if statement is where your equation should go, but for it to work, you will first have to convert temp to an integer, like this:
c = int(temp)
Also, to get your calculation to work out right, you should make the fraction you're multiplying by a floating-point number:
f = ((9/5.0)*c +32)
The rest of your code should be okay if you make the changes above.
A couple of things first - always use raw_input for user input instead of input. input will evaluate code, which is potentially dangerous.
while 1:
print "\tConvert ciliuse to fehrenhit\n"
temp = raw_input("\nEnter the temp in C \n\t")
if temp in ("quit", "q"):
break
try:
f = ((9.0 / 5.0) * float(temp) + 32)
except ValueError:
print "anything"
Instead of using isalpha to check if input is invalid, use a catch clause for ValueError, which is thrown when a non-numerical value is used.
Why isn't it working? Are you getting an error of any kind?
Straight away I can see one problem though. You are doing the calculation before you verify it as a number. Move the calculation to inside the if temp.isdigit().
Take a look at this for some examples:
http://wiki.python.org/moin/Powerful%20Python%20One-Liners
OK, this works. Only problem is when you quit, you get dumped out of the interpreter.
while 1: import sys; temp=raw_input('\nEnter the temp in C \n\t'); temp.isdigit() and sys.stdout.write('%lf' %((9./5)*float(temp)+32)) or temp=='q' and sys.exit(0) or sys.stdout.write(temp)