why doesn't += work in a while true loop python? - python

the code just doesn't work, I can not understand what is wrong with the +=
taken = 1
first = int(input(" "))
while taken <= 6:
print(1)
print(taken+=1)
the syntax error just pops up and the + is highlighted red, I have tried looking however the only question I found was where it did not work because of the global the person put before the thing they were += onto.

This is because variable += val is shorthand for
variable = variable + val
As this is an assignment expression, and doesn't return anything, that's why this is considered to be a syntax error.
Note 1: This has nothing to do with while loop, it's universally unaccepted
Note 2: Python doesn't support ++ / -- operators as of now
So, do this instead:
taken = 1
first = int(input(" "))
while taken <= 6:
taken+=1
print(f"1\n{taken}")

Try to write taken += 1 in the row above and than print taken.
taken = 1
first = int(input(" "))
while taken <= 6:
print(1)
taken += 1
print(taken)

you simply cannot do that.
you can do this instead :
taken = 1
first = int(input(" "))
while taken <= 6:
print(1)
taken += 1
print(taken)

Related

Having problems passing info from one function to another (Python)

I'm fairly new to python (been taking classes for a few months) and I've come across a reoccurring problem with my code involving passing information, such as an integer, from one function to another. In this case, I'm having problems with passing "totalPints" from "def getTotal" to "def averagePints" (totalPints in def averagePints defaults to 0).
def main():
endQuery = "n"
while endQuery == "n":
pints = [0] * 7
totalPints = 0
avgPints = 0
option = ""
print("Welcome to the American Red Cross blood drive database.")
print()
print("Please enter 'w' to write new data to the file. Enter 'r' to read data currently on file. Enter 'e' to "
"end the program.")
try:
option = input("Enter w/r/e: ")
except ValueError:
print()
print("Please input only w/r/e")
if option == "w":
print()
def getPints(pints):
index = 0
while index < 7:
pints[index] = input("Input number of Pints of Blood donated for day " + str(index + 1) + ": ")
print(pints)
index = index + 1
getPints(pints)
def getTotal(pints, totalPints):
index = 0
while index < 7:
totalPints = totalPints + int(pints[index])
index = index + 1
print(totalPints)
getTotal(pints, totalPints)
def averagePints(totalPints, avgPints):
avgPints = float(totalPints) / 7
print(avgPints)
averagePints(totalPints, avgPints)
Passing information from "def getPints" to "def getTotal" works fine, and both print the accurate information, but nothing passes from "def getTotal" to "def averagePints" and returns 0. What am I doing wrong in this case? Is it something to do with the scope of the variables listed above?
This is my first time posting to Stack Overflow because I could find any fixes to what I am having troubles with. What I expect to happen from this code is passing the number from "totalPints" in "def getTotal" to "def averagePints" to make a calculation with that number. I tried messing with the scopes of the declared variables and the order of when functions are called but I still can't really tell what I'm missing. All I know is that the value of "totalPints" in "def averagePints" always returns 0.
You have a variable scoping issue. In getTotal, totalPints is being updated with its value local to the function, not the global one like you are expecting. Returning the new value from the function and assigning it seems to have the intended effect. Below is the updated snippet:
def getTotal(pints, totalPints):
index = 0
while index < 7:
totalPints = totalPints + int(pints[index])
index = index + 1
print(totalPints)
return totalPints
totalPints = getTotal(pints, totalPints)

while function with the in operator not working

gone = []
turn = 0
def play(XO,player):
while 0 == 0:
num = input("\n"+player+" enter an available number where you want to put an '"+XO+"'.\n > ")
while ((str(num).isdigit() == False) or ((int(num) <= 9 and int(num) >= 1) == False)) or (num in gone):
num = input("\nValue was not an available number.\n"+player+" enter an available number where you want to put an '"+XO+"'.\n > ")
So, in the second while loop I'm having a problem. You see the (num in gone) part? I'm trying to make it so if num is found in the gone list then it will be true, but it isn't working. Instead it passes through it.
I've tested to see if (not num in gone) applies the opposite effect, and it does!
If you need to see my entire code I can post it... btw this is for a Tic-Tac-Toe program I am making.
You're putting too much logic in one condition. Splitting it up will help you a lot.
Try something like this:
gone = []
turn = 0
def play(XO, player):
while True:
num = input(
f"\n{player} enter an available number "
f"where you want to put an '{XO}'.\n > "
)
try:
num = int(num)
except ValueError:
print("Not a valid number, try again")
continue
if num < 1 or num > 9:
print("Number not in correct range, try again")
continue
if num in gone:
print("Number already gone, try again")
continue
gone.append(num)
turn += 1

How can i stop a for-loop iterating when the input is not valid? (not allowed to use a while loop) - Python

for i in range (0, 3):
print() # When iterates creates a space from last section
raw_mark = int(input("What was student: " + str(student_id[i]) + "'s raw mark (0 - 100)?: "))
days_late = int(input("How many days late was that student (0 - 5)?: "))
penalty = (days_late * 5)
final_mark = (raw_mark - penalty)
# Selection for validation
if 0 <= raw_mark <= 100 and 0 <= days_late <= 5 and final_mark >= 40:
print("Student ID:", str(student_id[i]))
print() # Spacing for user readability
print("Raw mark was:", str(raw_mark),"but due to the assignment being handed in",
str(days_late),"days late, there is a penalty of:", str(penalty),"marks.")
print()
print("This means that the result is now:", final_mark,"(this was not a capped mark)")
elif 0 <= raw_mark <= 100 and 0 <= days_late <= 5 and final_mark < 40: # Final mark was below 40 so mark must be capped
print("Student ID:", str(student_id[i]))
print()
print("Raw mark was:", str(raw_mark),"but due to the assignment being handed in",
str(days_late),"days late, there is a penalty of:", str(penalty),"marks.")
print()
print("Therefore, as your final mark has dipped below 40, we have capped your grade at 40 marks.")
else:
print("Error, please try again with applicable values")
At the else i would like the loop to loop back through but not having iterated i to the next value, so that it can be infinite until all 3 valid inputs are entered... cannot use a while loop nor can i put the if - elif- else outside the loop. Nor can i use a function :(
You can have your for loop behave like a while loop and have it run forever and implement your i as a counter. Then the loop can be terminated only if it ever hits 3 (or 2 so that you indices dont change), while otherwise it is set back to 0:
cnt_i = -1
for _ in iter(int, 1):
cnt_i += 1
if ...
else:
cnt_i = 0
if cnt_i == 2:
break
But seriously, whatever the reason for not using a while loop, you should use it anyhow..
Try something like this. You can keep track of the number of valid inputs, and only stop your loop (the while) once you hit your target number.
valid_inputs = 0
while valid_inputs <= 3:
...
if ...:
...
elif ...:
...
else:
# Immediately reset to the top of the while loop
# Does not increment valid_inputs
continue
valid_inputs += 1
If you really cannot use a while loop...
def get_valid_input():
user_input = input(...)
valid = True
if (...): # Do your validation here
valid = False
if valid:
return user_input
else:
return get_valid_input()
for i in range (0, 3):
input = get_valid_input()
# Do what you need to do, basically your program from the question
...
...
There are some additional gotchas here, as in you need to worry about the possibility of hitting the maximum recursion limit if you keep getting bad input values, but get_valid_input should ideally only return when you are sure you have something that is valid.
You can put the input statement inside while loop containing try block.
for j in range(3): # or any other range
try:
raw_mark = int(input("What was student: " + str(student_id[i]) + "'s raw mark (0 - 100)?: "))
days_late = int(input("How many days late was that student (0 - 5)?: "))
break
except:
pass

How to exit while loop

I don't understand why I cannot go out from simple loop.
Here is the code:
a = 1
#tip checking loop
while a != 0:
# tip value question - not defined as integer to be able to get empty value
b = input("Give me the tip quantinty which you gave to Johnnemy 'hundred' Collins :")
# loop checking if value has been given
if b:
#if b is given - checking how much it is
if int(b) >= 100:
print("\nJohnny says : SUPER!")
elif int(b) < 100:
print("\nJohnny says : Next time I spit in your soup")
elif b == '0':
a = 0
else:
print("You need to tell how much you tipped")
print("\n\nZERO ? this is the end of this conversation")
Thanks for your help.
This should solve your problem:
a = 1
#tip checking loop
while a != 0:
# tip value question - not defined as integer to be able to get empty value
b = input("Give me the tip quantinty which you gave to Johnnemy 'hundred' Collins :")
# loop checking if value has been given
if b:
#if b is given - checking how much it is
if int(b) >= 100:
print("\nJohnny says : SUPER!")
elif int(b) < 100:
print("\nJohnny says : Next time I spit in your soup")
if b == '0':
a = 0
else:
print("You need to tell how much you tipped")
print("\n\nZERO ? this is the end of this conversation")
the following condition
if b == '0':
a = 0
should be in the same scope as the if b: condition.
You cant break out of the loop because. actually, there is nobreak. You need to putbreak` command at the end of every loop branch where you would like to stop looping in order to break out of the loop.
Also, you could break out assigning a = 0 instead of the break.

Bulls and Cows Game - Python programming for beginners

I am a beginer programming Python and for a evaluation assignment I was asked to program a Bulls and Cows game using very simple code.
I have some code already written, but can't seem to make the function work. The function should be able to compare the four digit number the user wrote (num_guess) to the random number generated by the program (stored in a list called num).
I can input the value, but have no further feedback from the program.
Could you please check my code and help me?
Thanks!
import random
guess = raw_input("What is your guess? ")
if (len(guess) != 4):
guess = raw_input("Your guess must be 4 characters long! What is your guess?")
num_guess = []
for c in guess:
num_guess.append(int(c))
def compare(num_guess):
num = []
for i in range(4):
n = random.randint(0, 9)
while n in num:
n = random.randint(0, 9)
num.append(n)
if num_guess == num:
print "Congratulations! Your guess is correct"
output = []
if num_guess[0] == num [0]:
output.append["B"]
else:
output.append["C"]
if num_guess[1] == num [1]:
output.append["B"]
else:
output.append["C"]
if num_guess[2] == num [2]:
output.append["B"]
else:
output.append["C"]
if num_guess[3] == num [3]:
output.append["B"]
else:
output.append["C"]
return output
nguesses = 0
while nguesses < 11:
nguesses = nguesses + 1, compare
Without giving you the corrected code you will want to call the function at the end of your code. If you want to see result do:
print compare(num_guess)
This will show you an additional issue with all of these parts
output.append[]
I'm not sure if it is just how you pasted it but you may want to clean up the indentation. Also:
while n in num:
n = random.randint(0, 9)
This above section is not needed. Have fun and figure out how to make it work well.

Categories

Resources