Do while loops have local variables in Python? - python

I am trying to use a while statement like so:
o = 0
while o == 0:
try:
n = int(raw_input("Which number do you want to begin with?"))
o = 1
except:
o = 0
print "Please use a valid number."
However, when I try to use variable n later, it gives me the "local variable 'n' referenced before assignment' UnboundLocalError. That means that n cannot be recognized as a variable in the def I am using, because it only exists in the while statement? Is this possible?
The whole code:
import time
from sys import argv
import os
os.system("cls")
print "Welcome to Number counter 2.0!"
a = True
def program():
global a
if a == False:
os.system("cls")
o = 0
while o == 0:
try:
n = int(raw_input("Which number do you want to begin with?"))
o = 1
except:
o = 0
print "Please use a valid number."
if n == "/historyKeep false":
if a == False:
print "Command historyKeep is already set to false."
else:
a = False
print "Command set successfully."
elif n == "/historyKeep true":
if a == True:
print "Command historyKeep is already set to true."
else:
a = True
print "Command set successfully."
if n == "/historyKeep false":
n = raw_input("Which number do you want to begin with?")
elif n == "/historyKeep true":
n = raw_input("Which number do you want to begin with?")
d = raw_input("How many seconds between each number?")
d = int(d)
total_s = n * d
while n > 0:
print n
time.sleep(d)
n = n - 1
print "Done in", total_s, "seconds in total!"
end_q = raw_input("Exit or retry? (e/r)")
if end_q == "e":
os.system("cls")
print "Exiting."
time.sleep(0.5)
os.system("cls")
print "Exiting.."
time.sleep(0.5)
os.system("cls")
print "Exiting..."
time.sleep(0.5)
os.system("cls")
exit(0)
elif end_q == "r":
program()
program()

You set a = True at the beginning. You then test if a == False and only set n if it is. But then you test n == "/history.... n has not been set at this point.
You need to make sure n is assigned before you use it. It is not enough to just mention it in a branch that is not taken.

n is not defined in the scope that you are trying to use it to fix this define it outside of the while loop and the if statement the while loop is in:
global a
n = 0
Then when you ask the user for what number to start with, that value will replace 0, and you should be good to go. Also instead of declaring global a, why not just make a an input argument for the program() function?

Just to make sure, declare n outside of the loop first:
n = None
while True:
try:
n = int(raw_input("Text..."))
break
except:
print("Please enter a valid number!")
Note: Usually, you would use break to exit a loop. This is because your method requires an extra variable, which uses more memory (not much, but if you keep doing it, it will stack up).

Related

how to stop it without using "brake;"? its a guessing play

import math
import random
a = math.floor((random.random())*100)
if a%10 != 00:
c = math.floor(a/10)
a = a - c*10
#to make sure the number isnt over 10
attempts = int(input("enter num of attempts"))
att = attempts
for i in range(0,attempts+1,1):
tr = int(input("try"))
att = att -1
if tr == a:
print("good")
break;
else:
print("no,try again", "you got",att,"more attempts")
if att == 0:
print("game over,the num was", (a))
the game has random num between 0-10 and you need to insert num of attempst, and then guess what number is it, and you got the amount of attempst you have insert to try guessing the num.
You can replace the for loop by a while loop.
This way you have more control, you can use a found boolean and loop while it is False.
Note also that you have to increment i by yourself.
I printed the messages (win/lost) outside of the loop.
It makes the loop code more readable.
I also used randint() to choose the random number to guess.
It does all the work without further computation and is also part of the random module.
from random import randint
a = randint(1, 10)
attempts = int(input("enter num of attempts"))
att = attempts
found = False
i = 0
while i < attempts and not found:
i += 1
att -= 1
tr = int(input("try"))
if tr == a:
found = True
elif att > 0:
print("no,try again", "you got", att, "more attempts")
if found:
print("good")
else:
print("game over,the num was", (a))

the value of the variable doesn't change in python

def type_():
z = input("enter an integer : \n")
try:
z = int(z)
a = 1
except:
print("it is not an integer")
a = 0
return z,a
z,a = type_()
print (z,a)
while a == 0:
type_()
#the code runs good but the issue is when i enter an non integer the while loop gets back to the top but the value of the "a" doesn't change thereafter,even when i enter an integer,the loop runs infinitely...
kindly help out, thanks in advance
def type_():
z = input("enter an integer : \n")
try:
z = int(z)
a = 1
except:
print("it is not an integer")
a = 0
return z,a
z,a = type_()
print (z,a)
while a == 0:
z, a = type_() # You forgot to overide the a variable
The problem is that you assign the name a in the global scope only once. Names don't magically update, they don't know how or when they should be (re)assigned on their own.
Reassign a when calling type_ in the while loop.
while a == 0:
z, a = type_()
You're not changing a inside the loop, you need to set the value of z and a each time you run the loop:
while a == 0:
z, a = type_()

Why is my function being ignored?

In the console, my program prints the first question, and once the input is entered, prints the second one and terminates. It appears to skip the function. Obviously I've done something(s) wrong, any help would be appreciated. That while-loop still feels wrong.
def Prime(n):
i = n - 1
while i > 0:
if n % i == 0:
return False
print("This number is not prime.")
else:
i = i - 1
return True
print("This number is prime.")
def Main():
n = int(input("What is the number you'd like to check?"))
Prime(n)
answer2 = input("Thank you for using the prime program.")
Main()
Your function returns before printing output, so nothing ever gets to the console. Consider printing before returning:
def Prime(n):
i = n - 1
while i > 0:
if n % i == 0:
print("This number is not prime.") # Here
return False
else:
i = i - 1
print("This number is prime.") # And here
return True

Python: If condition appears to be met but isn't triggering

I know this seems like it should be very simple, but at this point I'm at my wit's end trying to figure this out. I've coded up a calculator in python, but for some reason the ending if-else statement is only firing the else segment.
import sys
import re
#setting values
x = 0
n = '+'
y = 0
#valid input flag
valid = True
#continue operations flag
run = True
again = "k"
#addition function
def add(x, y):
return x + y
#subtraction function
def subtract(x, y):
return x - y
#multiplication function
def multiply(x, y):
return x * y
#division function
def divide(x, y):
return x / y
#continuation loop
while run == True:
#Prompt for and accept input
equation = raw_input("Please insert a function in the form of 'operand' 'operator' 'operand' (x + y): ")
equation.strip()
#Divide input into 3 parts by spaces
pieces = re.split('\s+', equation)
#set part 1 = x as float
x = pieces[0]
try:
x = float(x)
except:
print "x must be a number"
valid = False
#set part 2 = operator
if valid == True:
try:
n = pieces[1]
except:
print "Please use valid formating (x [] y)."
valid = False
#set part 3 = y as float
if valid == True:
y = pieces[2]
try:
y = float(y)
except:
print "y must be a number"
valid = False
#If input is valid, do requested calculations
while valid == True:
if n == '+' :
print equation + " =", add(x,y)
elif n == '-' :
print equation, " =", subtract(x,y)
elif n == '*' :
print equation, "*", y, " =", multiply(x,y)
elif n == '/' :
if y == 0:
print "You cannot divide by zero."
else:
print equation, " =", divide(x,y)
else:
print "Please use an appropriate operator ( + - * / )."
#play again
again = raw_input("Play again? ")
print again
if again == ("yes", "y", "YES", "Yes","yes"):
run = True
print "yes'd"
else:
print "no'd"
run = False
When I run this code, I get two different problems:
If I enter a valid input (ie: 2 + 2), then my output is
"2 + 2 = 4.0"
"2 + 2 = 4.0"
"2 + 2 = 4.0"
repeating forever.
If I enter an invalid input, I get the "Play again? " Prompt, but
no matter what I enter, the else statement fires.
(for instance, in the case that I enter "yes" into "Play again? ", it will print:
"yes" (<-- this is from "print again" line )
"no'd" (<-- this is from "else: print "no'd" )
I dont know how to solve either of these problems at this point, so any help would be greatly appreciated.
Edit: Thank you everyone, I wish I could check mark all of you for helping me understand different things about what I did wrong.
In while valid == True:, you never change the value of valid, so it's always True and the loop is infinite. I don't see why it's even a loop - change it to if like the blocks above it and it will behave as expected.
Also, in if again == ("yes", "y", "YES", "Yes","yes"):, change == to in and it will behave as expected.
Perhaps you should replace this code:
while valid == True:
if n == '+' :
print equation + " =", add(x,y)
elif n == '-' :
print equation, " =", subtract(x,y)
elif n == '*' :
print equation, "*", y, " =", multiply(x,y)
elif n == '/' :
if y == 0:
print "You cannot divide by zero."
else:
print equation, " =", divide(x,y)
else:
print "Please use an appropriate operator ( + - * / )."
With this...
if valid:
Or...
while valid == True:
# Insert your previous code here.
break
You could also just simply set valid to false at the bottom of your loop too. That would work.
I think valid is constantly true in this case. You have also written while valid is true, which means it will keep iterating over the loop until valid is equalled to false. It appears that within this block of code in the while loop, valid isn't switched to false.
while valid == True: should probably be if valid == True
and for your second problem:
if again == ("yes", "y", "YES", "Yes","yes"): should probably be:
again = again.lower();
if again == "yes" or again == "y":
Your answer is looping because of
while valid == True:
Replace the loop with the if statement
You get "no'd" because of
if again == ("yes", "y", "YES", "Yes", "yes"):
Here you are equating string with a tuple, instead of checking whether the string is contained within a tuple. Try this instead:
if again in ("yes", "y", "YES", "Yes""):

python: program hanging! (print issue maybe?)

So, I'm quite nooby at python. I decided to make a program that makes prime numbers. I know there's probably a function built in that does this but I decided to do it myself.
number = 1
numlist = list()
for x in range (0, 1000):
numlist.append("")
print "Created list entry " + str(x)
while True:
number = number + 1
if number % 2 != 0:
numscrollerA = 1
numscrollerB = 1
while numscrollerA <= number:
if float(number) / float(numscrollerA) == float(int(number)):
numlist[numscrollerA] = "true"
if float(number) / float(numscrollerA) != float(int(number)):
numlist[numscrollerA] = "false"
numscrollerA = numscrollerA + 1
while numscrollerB <= number:
if numscrollerB != 1 and numscroller != number and numlist[numscrollerB] == "true":
primestatus = "false"
else:
primestatus = "true"
if primestatus == "true":
print number
I get "Created list entry x" 1000 times as I should. Then the program just hangs.
while numscrollerB <= number:
if numscrollerB != 1 and numscroller != number and numlist[numscrollerB] == "true":
primestatus = "false"
else:
primestatus = "true"
You don't increase numscrollerB in this loop, so it runs infinitedly. Anyway, You should rather use 'for loop':
for numscrollerB in range(1, number+1):
pass # do something
Your code is very unpythonic. Typical of a newcomer experienced in a different style of coding.
Your list is uneccessary.
In python you could create the list like this
def check_even(val):
#this contains your logic
return val % 2 == 0
evenslist = [check_even(i) for i in xrange(1, 1001)]
print numlist

Categories

Resources