Printing with Quotes [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How come when I use the program below i keep getting "y" in quotes opposed to the value defined by y, which would be the string entered by the user
def main():
x = (input("Give me a boolean: ").lower() == 'true')
y = str(input("Give me a string: "))
z = int(input("Give me a number: "))
if x == True:
print (y)
print ("\"",y,"\"",sep="")
else:
print (z*2)
main()

Let's talk about booleans, because this is actually the problem here.
x = bool(input("Give me a boolean: "))
# x is ALWAYS True unless the user enters an empty string
The problem here is that all non-empty strings are boolean True. "Hello" is True, "TRUE" is True, and "False" is True. The only string that evaluates to False is "". So when you prompt for input here, then test it later, you're always going to pass that test unless the user just bypasses the test. Let's move on...
y = str(input("Give me a string: ")) # good here, though no need to call str()
z = int(input("Give me a number: ")) # uh oh...
If I enter ajkldfj for z, it will throw a ValueError. The usual way to handle this is try/except, e.g.:
z = input("Give me a number: ")
try:
int(z)
except ValueError as e:
# handle it
Next up...
if x == True or true:
This is the same issue that TONS of people have. if foo == 1 or 2 doesn't mean what you think it does, it actually means if (foo == 1 is True) or (2 is True). To do what you're trying to do, you should do if x == "True" or x == "true", but better is if x.lower() == "true" and better still is if x.casefold() == 'true' but BEST YET is just if x. Remember, you're already turning it into a bool when you prompt for it. You can change that of course by dropping the bool() call, then testing for it here, in which case I recommend if x.lower() == 'true' or if x.casefold() == 'true'. The other code you'll see quite often is if x in ('true','True'), but since we can just lowercase to remove all ambiguity: DO IT!
Now to your print statements:
print (y) # prints the value in y
print ('"y"') # prints "y"
If this isn't what you want to do, you can use string formatting or really any of a bazillion other things to format it correctly. Let me know what you want to do and we can talk further!

you must use below line for print only y
print(y)
and below for y with Parentheses
print( "(" + y + ")")
Warning:in your Code if X==False then python give you below error
NameError: name 'true' is not defined

You can use format alongside print.
print("({0})".format(y))
Where 0 references the first argument passed to format, 1 the second, and so on. Also, you're doing x == True or true, the or true is wrong and should be removed. Also bool("True") == bool("False") == True, since strings (of length > 0) are True in Python, you probably want something like
x = str(input("True/False? "))
y = str(input("Input string: "))
z = int(input("Number: "))
if x.lower() == "true":
print("({0})".format(y))
Edit: Sample session
>>> def main():
x = str(input("True/False? "))
y = str(input("Input string: "))
z = int(input("Number: "))
if x.lower() == "true":
print("({0})".format(y))
>>> main()
True/False? false
Input string: dog
Number: 2
>>> main()
True/False? true
Input string: dog
Number: 2
(dog)

Related

Multiple unnecessary input appearing when using try except handling for input params [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 months ago.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Original close reason(s) were not resolved
def input_params():
user_input = int(input("Input a number"))
while user_input != 1 or user_input != 2:
try:
user_input = int(input("Input a number"))
if user_input == 1 or user_input == 2:
return user_input
else:
print("Invalid Input")
input_params()
except ValueError:
input_params()
When entering an invalid input such as "adf", and then proceeding to enter a valid input such as 2, the program doesn't process the valid input and asks me to input a value again. The program only comes to process the valid input on the second time I input it.
You don't need to use recursion. This code works just fine:
def inputParams(x,y):
while True:
try:
x = int(input(y))
if x == 1 or x == 2:
return x
else:
print("Invalid Input")
except:
pass
If you want to use recursion, delete the while loop, or use return inputParams(x, y) rather than just inputParams(x, y) to exit the function:
def inputParams(x,y):
try:
x = int(input(y))
if x == 1 or x == 2:
return x
else:
print("Invalid Input")
return inputParams(x, y)
except:
return inputParams(x, y)
The problem you're seeing comes from your test. Let's isolate it:
def f(x):
return x != 1 or x != 2
Presumably this should return True if x is not 1 or 2. Let's try it:
def test():
assert f(0)
assert not f(1)
assert not f(2)
assert f(3)
test() # oops!
Take another look at that test: x != 1 evaluates to True unless x is 1. x != 2 evaluates to True unless x is 2. If x is 2, the first test is True. If x is 1, the second test is True. Thus the code is actually running:
while True: ...
Then later on you check whether x is 1 or 2. A better test would be if x in {1, 2} or even if 1 <= x <= 2.
Then your recursion is muddling things even further, but you don't actually need recursion for this problem.

while loop not terminating on changing test condition [duplicate]

Switching from Unity JS to Python for a bit, and some of the finer points elude me as to why this does not work.
My best guess is that the variable guess is actually a string, so string 5 is not the same as integer 5?
Is this what is happening and either way how does one go about fixing this.
import random
import operator
ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a
def askQuestion(a):
guess = input("")
if guess == a:
print("Correct!")
else:
print("Wrong, the answer is",a)
askQuestion(generateQuestion())
Yes, you are absolutely right that "5" is distinct from 5. You can convert 5 into a string by using str(5). An alternative would be to convert "5" into an integer by int("5") but that option can fail, so better handle the exception.
So, the change to your program could be e.g. the following:
if guess == str(a):
instead of:
if guess == a:
Another option would be to convert guess into an integer, as explained in the other answer.
EDIT: This only applies to Python versions 2.x:
However, you're using input(), not raw_input(). input() returns an integer if you type an integer (and fails if you type text that isn't a valid Python expression). I tested your program and it asked What is 4 - 2?; I typed 2 and it sait Correct! so I don't see what is your problem.
Have you noticed that if your program asks What is 9 - 4? you can type 9 - 4 and it says Correct!? That's due to you using input(), not raw_input(). Similarly, if you type e.g. c, your program fails with NameError
I would however use raw_input() and then compare the answer to str(correct_answer)
I am assuming you are using python3.
The only problem with your code is that the value you get from input() is a string and not a integer. So you need to convert that.
string_input = input('Question?')
try:
integer_input = int(string_input)
except ValueError:
print('Please enter a valid number')
Now you have the input as a integer and you can compare it to a
Edited Code:
import random
import operator
ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a
def askQuestion(a):
# you get the user input, it will be a string. eg: "5"
guess = input("")
# now you need to get the integer
# the user can input everything but we cant convert everything to an integer so we use a try/except
try:
integer_input = int(guess)
except ValueError:
# if the user input was "this is a text" it would not be a valid number so the exception part is executed
print('Please enter a valid number')
# if the code in a function comes to a return it will end the function
return
if integer_input == a:
print("Correct!")
else:
print("Wrong, the answer is",a)
askQuestion(generateQuestion())

How do I check if a string is a negative number before passing it through int()?

I'm trying to write something that checks if a string is a number or a negative. If it's a number (positive or negative) it will passed through int(). Unfortunately isdigit() won't recognize it as a number when "-" is included.
This is what I have so far:
def contestTest():
# Neutral point for struggle/tug of war/contest
x = 0
while -5 < x < 5:
print "Type desired amount of damage."
print x
choice = raw_input("> ")
if choice.isdigit():
y = int(choice)
x += y
else:
print "Invalid input."
if -5 >= x:
print "x is low. Loss."
print x
elif 5 <= x:
print "x is high. Win."
print x
else:
print "Something went wrong."
print x
The only solution I can think of is some separate, convoluted series of statements that I might squirrel away in a separate function to make it look nicer. I'd be grateful for any help!
You can easily remove the characters from the left first, like so:
choice.lstrip('-+').isdigit()
However it would probably be better to handle exceptions from invalid input instead:
print x
while True:
choice = raw_input("> ")
try:
y = int(choice)
break
except ValueError:
print "Invalid input."
x += y
Instead of checking if you can convert the input to a number you can just try the conversion and do something else if it fails:
choice = raw_input("> ")
try:
y = int(choice)
x += y
except ValueError:
print "Invalid input."
You can solve this by using float(str). float should return an ValueError if it's not a number. If you're only dealing with integers you can use int(str)
So instead of doing
if choise.isdigit():
#operation
else:
#operation
You can try
try:
x = float(raw_input)
except ValueError:
print ("What you entered is not a number")
Feel free to replace float with int, and tell me if it works! I haven't tested it myself.
EDIT: I just saw this on Python's documentation as well (2.7.11) here
isn't this simpler?
def is_negative_int(value: str) -> bool:
"""
ref:
- https://www.kite.com/python/answers/how-to-check-if-a-string-represents-an-integer-in-python#:~:text=To%20check%20for%20positive%20integers,rest%20must%20represent%20an%20integer.
- https://stackoverflow.com/questions/37472361/how-do-i-check-if-a-string-is-a-negative-number-before-passing-it-through-int
"""
if value == "":
return False
is_positive_integer: bool = value.isdigit()
if is_positive_integer:
return True
else:
is_negative_integer: bool = value.startswith("-") and value[1:].isdigit()
is_integer: bool = is_positive_integer or is_negative_integer
return is_integer

Interactive input in python

Here is the directions for what I need to do:
You are to write a complete program that obtains three pieces of data and then process them. The three pieces of information are a Boolean value, a string, and an integer. The logic of the program is this: if the Boolean value is True, print out the string twice, once with double quotes and once without - otherwise print out twice the number.
Here is what I have so far:
def main():
Boolean = input("Give me a Boolean: ")
String = input("Give me a string: ")
Number = int(input("Give me a number: "))
Can anybody help me out?
On stackoverflow, we're here to help people solve problems, not to do your homework, as your question very likely sounds… That said, here is what you want:
def main():
Boolean = input("Give me a Boolean: ")
String = input("Give me a string: ")
Number = int(input("Give me a number: "))
if Boolean == "True":
print('"{s}"\n{s}'.format(s=String))
try:
print('{}\n{}'.format(int(Number)))
except ValueError as err:
print('Error you did not give a number: {}'.format(err))
if __name__ == "__main__":
main()
A few explanations:
Boolean is "True" checks whether the contained string is actually the word True, and returns True, False otherwise.
then the print(''.format()) builds the double string (separated by \n) using the string format.
finally, when converting the string Integer into an int using int(Integer), it will raise a ValueError exception that gets caught to display a nice message on error.
the if __name__ == "__main__": part is to enable your code to be only executed when ran as a script, not when imported as a library. That's the pythonic way of defining the program's entry point.
I like to add a bit of logic to ensure proper values when I do input.
My standard way is like this:
import ast
def GetInput(user_message, var_type = str):
while 1:
# ask the user for an input
str_input = input(user_message + ": ")
# you dont need to cast a string!
if var_type == str:
return str_input
else:
input_type = type(ast.literal_eval(str_input))
if var_type == input_type:
return ast.literal_eval(str_input)
else:
print("Invalid type! Try again!")
Then in your main you can do something like this!
def main():
my_bool = False
my_str = ""
my_num = 0
my_bool = GetInput("Give me a Boolean", type(my_bool))
my_str = GetInput("Give me a String", type(my_str))
my_num = GetInput("Give me a Integer", type(my_num))
if my_bool:
print('"{}"'.format(my_str))
print(my_str)
else:
print(my_num * 2)

Python Function variable: local and global

I am struggling with local and global variables.
I was doing this:
def SomeFunc(Input):
if Input == 1:
Input = "True"
elif Input == 0:
Input = "False"
RawInput=int(raw_input("Input 1 or 0: "))
SomeFunc(RawInput)
print str(RawInput)
and it showed this:
>>> def SomeFunc(Input):
if Input ==1:
Input = "True"
elif Input ==0:
Input = "False"
>>> RawInput = int(raw_input("Input 1 or 0: "))
Input 1 or 0: 1
>>> SomeFunc(RawInput)
>>> print str(RawInput)
1
What should I do so that the input will convert to str in the function?
Input is an int which is an immutable object. In other words, you can't change it anywhere. However, you can assign it to something else. One of the tricky things about python is learning that everything is just a reference. When you assign to something, you just change the reference. Think about your variables as strings which go into boxes. When you assign to a variable, you put that string in a particular box. When you assign that variable to something else, you change the box that string goes to. Of course, when you actually do an addition, you add the contents of the box, not the strings (which is a little confusing). If you're accustomed to programming in C, it's kind of like everything is a pointer which gets automatically dereferenced (except when you do an assignment).
So, what to do? The easiest thing is to return the value from your function.
def some_func(inpt):
if inpt == 1:
return "True"
elif inpt == 0:
return "False"
else:
raise ValueError("WHAT IS THIS GARBAGE? I SAID 0 OR 1!!!!") # ;^)
Now you can call your function as:
processed_input = some_func(rw_inpt)
as a side note, your function can be condensed to:
def some_func(inpt):
return str(bool(inpt))
or
def some_func(inpt):
return "True" if inpt else "False"
Both of these pass (and return "True" if the user puts in any integer that isn't 0). If you really want to force the user to not put in something like "2", you can do:
def some_func(inpt):
return {1:"True",0:"False"}[inpt]
But I wouldn't recommend that one...
Basically you want the argument to be pass-by-reference, but that is not how Python works for basic datatypes. The pythonic way of doing this is as following:
def some_func(input):
if input == 1:
return "True"
elif input == 0:
return "False"
And then
raw_input = some_func(raw_input)
Note: You can just do this: print bool(int(raw_input("Input 1 or 0: ")))
The more pythonic way of doing it would be as follows:
def some_func(x):
if x == 1:
return "True"
elif x == 0:
return "False"
x = int(raw_input("Input 1 or 0: "))
x = some_func(x)
print x
However if you did want to use globals you could do it like this but this is really hacky and it isn't one of the good coding practices that python promotes.
def some_func():
global x
if x == 1:
x = "True"
elif x == 0:
x = "False"
x = int(raw_input("Input 1 or 0: "))
some_func()
print x
Some other notes:
Try not to use names like the bultins eg. Input and RawInput since it makes things unclear and mixes everything up.
What should I do so that the input will convert to str in the
function?
def SomeFunc(Input):
as_string = str(Input)
if Input == '1':
Input = "True"
elif Input == '0':
Input = "False"
Note that python has a native boolean type, including the values True and False already. You can use the integer value of Input as a condition all on its own.

Categories