How to verify if input is not a letter or string? - python-3.x

I'm writing a basic program in IDLE with a menu choice with options from 1 to 4.
If a user input anything else then a number, it gives a ValueError: invalid literal for int() with base 10: 'a'
How can I check if the input is not a letter, and if it is, print a error message of my own?

def isNumber (value):
try:
floatval = float(value)
if floatval in (1,2,3,4):
return True
else:
return False
except:
return False
number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
while isNumber(number_choice) == False:
number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
else:
print('You have chosen ' + number_choice + '.\n')
This will check if the number is 1,2,3 or 4 and if not will ask the user to input the number again until it meets the criteria.

I am slightly unclear on whether you wish to test whether something is an integer or whether it is a letter, but I am responding to the former possibility.
user_response = input("Enter an integer: ")
try:
int(user_response)
is_int = True
except ValueError:
is_int = False
if is_int:
print("This is an integer! Yay!")
else:
print("Error. The value you entered is not an integer.")
I am fairly new to python, so there might very well be a better way of doing this, but that is how I have tested whether or not input values are integers in the past.

isalpha() - it is a string method which checks that whether a string entered is alphabet or words(only alphabets, no spaces or numeric) or not
while True:
user_response = input("Enter an integer : ")
if user_response.isalpha():
print("Error! The value entered is not an integer")
continue
else:
print("This is an integer! Yay!")
break
This program is having infinite loop i.e. until you enter an integer this program will not stop. I have used break and continue keyword for this.

Related

How do I continue looping, even through an error? Python

I have two conditions in my story using the question that I made to ask the users.
The first condition is true and second condition is false. In the first condition, if it's true, I want the program to finish. In the second condition, if it's false, I want to loop back to the question that I asked.
I have the following code, but so far it will loop back if the first is true and the second is false.
Any ideas?
invalid = ValueError
def age():
user_input = input("Enter your Age")
try:
val = int(user_input)
print("Input is an integer number. Number = ", val)
except ValueError:
print("No.. input is not a number. It's a string")
while invalid:
age()
I'd make things easier and just use a boolean as your continuation flag, rather than the ValueError:
ask_again = True
def age():
user_input = input("Enter your Age")
try:
val = int(user_input)
print("Input is an integer number. Number = ", val)
ask_again = False
except ValueError:
print("No.. input is not a number. It's a string")
while ask_again:
age()
Does that look like what you want? Happy Coding!
The simplest way to execute a while loop is to just use while True and then break from the loop once the condition is satisfied
def age():
while True:
try:
val = int(input("Enter your Age"))
print("Input is an integer number. Number = ", val)
break
except ValueError:
print("No.. input is not a number. It's a string")
age()

User validation loop for binary input is not recognising input

new to programming, but I'm working on a binary to decimal converter and I'm trying to make sure that the only input is either a '0' or '1' and not alpha, and not empty ''.
I have figured out logic for not empty and not alpha input , but I can't figure out the logic for the last condition - if 1 not in string or 0 not in string. It works if I enter either 1 or zero, but this isn't what i'm looking. I just want to check that there is only 1's or 0's and then proceed with the rest of the program.
I've spent hours on just this today so any help is appreciated. :)
Thanks in advance :)
def convert_to_decimal(binary_number):
print('\n')
#The binary input to be converted, entered as a string.
binary = input('Please enter binary numbera: ')
while binary.isalpha() or binary == '':
print("Please make sure your number contains digits 0-1 only.a ")
binary = input('Please enter numberb: ')
while binary not in '1' and binary not in '0':
print("Please make sure your number contains digits 0-1 only.x ")
binary = input('Please enter numberc: ')
Here I reworked it a little and its a bit inefficient, but here it is. It is a bit self-explanatory, but basically how it works, is it iterates over the inputString, and checks if each number is a 1 or 0 if not, the continue to ask, otherwise continue.
def isBinary(stringNum):
if len(stringNum) ==0:
return False
for chr in stringNum:
if chr != "0" and chr != "1":
return False
return True
def convert_to_decimal():
print('\n')
#The binary input to be converted, entered as a string.
binary = input('Please enter binary number: ')
while not isBinary(binary):
binary = input('Please enter binary number: ')
The reason yours doesn't work is you say if not in 1 and not in 0, which is wrong. in in this case returns True if the WHOLE string is in the target("0"). Since "10" isn't completely in 1 or in 0, it will ask you again, so you can see why that wouldn't work.
I hate myself for finding the answer, but it works :)
def convert_to_decimal(binary_number):
print('\n')
#The binary input to be converted, entered as a string.
binary = input('Please enter binary numbera: ')
while binary.isalpha() or binary == '':
print("Please make sure your number contains digits 0-1 only.a ")
binary = input('Please enter numberb: ')
while not binary.startswith('0') and not binary.startswith('1'):
print("Please make sure your number contains digits 0-1 only.x ")
binary = input('Please enter numberc: ')

Python3 if if else

When i do this in this way
x = "Hello"
if len(x) <= 9:
print("The password must contain at least 9 letters")
if x[0].islower():
print("The first password letter must be uppercase")
else:
print("Password saved")
password = x
i getting
>The password must contain at least 9 letters
>Password saved
What should I do to make the program stop on:
>The password must contain at least 9 letters
Use elif between if and else:
x = "Hello"
if len(x) <= 9:
print("The password must contain at least 9 letters")
elif x[0].islower():
print("The first password letter must be uppercase")
else:
print("Password saved")
password = x
elif is executed only when if wasn't executed, and elif's condition is true. You can also chain as many elifs as you want, in which case the first elif whose condition matches is executed.
Update: Since OP said in comments that he wants all errors to be shown at once, I would use something like this:
x = "Hello"
errors = []
if len(x) <= 9:
errors.append("The password must contain at least 9 letters")
if x[0].islower():
errors.append("The first password letter must be uppercase")
if errors:
print('\n'.join(errors))
else:
print("Password saved")
password = x
The problem is that you have two if filters in the code. I'm assuming you want the structure where both "The password must contain at least 9 letters" and "The first password letter must be uppercase"can be returned if both their conditions are met.
If, however, you don't need this capability, simply replace the second if with an elif and it should work.
If you need this capability, try something like:
x = "Hello"
if len(x) <= 9:
print("The password must contain at least 9 letters")
if x[0].islower():
print("The first password letter must be uppercase")
if len(x) >= 9 and x[0].isupper():
print("Password saved")
password = x
This simply adds a third if statement testing that the previous conditions were fulfilled.

Python -Need to match DNA from 2 inputs

Currently working on a project to do the following:
Ask user to enter a first strand of dna
Checks to make sure that the strand is valid (A,C,T and G, lower case is also accepted).
After first strand is entered, the program asks for the second strand and checks if is
complementary
A is Complementary of T, T to A. and G is complementary with C and C to G.
Result should be:
Enter first sequence of dna: ATGC
Enter second sequence of dna:TACG
"They are Complementary"
Enter first sequence of dna: GTC
Enter second sequence of dna:GAC
not complementary.
Enter second sequence of dna: exit
exiting program.....
#Code starts here:
def compare_DNA_lenght(dna1,dna2):
if len(dna1) != len(dna2):
print ('Input sequence incorrect')
def complement(sequence):
""" (str) -> str"""
replace={'a':'t','t':'a','c':'g','g':'c'}
complement=''
print('in the loop',sequence)
for i in sequence:
complement=complement+replace[i]
print(sequence)
while (dna1 != "exit" and dna2 != "exit"):
dna1= input('Please enter your first sequence:')
dna2= input('Please enter your second sequence:')
dna1=dna1.lower()
dna2=dna2.lower()
if (dna1 =="exit" and dna2 =="exit"):
print ("Exiting program")
if(dna2 == complement):
print ("They are complementary")
elif(dna2 != complement):
print ("Not a complementary strand")
print (complement)
You should read up on how while loops work in Python. In the meantime, here's the basic structure of one:
while condition:
code
Keep in mind that you should always make sure that condition will eventually evaluate to false, otherwise you'll end up in an infinite loop, causing your program to hang. A simple example would be printing the numbers 1 through 5:
i = 1
while (i <= 5):
print(i)
i = i + 1
Eventually, i is 6, so the while loop will not execute the code inside, because 6 is not equal to or less than 5.
Before your while loop, you need to declare your dna1 and dna2 variables so your program doesn't throw an error saying it can't find those variables.
dna1= input('Please enter your first sequence:')
dna2= input('Please enter your second sequence:')
while (dna1 != "exit" and dna2 != "exit"):
Additionally, you don't need to check if both strings say "exit" to break out of the loop. Just one should suffice.
if (dna1 =="exit" or dna2 =="exit"):
On an unrelated note, it's considered good practice to spell your method names correctly. "compare_DNA_lenght" should probably be "compare_DNA_length".
Check valid DNA strand
So the first thing you need to do is to check whether or not the used input is a valid DNA. Since a DNA only contains A,T,G and C we can check the validity by creating a formula that checks for A,T,G and C. True if these are present and False if any letters other than A,T,G and C.
def is_dna_strand(x):
"""
(str) -> bool
Returns True if the DNA strand entered contains only the DNA bases.
>>> is_dna_strand("AGTC")
'True'
>>> is_dna_strand("AGHFJ")
'False'
"""
a=x.lower()
i=0
while i != (len(a)):
if ((a[i])!= "a") and ((a[i])!="t")and((a[i])!="c")and((a[i])!="g"):
return False
i+=1
return True
Check the base pairs
def is_base_pair(x,y):
"""
(str,str) -> bool
Returs true if two parameters form a base pair.
>>> is_base_pair("A","T")
'True'
>>> is_base_pair("A","G")
'False'
"""
a=x.lower()
b=y.lower()
if a=="a" and b=="t":
return True
elif a=="t" and b=="a":
return True
elif a=="c" and b=="g":
return True
elif a=="g" and b=="c":
return True
else:
return False
Check whether it's a valid DNA or not.
So the final step in this process is check the validity of the entire molecule.
def is_dna(x,y):
"""
(str,str) -> bool
Returs true if the two strands form a properly base-paired DNA.
>>> is_dna("AAGTC","TTCAG")
'True'
>>> is_dna("TCGA","TCAG")
'False'
"""
i=0
j=0
if len(x)==len(y):
while i < (len(x)):
b=x[i]
c=y[i]
i=i+1
return is_base_pair(b,c)
else:
return False

showing result of try except integer check as a string

I need a function to check that different user input variables are integers.
The results should be confirmed to the user at the end.
The check works in that it keeps looping until integer is typed in,
but cannot get the results to display...
def chkint(msg):
while True:
try:
n = input(msg)
return(int(n))
except ValueError:
print("Please enter an actual integer.")
number1 = input (chkint("Please enter first value:"))
number2 = input (chkint("Please enter second value:"))
results = (number1, number2)
print ("I have accepted: " + str (results))
No answer, so I just played about with this and hey presto, it works...
def chkint(msg):
while 1:
try:
n = input(msg)
return(int(n))
except ValueError:
print("Please enter an integer.")
number1 = chkint("Please enter first value:")
number2 = chkint("Please enter second value:")
results = [number1, number2]
print ("I have accepted: " + str (results))
Casting it to int() in a try: block is a good way to check a number. In your original attempt you were asking for an input whose message relied on further input.
Simplified version of the mistake:
def getMessage():
return input() # this asks the user what to ask the user for
input(getMessage()) # this waits for getmessage to finish before asking the user
Removing the input() statements was the easiest fix, as you did.
But a more readable fix would be to make chkint(msg) do nothing but return true or false based on whether or not the string was a number, like this
def chkint(msg): # returns true if the string can be converted, false otherwise
try:
int(msg)
except ValueError:
return False
return True

Resources