How to make if else work for python3 [duplicate] - python

This question already has answers here:
Differences between input commands in Python 2.x and 3.x
(2 answers)
Closed 6 years ago.
I have recently made the switch to Python 3 and regular things that usually work with Python 2 don't work with Python 3. I have been able to fix the rest but I am struggling with this one. I cannot check what "type" something is.
raw = input("Please give me a number, string\
or decimal: ")
if type(raw) == int:
print("You entered a number")
elif type(raw) == float:
print("You entered a decimal")
elif type(raw) == str:
print("You entered a string")
else:
print("error please try again")
`

In python3.x, input always returns an object of type str. The equivalent to python2.x would be eval(input('...')). As with using eval at any time, be sure that you absolutely trust that the input won't do malicious things to your program or computer...
A better way would be to use something like ast.literal_eval (which will safely evaluate your literals) or to do the checking yourself...
def is_int_str(s):
"""Checks if a string (s) represents a python integer."""
try:
int(s)
except ValueError:
return False
return True
And it's trivial to then write the analogous float version...

Related

Python: Help me, what am i doing wrong? [duplicate]

This question already has answers here:
String comparison in Python: is vs. == [duplicate]
(4 answers)
Closed 2 years ago.
I'm learning how to code and to start i want crate a command that when i write "Dio" for example it writes me "Error 404: dio non esiste" but it says that the code is wrong, what am i doing wrong? here's the code
name = int(input("Come ti chiami? "))
if name is "Antonio":
print("Eh no")
if name is "Dio":
print("Error 404: Dio non esiste")
if name is "Dio porco":
print("lol")
You have taken input of type int:
Instead just take :
name = input("Come ti chiami? ")
which would be string by default,
and use "==" to compare.
But if you have just started learning, I would suggest first go through the python documentation which would give you a basic understanding of how to write python codes.
is checks if two values are exactly the same reference. Since you're inputting one value from a user and the other is hard coded, they won't be the same reference. Instead, you should use the == operator. Additionally, if you're inputting a name, you shouldn't convert the input to an int:
name = input("Come ti chiami? ")
if name == "Antonio":
print("Eh no")
if name == "Dio":
print("Error 404: Dio non esiste")
if name == "Dio porco":
print("lol")

TypeError in if else statement [duplicate]

This question already has answers here:
How do you input integers using input in Python [duplicate]
(3 answers)
Closed 3 years ago.
I keep getting this error:
if AR_GCC<16 and AR_GCC>0:
TypeError: '<' not supported between instances of 'str' and 'int'
It is a program that is supposed to print the cancer risk according to the input of the user (not a real thing just for practice)
This is the piece of code that doesn't work:
AR_GCC=input("AR_GCC repeat copy number?")
if (AR_GCC>0 and AR_GCC<16):
risk="High risk"
elif (AR_GCC >= 16):
risk = "Medium risk"
else:
print("Invalid")
You need to make sure the input is interpreted as number. Simply adding int() before the input function should solve that. Of course if the value passed is a string, it will fail. Therefore your code should be:
AR_GCC=int(input("AR_GCC repeat copy number")) should do the trick. Sorry for formatting, typing from phone

Python 3.6.2 Equality Comparison with Boolean Literal [duplicate]

This question already has answers here:
Comparing True False confusion
(3 answers)
Closed 5 years ago.
As part of an assignment we've been asked to create a very basic/elementary program that asks for user input (whether they desire coffee or tea, the size, and whether they desire any flavourings), and then outputs the cost of the particular beverage, including their name and what they ordered, in addition to the cost. The code I wrote works perfectly; however, the only question I have is more for my own understanding. Our instructions for the customer's name were as follows: "The customer’s name – A string consisting of only upper and lower case letters; no
spaces (you may assume that only contains letters of the alphabet)."
Thus my code was as follows:
customerName = str(input('Please enter your name: '))
if customerName.isalpha() == False:
print('%s is an invalid name, please try again!' % customerName)
else:
And then I just continue from there - however, PyCharm is telling me "expression can be simplified - this inspection detects equality comparison with a boolean literal" regarding the
if customerName.isalpha() == False:
statement. What would be the best way to simplify this?
You can use the result of str.isalpha directly; it's a boolean!:
if not customerName.isalpha():
print('%s is an invalid name, please try again!' % customerName)

How can you get python to detect strings from integers [duplicate]

This question already has answers here:
How can I check if string input is a number?
(30 answers)
Closed 7 years ago.
In my program I need a hand in trying to get python to say that a input is invalid, the code asks for numbers, if you input a letter I would like it to say its invalid rather than breaking, is there any way I can do this?
Here is some code that works using a try/except block. The code attempts to convert the input into a number, if it succeeds it breaks out of the loop, if not the error is caught and an error message is printed, and then the loop starts again
passed = False
print "input a number"
while not passed:
a = raw_input()
try:
number = int(a)
passed = True
print "Number inputted"
except(ValueError):
print "You did not input a number, try again"

Python - And, OR validations [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Multiple if statements under one code, with multiple conditons [duplicate]
(3 answers)
Closed 8 years ago.
It is pretty self-explanitory from the code but I want to check if the input is not equal to these values than ask again. I thought this would work but it doesn't and its glitchy, what is a better way to do this?
type=input("Please choose an option: ")
while type.isalpha() == False:
type=input("Please choose an option: ")
while type != ("a" and "A" and "b" and "B" and "c" or "C"):
type=input("Please choose an option: ")
Simply do while not type in ("a","A","b","B" ...) to check whether type is one of the listed elements.
The code above is, as mentioned in comments, equivalent to while type != someListElement because the and and or are evaluated first.
You would need to write:
while (type != "a" and type !="A" and type !="b" and type !="B" and type !="c" or type !="C"):
I think the simplest solution would be to use
type = raw_input("Please choose an option: ")
while type not in list('AaBbCc'):
type = raw_input("Please choose an option: ")
list will convert from a string to a list of single-character strings, which you can then test for inclusion using in. I don't think you need the test for isalpha, because everything you're checking for is already a letter.
Also, you should always use raw_input rather than input to get user input, because raw_input always returns a string, while input tries to eval what the user enters, which is not what you want.
(This is assuming you're using Python 2. If you're using Python 3, input is what raw_input was before, and raw_input no longer exists.)

Categories