Confused with Def Python - python

def yesno(endwhat):
end = False
while not end:
ok = input("<Y/N>")
if ok.upper == 'Y' or ok.upper == 'N':
if ok.upper == 'Y':
end = True
endwhat = True
else:
print("Enter only <Y/N>")
return(ok)
This Doesn't Work, It Just Repeats even when I put Y or N.
I think the problem is when I enter a var in 'endwhat' it doesn't change it to True.
Any Help is Truly Appreciated.
Thanks...

You forgot to put () to string function.
def yesno(endwhat):
end = False
while not end:
ok = input("<Y/N>")
if ok.upper() == 'Y' or ok.upper() == 'N':
if ok.upper() == 'Y':
end = True
endwhat = True
else:
print("Enter only <Y/N>")
return(ok)

.upper() is a function, and all functions must contain a '()' for any parameters(if there are any). Otherwise they are taken to be default values mentioned. you have forgotten to put '()'. the right version would be-
def yesno(endwhat):
end = False
while not end:
ok = input("<Y/N>")
if ok.upper() == 'Y' or ok.upper() == 'N':
if ok.upper() == 'Y':
end = True
endwhat = True
else:
print("Enter only <Y/N>")
return(ok)

You forgot () for upper.
You can also use the code as following:
def yesno(endwhat):
end = False
while not end:
ok = input("<Y/N>").upper()
if ok == 'Y' or ok == 'N':
if ok == 'Y':
end = True
endwhat = True
else:
print("Enter only <Y/N>")
return(ok)

Related

Python if elif and else statement not working

I'm trying to write a short-ish script to entertain myself and potentially others. When I run it it tends to just skip over the if elif and else statements.
import random
adventure = ["fantasy" , "sci-fi" , "pirate" , "pre-history"]
setting = ["ocean", "forest" , "desert" , "castle"]
while True:
adven = []
setti = []
random.shuffle(adventure)
random.shuffle(setting)
adven.append(adventure[0])
setti.append(setting[0])
print(adven)
print(setti)
accept = input("Is this acceptable? ")
if accept == "y" :
print("Great, let us get started!")
break
else :
print("I am so sorry, lets try again!")
adve = []
sett = []
adve.append(adven)
sett.append(setti)
if adve == "fantasy" :
if sett == "ocean" :
print("1")
elif sett == "forest" :
print("2")
elif sett == "desert" :
print("3")
elif sett == "castle" :
print("4")
if adve == "sci-fi" :
if sett == "ocean" :
print("5")
elif sett == "forest" :
print("6")
elif sett == "desert" :
print("7")
elif sett == "castle" :
print("8")
if adve == "pirate" :
if sett == "ocean" :
print("9")
elif sett == "forest" :
print("10")
elif sett == "desert" :
print("11")
elif sett == "castle" :
print("12")
if adve == "pre-history" :
if sett == "ocean" :
print("13")
elif sett == "forest" :
print("14")
elif sett == "desert" :
print("15")
elif sett == "castle" :
print("16")
print(adve)
print(sett)
Would I need to keep it in the while True loop? I am not sure what to do because I want to make sure it works before I get any real details written into the script.
Try in. As in:
if "fantasy" in advve:
Will likely work better for you than == here.
Why? Because you're testing if a string is in a list of strings.
Don't forget to swap your operands around. Unlike == in cares which comes first.
As I understand, you would like to have multiple values in adven and setti, that's why it is a list?
So, firstly, you should take the definition of these values outside of loop scope:
adven = []
setti = []
while True:
...
You are appending list to list, so you getting list in list.
adve = []
adve.append(["random", "stuff"])
print(adve)
# [['random', 'stuff']]
Comparing a list to a string is always false because you compare different types of values.
print(adve == "random")
# False
print(["random"] == "random")
# False
To fix it you should:
# adve.append(adven)
adve = adven.copy() # or simply `adve = adven`, or just use adven instead adve.
print(adve)
# ['random', 'stuff']
And:
# adve == "random"
print("random" in adve)
# True
Btw, you should use pop() function so you wouldn't get duplicates:
# adven.append(adventure[0])
# setti.append(setting[0])
adven.append(adventure.pop())
setti.append(setting.pop())
If I misunderstood, and you don't need to handle multiple values for adven and setti, then your code should looks like this:
import random
adventure = ["fantasy", "sci-fi", "pirate", "pre-history"]
setting = ["ocean", "forest", "desert", "castle"]
while True:
random.shuffle(adventure)
random.shuffle(setting)
adven = adventure[0]
setti = setting[0]
print(adven)
print(setti)
accept = input("Is this acceptable? ")
if accept == "y":
print("Great, let us get started!")
break
else:
print("I am so sorry, lets try again!")
adve = adven
sett = setti
multiplier = 0
if adve == "fantasy":
multiplier = 1
elif adve == "sci-fi":
multiplier = 2
elif adve == "pirate":
multiplier = 3
elif adve == "pre-history":
multiplier = 4
else:
print(f"issue with adve: {adve}")
if sett == "ocean":
print(multiplier * 1)
elif sett == "forest":
print(multiplier * 2)
elif sett == "desert":
print(multiplier * 3)
elif sett == "castle":
print(multiplier * 4)
print(adve)
print(sett)

CS50P PSETS 2, Vanity plates

I'm having some issues with the psets 2 of cs50p, precisely I'm talking about the "Vanity Plates" problem, where I fulfilled all requests except one, which said:
“Numbers cannot be used in the middle of a plate; they must come at the end. For example, AAA222 would be an acceptable … vanity plate; AAA22A would not be acceptable. The first number used cannot be a ‘0’.” Can you help me? Thank's
this is the code I wrote so far:
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if s.isalnum() | s[:2].isalpha() | 2 < len(s) < 6 | :
else:
return False
main()
you have to consider all the cases one by one, this is how I solved it:
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if len(s) < 2 or len(s) > 6:
return False
elif not s[0].isalpha() or not s[1].isalpha():
return False
elif checkFirstZero(s):
return False
elif checkMiddleZero(s):
return False
elif last(s):
return False
elif worng(s):
return False
return True
def last(s):
isAlp = False
isNum = False
for w in s:
if not w.isalpha():
isNum = True
else:
if isNum:
return True
return False
def checkCuntuNNumber(s):
isFirstTry = True
isNum = False
for w in s:
if not w.isalpha():
if isFirstTry:
isNum = True
isFirstTry = False
if isNum and s[-1].isalpha():
return True
def checkMiddleZero(s):
isFirstTry = True
isNum = False
for w in s:
if not w.isalpha():
if isFirstTry:
isNum = True
isFirstTry = False
if isNum and s[-1].isalpha():
return True
else:
return False
def checkFirstZero(s):
for w in s:
if not w.isalpha():
if int(w) == 0:
return True
else:
return False
def worng(s):
for w in s:
if w in [" ", ".", ","]:
return True
return False
main()
This is how I did it. I am sure there is an easier way to do it out there but hopefully this helps :)
characters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
numbers = ['1','2','3','4','5','6','7','8','9','0']
def main ():
plate = (input ("Plate: ")).upper()
if is_valid(plate):
print ('Valid')
else:
print ('Invalid')
def is_valid (s):
#Check whether length is between 2 and 6 included
if len(s) < 2 or len(s) > 6:
return False
elif char_check(s):
return False
elif char_start(s):
return False
elif zero_check(s):
return False
elif alpha_follow_check (s):
return False
else:
return True
#Check for valid characters
def char_check(s):
for i in s:
if not (i in characters or i in numbers):
return True
#Check whether first two are letters
def char_start (s):
for i in s[:2]:
if not i in characters:
return True
#Check if zero is first number listed
def zero_check (plate_response):
length_string = len (plate_response)
letter_position = 0
number_present = 0
zero_position = None
if any (i in numbers for i in plate_response):
for i in plate_response [0:length_string]:
if i == '0':
zero_position = letter_position
break
letter_position = letter_position + 1
for i in plate_response [0:zero_position]:
if i in numbers:
number_present = 1
if number_present == 0:
return True
else:
return False
#Check alphabet follows numbers
def alpha_follow_check (plate_response):
length_string = len (plate_response)
letter_position = 0
number_position = None
if any (i in numbers for i in plate_response):
for i in plate_response [0:length_string]:
if i in numbers:
number_position = letter_position
break
letter_position = letter_position + 1
for i in plate_response [number_position:length_string]:
if i in characters:
return True
else:
return False
main ()
idk if will help, but the part that i've had the most difficulty in this problem was: "Numbers cannot be used in the middle of a plate; they must come at the end, AAA22A would not be acceptable", then i learned that you can create a full list from the plate that the user inputed, and how to actually use it, with the:
ls = list(s)
for i in range(len(ls)):
After that, we check when the first number appears. "if == '0'" ,then returns False to the function.
After that, if the first number isn't a 0, the program checks if the next item in that list is letter, and, if it is, also return False.
i < len(ls) -1 => this part guarantee that the program will not run in the last item of the list
ls[i+1].isalpha() => and this part check that, if the item on the list was a number, and then the next item is a letter, it returns False
I hope it helps someone, i've spend a lot of time trying to figure it out what to do, and then reached this solution: "for i in range(len(ls))".
Now my code is complete and working.
My code:
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if not s.isalnum():
return False
elif len(s) < 4 or len(s) > 7:
return False
elif s[0].isdigit()or s[1].isdigit():
return False
elif s[-1].isalpha() or s[-2].isalpha():
return False
else:
ls = list(s)
for i in range(len(ls)):
if ls[i].isdigit():
if ls[i] == '0':
return False
elif i < len(ls) -1 and ls[i+1].isalpha():
return False
else:
return True
main()

I need to modify the function so the user input references the two different dictionaries

from random import *
easy_glossary = {'word1':'definition1',
'word2':'definition2',
'word3':'definition3'}
hard_glossary = {'word4':'definition4',
'word5':'definition5',
'word6':'definition6'}
def show_flashcard():
random_key = choice(list(glossary))
print('Define: ', random_key)
input('Press return to see the definition')
print(glossary[random_key])
exit = False
while not exit:
user_input = input('Enter e to show an easy flashcard, h for hard and q to quit: ')
if user_input == 'e':
show_flashcard()
elif user_input == 'h':
show_flashcard()
elif user_input == 'q':
exit = True
else:
print('You need to enter either e, h or q.')
You might be able to try something like this
from random import *
easy_glossary = {'word1':'definition1',
'word2':'definition2',
'word3':'definition3'}
hard_glossary = {'word4':'definition4',
'word5':'definition5',
'word6':'definition6'}
def show_flashcard(flashcard_type):
if flashcard_type == 'e':
glossary = easy_glossary
if flashcard_type == 'h':
glossary = hard_glossary
random_key = choice(list(glossary))
print('Define: ', random_key)
input('Press return to see the definition')
print(glossary[random_key])
exit = False
while not exit:
user_input = input('Enter e to show an easy flashcard, h for hard and q to quit: ')
if user_input == 'e':
show_flashcard('e')
elif user_input == 'h':
show_flashcard('h')
elif user_input == 'q':
exit = True
else:
print('You need to enter either e, h or q.')
You can create something like this:
hards = {
'word1': 'def'
}
easy = {
'word2': 'def2'
}
hardsandeasy = {}
for key in hards:
hardsandeasy[key] = hards[key]
for key in easy:
hardsandeasy[key] = easy[key]
#hardsandeasy will be the sum of the hard and easy dicts

function either returns None or says "maximum recursion depth exceeded"

I am trying to create a program that will take two sets of random integers, and print a statement based on the results of those two sets of integers. However, when I call the method, I either receive "None" or an error stating "maximum recursion depth exceeded". I can't seem to figure out how to structure my return statements within these methods so that this works properly.
def genre(a,b):
genreType = random.randint(a,b)
if genreType == '1':
genreType = "Fantasy"
return genre()
elif genreType == '2':
genreType = "Sci-Fi"
return genre()
def medium():
mediumType = random.randint(1,2)
if mediumType == '1':
genre = genre(1,2)
print("Play a " + genre + "game")
return medium()
elif mediumType == '2':
genre = genre(1,2)
print("Watch a " + genre + "anime")
return medium()
First, if a function has a branch without a return, it will return None, e.g.:
def something():
if False:
return "Thing"
# There is no return in "else"
print(something()) # None
Second, comparing numbers to strings never succeeds:
print(1 == 1) # True
print(1 == '1') # False
So the example you've provided can only always return None
Third, you are not returning anything meaningful from your functions:
def genre(a,b):
genreType = random.randint(a,b)
if genreType == '1':
genreType = "Fantasy"
return genre() # call this function again, but with no parameters, why?!
If the condition had a chance of being true, you would be getting
TypeError: genre() missing 2 required positional arguments: 'a' and 'b'
I can only guess that you meant to do this:
if genreType == 1:
genreType = "Fantasy"
return genreType
Or, shorter and arguably more readable:
def genre(a,b):
genreType = random.randint(a,b)
if genreType == 1:
return "Fantasy"
elif genreType == 2:
return "Sci-Fi"
# And you can add your own error to know what exactly went wrong
else:
raise Exception("Genre bounds must be between 1 and 2")

python - form check doesn't work

I have a problem. I want to create a form in python. If something is wrong, I want an alert-window (showwarning()). Otherwise it should write 'TRUE' into the command line.
The problem is that I get every time a alert-window. It does not care if the form is filled out correctly or wrong.
Can somebody help me with this problem?
code:
""" Variables """
inputError_1 = bool(0)
inputError_2 = bool(0)
inputError_3 = bool(0)
valueCheck = bool(0)
""" Check-Button """
def Check():
if len(nameOne.get()) == 0:
inputError_1 == TRUE
elif len(nameTwo.get()) == 0:
inputError_2 == TRUE
elif len(comment.get(INSERT)) == 0:
inputError_3 == TRUE
else:
valueCheck = bool(1)
if inputError_1 == FALSE or inputError_2 == FALSE or inputError_3 == FALSE:
showwarning()
else:
print'TRUE'
I think that you can do this in a simpler way:
def check():
if len(nameOne.get()) == 0 or len(nameTwo.get()) == 0 or len(comment.get(INSERT)) == 0:
showwarning()
else:
print 'True'
check()

Categories

Resources