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)
Related
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")
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
This question already has answers here:
Case insensitive 'in'
(11 answers)
Closed 6 years ago.
I'm a little confused regarding a Python exercise that requires a case insensitive input.
This part of the excercise that confuses me:
Make sure your comparison is case insensitive. If 'John' has been used, 'JOHN' should not be accepted.
Here is my code:
current_users = ['username_1', 'username_2', 'username_3', 'username_4',
'username_5']
new_user = ['new_user_1', 'new_user_2', 'new_user_3', 'username_1', 'Username_2']
for username in new_user:
if username in current_users:
print("Please enter a new username.")
elif username not in current_users:
print("This username is available.")
My problem is that I'm trying to get my code to reject "Username_2" because of the capital "U" but I have no idea how to do this. I'm reading through Python Crash Course by Eric Matthes and am currently on chapter 5 but I don't recall being taught how to reject case insensitive inputs yet.
I know of the upper(), lower(), and title() string methods and I tried using:
username.lower() == username.upper()
new_user.lower() == new_user.upper()
before my for loop, but this just results in a syntax error.
You can convert each new username to lower case and compare it to a lower case version of the user list (created using a list comprehension).
lower_case_users = [user.lower() for user in current_users]
if new_user.lower() in lower_case_users:
# Name clash
You may want to store your usernames in lowercase when they are first created to avoid creating a lower case version from the user list.
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...
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.)