Code not checking values in list? - python

This program I am trying to build needs to check if the user's input corresponds to values in a list. Here is the code I have:
def find_val(val, seq):
for ele in seq:
if val == ele:
return True
return False
def get_input(possible_vals, day_or_time_string):
if day_or_time_string == "day":
answer = input("What day would you like your appointment? ")
else:
answer = input("What time would you like your appointment? ")
answer = answer.strip()
valid_entry = find_val(answer, possible_vals)
if valid_entry == True:
count = 0
while False:
second_answer = input("Invalid entry. Please enter a valid day: ")
count = count + 1
if count == 3:
print("This is getting silly - still not a valid entry")
if second_answer in possible_vals:
return second_answer
else:
return answer
day_list = ["Monday", "Tuesday", "Wednesday"]
res = get_input( day_list, "day" )
print("The funtion returned", res)
This is the type of output I should be getting:
What day would you like your appointment? saturday
Invaild entry. Please enter a valid day: Monday
The funtion returned Monday
However, it seems that no matter what I input, the function returns it, and doesn't check if the input matches a string in the list:
What day would you like your appointment? akw
The function returned akw
What is wrong with my code that isn't allowing the user's input to be checked whether or not it is in the list day_list?

First
valid_entry = find_val(answer, possible_vals)
if valid_entry == True:
can be simplified to
if answer in possible_vals:
(your find_val function is totally unnecessary)
Then your problem is that
while False:
...
simply never executes... Did you mean while True? If so You'll need to somehow break out this (now) infinite loop using a break statement for example.
And finally as A.G. suggests, you explicitly tell your program to return answer when it's not "valid" so why do you expect otherwise?

Related

python check user input is day of the week

I am attempting to define a function that asks the user which days of the week they are available. I need their input to be saved into a list for future use. I want to ensure they are entering the day of the week properly and that it is in the correct format. I have tried various ways but cannot seem to get it to work correctly.
Here is what I have so far:
daysWeek = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]
def daysInput(message):
print(daysWeek)
z = False
while z == False:
i = list(input(message).strip().title().replace(",", " ").split(" "))
print(i)
varify = 0
for day in i:
for dow in daysWeek:
if day == dow:
varify += 1
else:
varify = 0
if varify == 0:
print("Invalid entry")
else:
z = True
return i
When varify += 1 is executed, and a next iteration executes, varify is set back to 0 even though the input day had matched with a correct day in the previous iteration. That means that unless you enter only the last day (Sun), the input will be rejected.
Secondly, if a day is found, and the next day from the input is checked, you'll destroy the previous result, by clearing varify again, even though a match will be found in a next iteration.
You need to implement the logic that for all inputs, some day of the week should match with it. You can do this a lot easier with the all function and the in operator:
daysWeek = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]
def daysInput(message):
print(daysWeek)
while True:
inp = list(input(message).strip().title().replace(",", " ").split(" "))
print(inp)
if all(day in daysWeek for day in inp):
return inp
print("Invalid entry")
daysInput("Enter some days of the week: ")

A TypeError prevents me from forming the conditionals of my function (Python)

The function is supposed to receive a number representing a year, and then print if it's a leap year or not.
def isItALeapYear(year):
while True:
if year % 4 == 0:
print("That is a leap year! ")
break
elif year % 4 != 0:
print("That is not a leap year...")
break
elif not isinstance(year, int) or year == None:
print("Please enter a number...")
break
The program works, the only thing I can't get right is that it is supposed to notify you if anything that it's not a number is being used as an argument. I've tried both the isinstance() function, as well as writing what I want as year != int. And then year == None in the hopes of making it work in case anything nondefined is used as an argument.
I read this post with the exact same error: TypeError: not all arguments converted during string formatting python
But I'm not intending to format anything with the % symbol
As far as I'm concerned the % can be used as an operand to get the residue of a division.
So in this case I'm using it to figure out if a year is a leap year or not by asking if the residue is 0 when divided by 4. I'm pretty stuck, and the sad thing is the error comes up in the very first "if", so I can't really know if the last lines for excluding any non int type argument work or not. Any help would be really appreciated!
You could use the isleap() function from the standard library (module calendar):
from calendar import isleap
def isItALeapYear(year):
if not isinstance(year, int):
print("Please provide a number")
elif isleap(year):
print("That is a leap year!")
else:
print("That is not a leap year...")
I recommend to divide the functionality of checking the number from returning the output as well as from receiving the input.
def is_multiple_of_four(number: int):
if number % 4 == 0:
return True
else:
return False
if __name__ == '__main__':
user_input = ""
while not user_input.isdigit():
user_input = input("Please type in a year: ")
if is_multiple_of_four(int(user_input)):
print("That is a leap year!")
else:
print("That is not a leap year.")
Here you can see the function that checks the number does only that, it checks the number if it's modulo of 4 equals 0.
In the script outside the function you can retrieve the user input for as long as it takes to get a valid numeric and return the output in respect of the functions results.
Edit (adding clarification asked in the comments)
The first condition if __name__ == '__main__' is quiet common in python. It's not necessary for your function, but I like using it in answers if people seem to learn Python, so they don't miss out on it. Here is a question with a good answer: What does if __name__ == "__main__": do?
The short answer in the accepted answer is enough to understand why you might want to use it.
The second condition
user_input = ""
while not user_input.isdigit():
first defines a variable user_input with an arbitrary non-digit String value and than uses the negated isdigit() method of the String class on it as condition. Therefor the while loop gets entered in the beginning, as the arbitrary value is not an digit. From then on the value will be re-assigned with user input until it holds an actual digit. This digit is still a String however.
First thing while loop in the function makes no sense you can remove it(If you want).
There are multiple ways to do that I will show.
First One.
def isItALeapYear(year):
if type(year) != int:
return # here return to exit the function
while True:
if year % 4 == 0:
print("That is a leap year! ")
break
elif year % 4 != 0:
print("That is not a leap year...")
break
elif not isinstance(year, int) or year == None:
print("Please enter a number...")
break
Another is.
def isItALeapYear(year):
try:
int(year)
except ValueError: # this line of code executes when the year is not the int
return # here return to exit the function
while True:
if year % 4 == 0:
print("That is a leap year! ")
break
elif year % 4 != 0:
print("That is not a leap year...")
break
elif not isinstance(year, int) or year == None:
print("Please enter a number...")
break
I know there are more ways to do that but these are the best ones (I Think).
Your function is not accurate then you can use this one.
def isItALeapYear(year):
if type(year) != int:
return
if (( year%400 == 0)or (( year%4 == 0 ) and ( year%100 != 0))):
print(f"{year} is a Leap Year")
else:
print(f"{year} is Not the Leap Year")
Edit For Quetioner
def isItALeapYear(year):
if type(year) != int:
return
if (( year%400 == 0)or (( year%4 == 0 ) and ( year%100 != 0))):
print(f"{year} is a Leap Year")
else:
print(f"{year} is Not the Leap Year")
try:
isItALeapYear(asdasd)
except NameError:
print("You give the wrong Value")

Break out of while True loop with function

So I have a while true loop -
while True:
getStatus()
print('Ended')
I hope to be able to break out of it if answer is 999. this is what I tried:
def getStatus():
answer = input('What is the box ID? ')
if answer == 999:
return False
elif type(answer) == int:
boxId = answer + 1
print(boxId)
However even when the input is '999' it loops back and asks 'What is the box ID? ' again.
How do I get out of the while true loop?
Your while loop keeps looping because that's exactly what you've told it to do. After the function you call from its body returns, you ignore the return value, unconditionally print "Ended" and then do it all again, since the condition on the loop is obviously still truthy.
If you want the function to control if the loop keeps going, you should use its return value as the condition in the loop, with something like this:
running = True
while running:
running = getStatus()
print("Ended") # move this outside the loop!
This requires that getStatus returns a truthy value when you want to keep looping and a falsey value when you want to stop. Your current implementation of that function doesn't do that. It returns False when 999 is entered, but doesn't explicitly return anything if you give other input (which in Python is equivalent to returning None). Since both False and None are falsey, the code above won't actually work (you could patch it with something like running = getStatus() is None, but that would be horrible). You should change the function to have an explicit return statement in all of its branches (including the case for non-integer inputs, where it doesn't go into either your if or elif blocks).
If the loop and the function's logic are tightly intertwined, it might make sense to move the loop into the function itself, rather than having it be separate and needing to use a return value to signal when to stop. In a single function, you can use break to exit a loop directly:
def getStatus():
while True:
answer = input('What is the box ID? ')
if answer == 999:
break
elif isinstance(answer, int): # isinsance() is better than type(...) == ...
boxId = answer + 1
print(boxId)
else:
print("I'm sorry, I didn't understand that.") # still good to handle this case
you can add if statement before get_status() that will check if it's true and break and in the get_status function you will have to return true to break
def getStatus():
answer = input('What is the box ID? ')
if answer == 999:
return True
elif type(answer) == int:
boxId = answer + 1
print(boxId)
while True:
if getStatus():
print('Ended')
break
def selectedCountry():
while True:
country = input("Enter country of which you want to check pictures HR, RS, RO: ").upper()
if country == str("HR") or country == str("RO") or country == str("RS"):
break
else:
print("Please enter HR or RO or RS: " + "you wrote: " + country)
Why while True is working outside of a function and inside the same problem with asking again
Enter country of which you want to check pictures HR, RS, RO: >? hr
Enter country of which you want to check pictures HR, RS, RO:
You may change it to -
while True:
if(getStatus()==False):
print('Ended')
break
By this you can use returned value to break out of infinite loop.

How to find the mean of a list

I'm very new to python and trying to write some code so that the user enters something. If it's an integer it's sorted into the Numbers list, if it's a string it goes into the String list.
I want to be able to find the mean of all the numbers that are in the list and print out the result.
And in the String section I want to be able to print out everything within the string and its length.
User types 'save' to exit and if input is valid that's caught.
Numbers = []
String = []
while(True):
user_input = input("What's your input? ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(user_input)
for i in range(len(Numbers)):
Numbers[i] = int(Numbers[i])
print(sum(Numbers)/len(Numbers)
elif isinstance(user_input, str):
String.append(user_input)
print(String)
print (len(String)-1)
else:
print("Invalid input.")
break
#use isalpha to check enterted input is string or not
#isalpha returns a boolean value
Numbers = []
String = []
while(True):
user_input = input("input : ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(int(user_input))
print(sum(Numbers)/len(Numbers))
elif user_input.isalpha():
String.append(user_input)
print(String)
print (len(String))
else:
print("Invalid input.")
break
There is good thing called statistics.mean:
from statistics import mean
mean(your_list)
You are using Length, which has not been defined. I think what you wanted was
print(sum(Numbers)/len(Numbers))
and you probably don't want it inside the loop, but just after it (although that might be another typo).
I found other more convenient way to produce the mean: Use statistics model and output the mean.
#import useful packages
import statistics
#Create an empty list
user_list = []
#get user request
user_input = input("Welcome to the average game. The computer is clever enough to get the average of the list of numbers you give. Please press enter to have a try.")
#game start
while True:
#user will input their number into a the empty list
user_number = input("Type the number you want to input or type 'a' to get the average and quit the game:")
#help the user to get an average number
if user_number == 'a':
num_average = statistics.mean(user_list)
print("The mean is: {}.".format(num_average))
break #Game break
else:
user_list.append(int(user_number))
print(user_list)

inconsistent string to int error and response

I've made a simple program where the users adds as many numbers as they would like then type 'exit' to stop it and print the total but sometimes it says the converting the string to int fails, and sometimes it does convert but then it has the wrong out put e.g I type 1 + 1 but it prints 1
def addition():
x = 0
y = 1
total = 0
while x < y:
total += int(input())
if input() == "exit":
x += 1
print(total)
addition()
I have tryed converting it to a float then to an int but still has inconsistency, I did start learning python today and am finding the syntax hard coming from c++ / c# / Java so please go easy on the errors
Maybe this is what you are looking for:
def addition():
total = 0
while True:
value = input()
if value == "exit":
break
else:
try:
total += int(value)
except:
print('Please enter in a valid integer')
print(total)
EDIT
There are two reasons why the code isn't working properly:
First, the reason why it is failing is because you are trying to cast the word "exit" as an integer.
Second, as user2357112 pointed out, there are two input calls. The second input call was unintentionally skipping every other number being entered in. All you needed to do was one input call and set the entered value into a variable.
You can break the while loop, without using x and y.
def addition():
total = 0
while True:
total += int(input())
if input() == "exit":
break
print(total)
addition()
These are a few ways you can improve your code:
Run the loop forever and break out of it only if the user enters "exit"
To know when the user entered "exit" check if the input has alphabets with isalpha()
Making the above changes:
def addition():
total = 0
while True:
user_input = input()
if user_input.strip().isalpha() and user_input.strip() == 'exit':
break
total += int(user_input)
print(total)
addition()
def safe_float(val):
''' always return a float '''
try:
return float(val)
except ValueError:
return 0.0
def getIntOrQuit():
resp = input("Enter a number or (q)uit:")
if resp == "Q":
return None
return safe_float(resp)
print( sum(iter(getIntOrQuit,None)) )
is another way to do what you want :P

Categories

Resources