When writing SWITCH statements how can one represent logical operators inside the CASE? - switch-statement

Here's what I've written so far....
case count > 10 & & count %2 == 0:
(document.body.style.backgroundColor = "white").
break;
default:
(document.body.style.backgroundColor = "rgb(186, 155, 111)")
}
}
Tried writing it this way but it's like the code isn't being read at all, I want it to change color if the number is greater than 10 And also an even number...So Thanks!
Also I can't write it in the switch because i am at case 10 already.

Related

Variable not changing after trying to update it

I'm trying to make a variable update after a line of the code is passed. The problem I'm having is that, once that line of the code is passed and then printed again, the variable is the default one, in this case 10.
I don't know if I'm doing something wrong or anything, but I just can't see where I'm failing, maybe because I'm a beginner. Tried everything I could think of before asking for help but at this point I'm desperate. Thanks.
number = 10
def numberFun(question,valid=("ADD","REM")):
while (answer := input(question)) and answer not in valid:
print(f"Please, choose between {valid}.")
return answer
print(f"{number}: before updating.")
numberAction = numberFun("You want to add or remove one?\n")
if numberAction == "ADD":
print(number + 1)
elif numberAction == "REM":
print(number - 1)
print(f"{number} : after updating.")
This is because you aren't updating the value stored in number. My guess is that you are trying to do so in your if/elif clauses; if that is the case, this should work:
number = 10
def numberFun(question,valid=("ADD","REM")):
while (answer := input(question)) and answer not in valid:
print(f"Please, choose between {valid}.")
return answer
print(f"{number}: before updating.")
numberAction = numberFun("You want to add or remove one?\n")
if numberAction == "ADD":
number += 1 # equivalent to 'number = number + 1'
elif numberAction == "REM":
number -= 1 # equivalent to 'number = number - 1'
print(number)
print(f"{number} : after updating.")
Originally, you were only printing number after some operation. In order for the value in number to change, you would need to reassign some value to the variable.
Notice how I perform a computation where you performed output. I moved output below the computations.
number = 10
def numberFun(question,valid=("ADD","REM")):
while (answer := input(question)) and answer not in valid:
print(f"Please, choose between {valid}.")
return answer
print(f"{number}: before updating.")
numberAction = numberFun("You want to add or remove one?\n")
if numberAction == "ADD":
number = number + 1
elif numberAction == "REM":
number = number - 1
print(number)
print(f"{number} : after updating.")
To add or subtract 1 from the variable num you need to do addition or subtraction operation on the value and store that in the same variable to "update" it.
In your code, in line 12 and line 14, you do the addition, subtraction respectively but you print the result instead of storing the result in the variable number which would "update" the prestored value which in this case is 10.
So, replacing print(number + 1) from line 12 with number += 1 to add 1 to the previous value and replacing print(number - 1) from line 14 with number -= 1 to subtract one to "update" the stored value based on the user's choice.
Then, in the last line when you print the number variable it will display the "updated" value of the variable number
number = 10
def numberFun(question,valid=("ADD","REM")):
while (answer := input(question)) and answer not in valid:
print(f"Please, choose between {valid}.")
return answer
print(f"{number}: before updating.")
numberAction = numberFun("You want to add or remove one?\n")
if numberAction == "ADD":
number += 1
elif numberAction == "REM":
number -= 1
print(f"{number} : after updating.")

How do I achieve this following function only using while loop?

I'm currently working on this problem that ask me to generate an arrow pattern using loops function that looks something like this:
"How many columns? 3"
*
*
*
*
*
I know I can do this with for loop(probably more efficient too), but that is not what I aimed for. I wanted to achieve this only using while loop.
I have some ideas:
1. I set up a control variable and an accumulator to control the loop
2. I then write 2 separate loops to generate the upper and lower part of the pattern. I was thinking about inserting the space before the asterisks using method like this:
(accumulator - (accumulator - integer)) * spaces.
#Ask the user how many column and direction of column
#they want to generate
Keep_going = True
Go = 0
while keep_going:
Column_num = int(input("How many columns? "))
if Column_num <= 0:
print("Invalid entry, try again!")
else:
print()
Go = 1
#Upper part
while Keep_going == True and Go == 1:
print("*")
print(""*(Column_num - (Column_num - 1) + "*")
...but I soon realized it wouldn't work because I don't know the user input and thus cannot manually calculate how many spaces to insert before asterisks. Now everything on the internet tells me to use for loop and range function, I could do that, but I think that is not helpful for me to learn python since I couldn't utilize loops very well yet and brute force it with some other method just not going to improve my skills.
I assume this is achievable only using while loop.
#Take your input in MyNumber
MyNumber = 5
i = 1
MyText = '\t*'
while i <=MyNumber:
print(MyText.expandtabs(i-1))
i = i+1
i = i-1
while i >=1:
print(MyText.expandtabs(i-1))
i = i-1
Python - While Loop
Well first you have to understand that a while loop loops until a requirement is met.
And looking at your situation, to determine the number of spaces before the * you should have an ongoing counter, a variable that counts how many spaces are needed before you continue. For example:
###Getting the number of columns###
while True:
number=int(input('Enter number of rows: '))
if number<=0:
print('Invalid')
else:
###Ending the loop###
break
#This will determine the number of spaces before a '*'
counter=0
#Loops until counter equals number
while counter!=number:
print(" "*counter + "*")
#Each time it loops the counter variable increases by 1
counter=counter+1
counter=counter-1
#Getting the second half of the arrow done
while counter!=0:
counter=counter-1
print(" "*counter + "*")
Please reply if this did not help you so that i can give a more detailed response

Multiplication table in Python with # on all even numbers

I am trying to create a python multiplication table from 2 - 10. If you enter an invalid number it will tell you that it is an invalid entry and ask you to input a number again. It is also supposed to put a # on all even numbers. I am having trouble continuing after an invalid entry and also putting a # on all even numbers. My current code is below
def main():
rows = int(input("What size multiplication table would you like (2-10): "))
if rows <=1 or rows >10:
print (" Invalid Entry - Enter a number between 2 - 10 ")
else:
counter = 0
multiplicationTable(rows,counter)
def multiplicationTable(rows,counter):
size = rows + 1
for i in range (1,size):
for nums in range (1,size):
value = i*nums
print(value,sep=' ',end="\t")
counter += 1
if counter%rows == 0:
print()
else:
counter
main()
I am typing this on my phone so bear with me.
Since you are trying to only get a certain input, you want to have a loop so that we can keep asking the user to enter a number if it is outside the range we want.
So in a generic example where we repeatedly ask a user for a certain input:
While True:
rows = int(input(“enter size: “))
if 1 <= rows < 10:
multiplicationTable(rows, 0)
break
else:
print(“Invalid”)
continue
While True: will run infinitely naturally. However, the magic is in the continue and break statements. continue will make it restart at the top of the loop and break will make it exit the loop after the process is done.
note:
Some programmers consider it bad practice to use the loops in this fashion because it could imply poor logic.
If you need help with an alternate solution I can try and help when I get to my computer.
Best of luck!

Adding more variables to result every while loop

I started to learn python last week and I have to write a while loop where the user is repeatedly asked to input an even number. Then, as long as he inputs an even number, the program should put out the sum of all of the previously added numbers. As soon as an odd number is added, the loop should stop without putting out the odd-numbered result.
Do you have any tipps?
thank you!
total = 0
while True:
number = int(input("enter number:" ))
if number % 2 == 0:
total += number
print(f"Total: {total}")
else:
print(f"Final total: {total}")
break
total = 0 - First, we want to initialize our total variable so that we can use it within the loop to count up the sum of all entries.
The while True: line starts an infinite loop. These can be dangerous, but we're going to break out of it later when a condition is met (in this case, an odd number being entered).
number = int(input("enter number: ")) asks the user for input, converts that input into and int and stores it in the variable called number.
if number % 2 == 0: - This checks whether or not the number is even using the modulo operator. This returns the remainder from the division of the first number into the second. For a number to be even, it must have a remainder of 0 when divided by 2.
total += number is shorthand for total = total + number. This simply adds the user's input to the total.
print(f"Total: {total}") prints out the total using an f-string. See PEP 498 for more info. Essentially, creating an f-string is as easy as putting an f before the literal string creation. This allows you to plug variables directly into strings instead of having to rely on the .format() method.
The above print line would be written as print("Total: {}".format(total)) if not using f-strings.
The else statement catches any number that is not even, so therefore must be odd. It prints out the final total and then break will make us leave our infinite loop.

String index out of range and I can't fix the error

So below is my code. Somewhere in the "for digit in observed" loop there is an indexing error that I can't seem to find or fix. I believe it's something to do with the PINS list, but I'm not sure, as none of my edits have made a difference. Test case that fails is observed = '11'. Single cases all pass. Unfortunately as I'm using codewars, there is no line given for the error, just the following:
Traceback:
in
in get_pins
IndexError: string index out of range
def get_pins(observed):
# Let's see what we're working with
print("observed")
print(observed)
print(" ")
# Dictionary of possible numbers for a half-assed observation of a key press.
possible = {'0':'08','1':'124','2':'1235','3':'236',
'4':'1457','5':'24568','6':'3569',
'7':'478','8':'05789','9':'689'}
# Single digit pwd case
PINS=[]
if len(observed) == 1:
for digit in possible[observed]:
PINS.append(digit)
return PINS
# Find number of possible PINs
num_possibles = 1
# Step through observed digits
for digit in observed:
num_possibles*=len(possible[digit])
# Populate PINS to allow string manipulation
PINS = " "*num_possibles
print(PINS[num_possibles])
num_change = num_possibles
change = []
count = 0
# Step through observed, determine change of digit,
for digit in observed:
# Last digit in observed means it iterates every time
if digit != observed[len(observed)-1]:
# Develop array for checking position
num_change = num_change/len(possible[digit])
for i in range(1,len(possible[digit])):
change.append(i*num_change)
print(change)
# Populate PINS with possible digit, full pin is created after final iteration of digit/observed loop
for pin in range(0,num_possibles-1):
PINS[pin] = PINS[pin] + possible[digit][count]
if (pin+1) in change:
count+=1
change=[]
count =0
else:
for pin in range(0,num_possibles-1):
PINS[pin] = PINS[pin] + possible[digit][count]
count+=1
if count == len(possible[digit]):
count = 0
return PINS
The problem is here:
PINS = " "*num_possibles
print(PINS[num_possibles])
The first line creates a string of spaces of length num_possibles. This means that the valid indices are 0, 1, ..., num_possibles - 1. However, in the very next line you try to index the string at the non-existent index num_possibles.
I would simply drop that print. What is the point of it? You know that PINS is a string of all spaces, so why bother?
Strings are immutable, since PINS is a string, the line
PINS[pin] = PINS[pin] + possible[digit][count]
would trigger the error:
TypeError: 'str' object does not support item assignment
What you should do is to initialize PINS as
PINS = [' ']*num_possibles
Or, probably even better
PINS = ['']*num_possibles
In which case
PINS[pin] = PINS[pin] + possible[digit][count]
would be legal (although it could be shortened by use of +=) -- although I'm not sure if this is what you really want to do since you are concatenating the strings stored as values in the possible and not adding the numbers represented by those strings.
At the end of the function, replace return PINS by return''.join(PINS)`
That will fix some of your bugs, but since I know neither intended input nor intended output I can't say any more.

Resources