Python if elif and else statement not working - python

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)

Related

Python PyQt5 setting the label of 32 textlabel by for loop

I am getting some voltage value from the box and based on that I need to update the text of all 32 text labels one by one.
if switch == 'J1':
if StatusPT[0] == True and StatusLED[0] == True:
self.color[0] = Qt.green
self.StatusJ1.setText('Pass')
if StatusPT[0] == False:
self.color[0] = Qt.red
self.StatusJ1.setText(StatusPT[1])
elif StatusLED[0] == False:
self.color[0] = Qt.red
self.StatusJ1.setText(StatusLED[1])
if switch == 'J2':
if StatusPT[0] == True and StatusLED[0] == True:
self.color[1] = Qt.green
self.StatusJ2.setText('Pass')
elif StatusPT[0] == False:
self.color[1] = Qt.red
self.StatusJ2.setText(StatusPT[1])
elif StatusLED[0] == False:
self.color[1] = Qt.red
self.StatusJ2.setText(StatusLED[1])
so I have 32 self.Status(J1-J32).setText
is there any way I do for loop to update them?

Skipping through all elifs to the end and activating the last statements

I am making a very creative tetris clone for a project with a friend and we have custom sprites for every shape (including the rotations) and we made a wall of else if statements for the rotations. It's supposed to work like this: It calls a random shape out of list of the main 7 shapes and every time the user presses "a" it changes the left facing gif of that shape using the giant el if wall. However, we ran unto an error where instead of executing the elif statements, it just skips to the last line and changes to the J shape no matter what shape was called in the random statement. Any help would be awesome, thank you! (We are still learning btw) also the rotate function is also supposed to happen when the user presses the "d" key but its supposed to change to the other direction.
import turtle as trtl
import random as rand
wn = trtl.Screen()
#configurations
tetris = trtl.Turtle()
drawer = trtl.Turtle()
background = trtl.Turtle()
starty = int(-400)
square = ("sqaure_block.gif")
s_block_normal = ("S_block_norm.gif")
s_block_standing = ("S_block_right.gif")
invert_s_block_normal = ("Z_block_norm.gif")
invert_s_block_standing = ("Z_block_right.gif")
l_block_normal = ("L_block_norm.gif")
l_block_180 = ("L_block_180.gif")
l_block_right = ("L_block_right.gif")
l_block_left = ("L_block_left.gif")
line_normal = ("line_block_norm.gif")
line_standing = ("line_block_standing.gif")
t_block_normal = ("T_block_norm.gif")
t_block_180 = ("T_block_180.gif")
t_block_right = ("T_BLOCK_RIGHT.gif")
t_block_left = ("T_block_left.gif")
j_block_normal = ("J_block_norm.gif")
j_block_180 = ("J_block_180.gif")
j_block_right = ("J_block_right.gif")
j_block_left = ("J_block_left.gif")
wn.addshape (square)
wn.addshape(s_block_normal)
wn.addshape(s_block_standing)
wn.addshape(invert_s_block_normal)
wn.addshape(invert_s_block_standing)
wn.addshape(l_block_normal)
wn.addshape(l_block_180)
wn.addshape(l_block_right)
wn.addshape(l_block_left)
wn.addshape(line_normal)
wn.addshape(line_standing)
wn.addshape(t_block_normal)
wn.addshape(t_block_180)
wn.addshape(t_block_right)
wn.addshape(t_block_left)
wn.addshape(j_block_normal)
wn.addshape(j_block_180)
wn.addshape(j_block_right)
wn.addshape(j_block_left)
Tshape = [square, s_block_normal, invert_s_block_normal, l_block_normal, line_normal, t_block_normal, j_block_normal]
squarecor = [-50, -25, -100, -50]
wn.bgcolor("lightblue")
background.speed("fastest")
background.hideturtle()
background.pu()
background.goto(-400,-200)
background.fillcolor("blue")
background.pencolor("blue")
background.begin_fill()
background.pd()
background.goto(400,-200)
background.goto(400,-350)
background.goto(-400,-350)
background.goto(-400,-200)
background.end_fill()
#sprite direction change
def sprite_right():
global tetris
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_normal)
tetris.showturtle()
def sprite_left():
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_normal)
tetris.showturtle()
'''
def (fast_down):
global tetris
tetris.setheading(270)
tetris.forward(10)
'''
#turn right
def turn_right():
tetris.speed("fastest")
tetris.setheading(0)
tetris.speed(1)
tetris.forward(10)
tetris.speed("fastest")
tetris.setheading(270)
#turn left
def turn_left():
tetris.speed("fastest")
tetris.setheading(180)
tetris.speed(1)
tetris.forward(10)
tetris.speed("fastest")
tetris.setheading(270)
#down
#tetris container/backround
drawer.pensize(5)
drawer.speed("fastest")
drawer.penup()
drawer.goto(150, 200)
drawer.pendown()
drawer.setheading(270)
drawer.forward(400)
drawer.setheading(180)
drawer.forward(300)
drawer.setheading(90)
drawer.forward(400)
drawer.hideturtle()
#game WIP!!!!!!!!!!
y = 0
space = int(1)
tracer = True
def spawn_T():
new_T=rand.choice(Tshape)
tetris.shape(t_block_180)
tetris.pu()
tetris.goto(0, 200)
tetris.setheading(270)
tetris.forward(10)
'''
if ((abs(space - starty)) < 200):
tetris.forward(2)
else:
'''
tetris.stamp()
'''
space = space =+ 1
'''
tetris.hideturtle()
tetris.goto(0,200)
tetris.showturtle()
if (y == 0):
spawn_T()
#changeing the directions of the sprites
#events
wn.onkeypress(turn_right, "Right")
wn.onkeypress(turn_left, "Left")
wn.onkeypress(sprite_right, "a")
wn.onkeypress(sprite_left, "d")
'''
wn.onkeypress(fast_down, "s")
'''
wn.listen()
wn.mainloop()
Here is the google drive file https://drive.google.com/drive/folders/1Q_zXEqm4aFHQ4RV-ZvEXCK2Wi7SHMxrW?usp=share_link
I think the indentation is wrong here. Maybe try putting the last else-statement one tab further?
Please use elif instead of the else: if formulation to get away from the bewildering indentation - here's how it should look:
def sprite_right():
global tetris
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_normal)
tetris.showturtle()
def sprite_left():
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_normal)
tetris.showturtle()
That said, because this is all the code you've provided, it's not possible to run it and examine why it's not working. Can you please provide an example of an implementation of these functions?
According to the documentation, shape() returns the current shape with no parameters, and sets it with one parameter. Therefore in:
if tetris.shape(s_block_normal):
shape(name) returns None, which is always False. So, if you change to:
if tetris.shape() == s_block_normal:
It should function as required.
Also, you can get rid of the if ladder completely by, for instance, something like:
next_left_shape = {s_block_normal: s_block_standing,
invert_s_block_normal: invert_s_block_standing,
... }
tetris.shape(next_left_shape[tetris.shape()])

Trying to make a leveling system, however it only works once and then stops working?

I'm making a leveling system and it only levels me up once and then stops working. Once it levels me the xp doesn't reset and my level does not go up. Here's the code!
level = int(1)
crexp = int(260)
reqxp = int(100)
while crexp >= reqxp:
level = level+1
crexp = crexp-reqxp
reqxp = (reqxp/100)*120
continue
while 3 > 2:
pinput = input()
if pinput == "1":
crexp = crexp + 60
elif pinput == "2":
print(level)
elif pinput == "3":
print(crexp)
elif pinput == "4":
print(reqxp)
elif pinput == "5":
break
The problem with your current code is that you are not rerunning the 'level up' part of the code. Python generally (when not in a while/for loop e.c.t) reads your code from top to bottom. This means by the time you get into the second while loop the first while loop has finished and will never be run again.
To fix this you want to tell python to recalculate the level and experience variables at certain points - the easiest way to do this is to make the first while loop into a function and call it at the start of the second while loop. You would get something like this -
def checkLevelUp(currentXp, requiredXp, currentLevel):
while currentXp >= requiredXp:
currentLevel = currentLevel+1
currentXp = currentXp-requiredXp
requiredXp = int(requiredXp * 1.2)
return currentLevel, currentXp, requiredXp
level = 1
crexp = 260
reqxp = 100
while True:
level, crexp, reqxp = checkLevelUp(crexp, reqxp, level)
pinput = input()
if pinput == "1":
crexp = crexp + 60
elif pinput == "2":
print(level)
elif pinput == "3":
print(crexp)
elif pinput == "4":
print(reqxp)
elif pinput == "5":
break
Note also the changes to calculating the next required xp - dividing by 100 and then multiplying by 120 is just the same as multiplying by 1.2.

How do i roll mutiples dices in one command

I'm making a discord bot, i already made a dice rolling systen, but I want to improve it. I want to roll multiple dices at once, like Avrae can do.
#client.command(aliases=['r', 'dado', 'dice'])
async def roll(ctx, dados='', numero=20, conta='', ficha=''):
rolagem = random.randint(1,int(numero))
if conta == '':
total = (int(rolagem))
elif conta == '+':
total = (int(rolagem) + int(ficha))
elif conta == '-':
total = (int(rolagem) - int(ficha))
elif conta == 'x':
total = (int(rolagem) * int(ficha))
elif conta == '/':
total = (int(rolagem) / int(ficha))
if ficha == '':
ficha = ''
if total < 0:
total = '1'
if total == 0:
total == '1'
if rolagem == 20:
rolagem = '**20**'
if rolagem == 1:
rolagem = '**1**'
await ctx.send(f'{ctx.author.mention} 🎇 \n**Resultado**: D{numero} ({rolagem}) {conta} {ficha}\n**Total**: {total}')
So, the command should work like: (prefix)r (number of dices to roll) (dice), and show the results like: (number of dices rolled):(dices results)(sum of the dices result)
For exemple: -r 5 d20; Results for 5 D20:(1, 5, 8, 16, 20) (sum).
I want to know how I shoul do it
Here is a roll function I wrote, modified to use strings like you did:
import random
def roll(n='1', d='20', a='+', m='0'):
res = []
for i in range(int(n)):
res.append(random.randint(1, int(d)))
roll_modified = sum(res)
if a == '+' or a == '-' or a == '*' or a == '/':
roll_modified = eval('{}{}{}'.format(roll_modified, a, int(m)))
if roll_modified < 1:
roll_modified = 1
return roll_modified, res
It uses eval to apply the modifiers, so use with caution. I check the value of the operator and use int() on the number to ensure it is a safe expression.
Use it like this:
roll_modified, res = roll('3', '20', '-', '2')
roll_modified is the result after applying sum and modifiers.
res is a list of all the original rolls
You could then print your results with:
res_str = ["**{}**".format(x) if x == 20 or x == 1 else str(x) for x in res]
print(roll_modified, "[{}]".format(", ".join(res_str)))
will output:
36 [14, 4, **20**]

local variable '?' referenced before assignment

I am new to Python and programming in general. I would like to know how to get rid of this compile error
def health_risk(activity_level, is_smoker):
"""Counts the aliveness of a person"""
alive = "alive?" or "sedentary"
very_low = "low" or "very low"
active = "active" or "very active"
if (activity_level in alive) and is_smoker is True:
xer = "extreme"
elif (activity_level in active) and is_smoker is True:
xer = "medium"
elif (activity_level == alive) and (is_smoker is False):
xer = "high"
elif (activity_level == very_low) and (is_smoker is False):
xer = "medium"
elif activity_level == active and is_smoker is False:
xer = "low"
return xer
level = health_risk('low', True)
print(level)
Thanks for the help and this is my first post, thanks.
Revise your variable statements to be assigned to lists.
alive = ["alive", "sedentary"]
very_low = ["low", "very low"]
active = ["active", "very active"]
Replace all == with in,
Include the missing elif statement.
elif (activity_level in very_low) and (is_smoker is True):
xer = "high" # or medium or whatever
note: to reduce redundancy, you could just put and is_smoker if it's True and and not is_smoker if it's False.

Categories

Resources