I need to break the while loop, I try to do it with status statment and it didn't work to me.
Any suggestions what are the easiest ways to break a while loop?
This is my code:
def loop_of_user(my_details):
"""_summary_
the function do a variety of actions on the the variable my_detailes
:my_details (dict): dictionary of detailes on mariha
"""
num = int(input())
if num == 1:
print(my_details["first_name"])
elif num == 2:
print(my_details["birth_date"][3:5])
elif num == 3:
print(len(my_details["hobbies"]))
elif num == 4:
print(my_details["hobbies"][-1])
elif num == 5:
my_details["hobbies"].append("cooking")
print(my_details["hobbies"])
elif num == 6:
print(tuple_birth_date(my_details["birth_date"]))
elif num == 7:
my_details ["age"] = calculate_age(my_details["birth_date"])
print(my_details["age"])
else:
return "break"
def main():
mariah_details = {"first_name" : "mariah", "last_name" : "carey", "birth_date" : "27.03.1970", "hobbies" : ["sing", "compose", "act"]}
status = ""
while status != "break":
loop_of_user(mariah_details)
if __name__ == "__main__":
main()
The I try to use in satatus like you see and write "break" in the else satement and it not working, it still in the loop and won't break.
I will love some help here.
You can put the while loop inside the function loop_of_user instead and call the function loop_of_user() explicitly.
def loop_of_user(my_details):
"""_summary_
the function do a variety of actions on the the variable my_detailes
:my_details (dict): dictionary of detailes on mariha
"""
while True:
num = int(input())
if num == 1:
print(my_details["first_name"])
elif num == 2:
print(my_details["birth_date"][3:5])
elif num == 3:
print(len(my_details["hobbies"]))
elif num == 4:
print(my_details["hobbies"][-1])
elif num == 5:
my_details["hobbies"].append("cooking")
print(my_details["hobbies"])
elif num == 6:
print(tuple_birth_date(my_details["birth_date"]))
elif num == 7:
my_details["age"] = calculate_age(my_details["birth_date"])
print(my_details["age"])
else:
break
def main():
mariah_details = {"first_name": "mariah", "last_name": "carey", "birth_date": "27.03.1970",
"hobbies": ["sing", "compose", "act"]}
loop_of_user(mariah_details)
if __name__ == "__main__":
main()
Related
I'm new at python and I'm trying to create this game using words picked at random based on words picked
from a previous function and whenever I run the script it keeps spitting out this weird code that I have no idea what it is. What I want instead of spitting out this weird code I want it to be a word. Do you have any tips of how to make it happen?
from random import randint
import time
from line import bloodline
bloodline()
if bloodline == 'Shadow':
spower = randint(1,6)
if spower == 1:
infinity = 'shade'
elif spower == 2:
infinity = 'decay'
elif spower == 3:
infinity == 'black'
elif spower == 4:
infinity = 'vampiric'
elif spower == 5:
infinity = 'eclispe'
print (infinity)
elif bloodline == 'Verglas':
ipower = randint(1,6)
if ipower == 1:
infinity = 'frozen'
elif ipower == 2:
infinity = 'artic'
elif ipower == 3:
inifinity ='glacier'
elif ipower == 4:
infinity = 'white'
elif ipower == 5:
infinity = 'biting'
print (infinity)
elif bloodline == 'Flame':
fpower = randint(1,6)
if fpower == 1:
infinity = 'blazing'
elif fpower == 2:
infinity = 'searing'
elif fpower == 3:
infinity = 'burning'
elif fpower == 4:
infinity = 'sparking'
elif fpower == 5:
infinity = 'scorching'
print (infinity)
output:
<function bloodline at 0x043D1E88>#this right here is what i'm trying to get rid off
code from line file:
from random import randint
def bloodline():
bloodline = randint(1,101)
if bloodline >= 61:
bloodline = 'Verglas'
elif bloodline >= 20:
bloodline = 'Flame'
elif bloodline >= 0:
bloodline = 'Shadow'
print (bloodline)
bloodline is a function, not a variable containing the value that it returns. You need to assign the function call to a variable, then use that in the rest of the code.
from random import randint
import time
from line import bloodline
bl = bloodline()
if bl == 'Shadow':
spower = randint(1,6)
if spower == 1:
infinity = 'shade'
elif spower == 2:
infinity = 'decay'
elif spower == 3:
infinity == 'black'
elif spower == 4:
infinity = 'vampiric'
elif spower == 5:
infinity = 'eclispe'
print (infinity)
elif bl == 'Verglas':
ipower = randint(1,6)
if ipower == 1:
infinity = 'frozen'
elif ipower == 2:
infinity = 'artic'
elif ipower == 3:
inifinity ='glacier'
elif ipower == 4:
infinity = 'white'
elif ipower == 5:
infinity = 'biting'
print (infinity)
elif bl == 'Flame':
fpower = randint(1,6)
if fpower == 1:
infinity = 'blazing'
elif fpower == 2:
infinity = 'searing'
elif fpower == 3:
infinity = 'burning'
elif fpower == 4:
infinity = 'sparking'
elif fpower == 5:
infinity = 'scorching'
print (infinity)
And in the line file, you need to return a value from the function.
from random import randint
def bloodline():
result = randint(1,101)
if result >= 61:
result = 'Verglas'
elif result >= 20:
result = 'Flame'
elif result >= 0:
result = 'Shadow'
return result
Don't use the same name bloodline for the function name and a variable.
The last line, print (bloodline), is printing out the function itself, not it's return value, since you're not calling it. However, if you were to call it and print it out, it would print out None, since the function bloodline doesn't return anything.
The simplest way to fix this is to remove print (bloodline) altogether, or returning the value you want to use.
Another thing I noticed is that the variable bloodline could be interpreted by Python to be the function itself, so it may rebind the function to a value.
Within the bloodline() function you should add a return(bloodline) at the end, as well as removing the print(bloodline) after defining the function.
You should also add return statement at the end of the function definition
So ive been writing Python for a bit now. I've decided to make an app to help my sister with multiplication tables. Im writing the code that will randomly pick from my 10 lists of the diffrent questions (I know there are better ways to write it but it gave me abilities i wanted to use with SQL). lists are by Table (Tone,Ttwo,Tthree, etc.) inside Tone would be ['1*1','1*2',...] then as seen in the if statement it calls by calling the list and problem with randomly generated numbers.
def pick_question():
Table = random.randint(0,9)
Col = random.randint(0,9)
if Table == 0:
if Col == 0:
return Tone[0]
elif Col == 1:
return Tone[1]
elif Col == 2:
return Tone[2]
elif Col == 3:
return Tone[3]
elif Col == 4:
return Tone[4]
elif Col == 5:
return Tone[5]
elif Col == 6:
return Tone[6]
elif Col == 7:
return Tone[7]
elif Col == 8:
return Tone[8]
elif Col == 9:
return Tone[9]
elif Table == 1:
if Col == 0:
return Ttwo[0]
elif Col == 1:
return Ttwo[1]
elif Col == 2:
return Ttwo[2]
elif Col == 3:
return Ttwo[3]
elif Col == 4:
return Ttwo[4]
elif Col == 5:
return Ttwo[5]
elif Col == 6:
return Ttwo[6]
elif Col == 7:
return Ttwo[7]
elif Col == 8:
return Ttwo[8]
elif Col == 9:
return Ttwo[9]
obviously it would keep going but it was already quite long. was wondering if there was anyway to make this not hae to be so repetitive and look better...
def pick_question():
Table = random.randint(0,9)
Col = random.randint(0,9)
return [Tone,Ttwo][Table][Col]
I guess what you are trying to write is
import random
Tone = [f"1*{i}" for i in range(1,10)]
Ttwo = [f"2*{i}" for i in range(1,10)]
Tthree = [f"3*{i}" for i in range(1,10)]
Tfour = [f"4*{i}" for i in range(1,10)]
Tfive = [f"5*{i}" for i in range(1,10)]
Tsix = [f"6*{i}" for i in range(1,10)]
Tseven = [f"7*{i}" for i in range(1,10)]
Teight = [f"8*{i}" for i in range(1,10)]
Tnine = [f"9*{i}" for i in range(1,10)]
Questions = [
Tone,
Ttwo,
Tthree,
Tfour,
Tfive,
Tsix,
Tseven,
Teight,
Tnine,
]
def pick_question():
Table = random.randint(0,8)
Col = random.randint(0,8)
return Questions[Table][Col]
print(pick_question())
but I guess what you are trying to do is this:
import random
A=random.randint(1,9)
B=random.randint(1,9)
print(f"{A}*{B}=?")
C=input()
try:
assert A*B==int(C)
print("You are RIGHT!")
except:
print(f"Your are WRONG, right answer is: {A*B}")
Good luck with python! it's an amazing language! :)
Just use a one-dimensional list:
def pick_question():
Table = random.randint(0,9)
Col = random.randint(0,9)
if Table == 0:
return Tone[Col]
elif Table == 1:
return Ttwo[Col]
This will do the trick.
Or even better, a two-dimensional list:
def pick_question():
Table = random.randint(0,9)
Col = random.randint(0,9)
List = [Tone, Ttwo]
return List[Table][Col]
I quite like this solution with dictionaries and the get method:
route = input()
branch = {'y': code1, 'n': code2}.get(route)
This shortens your code and will be easier to read.
Rather than write the inner if structures, why not just
return Tone[Col]
?
In fact, you can create a list with the Tone, Ttwo, etc. inside it and then write
return outer_list[Table][Col]
def pick_question(list_with_tone_ttwo):
table = random.randint(0,9)
col = random.randint(0,9)
return list_with_tone_ttwo[table][col]
EDIT: added full function
How can i make python print only one copy of the illegalstates-list?
It seems to list it for far too long, when all i would require is one copy.
import itertools
import copy
BOAT = "B"
def illegalStates(roles):
allstates = []
legalstates = []
illegalstates = []
husbands = []
wifes = []
sisalto = []
persons = copy.deepcopy(roles)
persons.remove(BOAT)
for i in range(1, len(persons)+1):
els = [list(x) for x in itertools.combinations(persons, i)]
allstates.extend(els)
allstates.append([])
for state in allstates:
husbands.append([])
wifes.append([])
for henkilo in state:
if henkilo == "H1":
husbands[len(sisalto)-1].append(1)
elif henkilo == "H2":
husbands[len(sisalto)-1].append(2)
elif henkilo == "H3":
husbands[len(sisalto)-1].append(3)
elif henkilo == "W1":
wifes[len(sisalto)-1].append(1)
elif henkilo == "W2":
wifes[len(sisalto)-1].append(2)
elif henkilo == "W3":
wifes[len(sisalto)-1].append(3)
for i in range(0, len(husbands)):
if len(husbands[i]) == 0 or len(wifes[i]) == 0:
legalstates.append(allstates[i])
print(*legalstates)
#--------------------------------
return illegalstates
if __name__ == "__main__":
main()
Here is the whole code, just in case its some other part of the code that keeps making this happen.
Also, when that list is printed, it does not print empty slots. Could this be printed somehow?
Your loop that starts while len(openlist) > 0:, contains a call to legalstates(), which contains a call to illegalstates(), which contains your print statement. Therefore, you're calling the method containing the print every time your while loop...loops
I am using python and asking for help on how to simplify the code below. Thanks.
for i in range(1,9):
if i == 1:
wt_1 = gwt_2018[gwt_2018.WkNum == i]
elif i == 2:
wt_2 = gwt_2018[gwt_2018.WkNum == i]
elif i == 3:
wt_3 = gwt_2018[gwt_2018.WkNum == i]
elif i == 4:
wt_4 = gwt_2018[gwt_2018.WkNum == i]
elif i == 5:
wt_5 = gwt_2018[gwt_2018.WkNum == i]
elif i == 6:
wt_6 = gwt_2018[gwt_2018.WkNum == i]
elif i == 7:
wt_7 = gwt_2018[gwt_2018.WkNum == i]
else i == 8:
wt_8 = gwt_2018[gwt_2018.WkNum == i]
Do you need something like this?
l = [wt_1, wt_2, wt_3, wt_4, wt_5, wt_6, wt_7, wt_8]
for index, i in enumerate(l):
i = gwt_2018[gwt_2018.WkNum == index+1]
Is that mandatory to have 'wt_i' as variable name for all i's ?
I would use a dictionary instead:
wt = {}
for i in range(1,9):
wt[i] = gwt_2018[gwt_2018.WkNum == i]
I found the solution [a link] (Create multiple dataframe using for loop in python 2.7)
gbl = globals()
for i in range(1,54):
gbl['df_'+str(i)] = gwt_2018[gwt_2018.WkNum == i]
Alright so here is my code, I get the result I want but I keep getting the "None" value under it. How do I eliminate the "None" value?
n = input("What day of the week are you leaving?")
r = input("How many days will you be resting?")
def days(n):
if n == 0:
print "Sunday"
elif n == 1:
print "Monday"
elif n == 2:
print "Tuesday"
elif n == 3:
print "Wednesday"
elif n == 4:
print "Thrusday"
elif n == 5:
print "Friday"
elif n == 6:
print "Saturday"
elif n >= 7:
print days(n%7)
print days(n+r)
This should do the trick:
days = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"]
print days[(n+r) % 7]
days never returns anything, so it implicitly returns None. Change all of the print statements in days to return statements:
def days(n):
if n == 0:
return "Sunday"
elif n == 1:
return "Monday"
elif n == 2:
return "Tuesday"
elif n == 3:
return "Wednesday"
elif n == 4:
return "Thrusday"
elif n == 5:
return "Friday"
elif n == 6:
return "Saturday"
elif n >= 7:
return days(n % 7)
Change all the print statements in your days(n) function to return instead.
You print in function days and print result from function days.
Because of function days returns nothing it prints None.