Python Local Variable As Counter - python

Using Python 3.7.
Is there any way to use a local variable as a counter?
I tried and received error:
UnboundLocalError
I did find a recommendation to use a glbal variable which is working, but if possible I would prefer to use a local variable.
Thanks,
-w
Working code using global variable for counter:
count = 0
def my_collatz(number):
global count
count +=1
if int(number)%2 == 0:
r = int((number)//2)
else:
r = int(((number * 3) + 1))
print('Attempt : ' + str(count) + ',' + str(r))
if r != 1:
return my_collatz(int(r))
print('Please enter a number : ')
number=input()
my_collatz(int(number))

It is a very strange function indeed. Anyway, you can avoid using a global variable by converting it into an input parameter:
count = 0
def my_collatz(number, count):
count +=1
if int(number)%2 == 0:
r = int((number)//2)
else:
r = int(((number * 3) + 1))
print('Attempt : ' + str(count) + ',' + str(r))
if r != 1:
return my_collatz(int(r), count=count)
print('Please enter a number : ')
number=input()
my_collatz(int(number),count)

One possible solution is to move the count variable as parameter to the function and increment it each call:
def my_collatz(number, count=1):
if number % 2 == 0:
r = number // 2
else:
r = (number * 3) + 1
print('Attempt : ' + str(count) + ',' + str(r))
if r != 1:
return my_collatz(r, count + 1)
print('Please enter a number : ')
number=input()
my_collatz(int(number))
Prints:
Please enter a number :
6
Attempt : 1,3
Attempt : 2,10
Attempt : 3,5
Attempt : 4,16
Attempt : 5,8
Attempt : 6,4
Attempt : 7,2
Attempt : 8,1
Other solution is to not use count at all, and instead make the function a generator (using yield). Then you can use enumerate() to obtain your number of steps:
def my_collatz(number):
if number % 2 == 0:
r = number // 2
else:
r = (number * 3) + 1
yield r
if r != 1:
yield from my_collatz(r)
print('Please enter a number : ')
number=input()
for count, r in enumerate(my_collatz(int(number)), 1):
print('Attempt : ' + str(count) + ',' + str(r))

Related

Python script unable to run from console but is running fine from Idle

After F5 in Idle the input prompt appears, I enter a number the file is generated - everything works.
If I try to execute the script directly from the file a console is opened and closed with no result.
If I move the f = open("galaxies.txt","w+") before the outer most FOR loop the script doesn't work at all.
Any suggestions for a fix and reasons why it behaves like this?
import string, random
f = open("galaxies.txt","w+")
def inputNumber(message):
while True:
try:
howmany = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return howmany
break
string.ascii_letters
type_galaxy = ['elliptical','spiral','irregular']
howmany = inputNumber('How many galaxies to generate? ')
for i in range(howmany):
planet_names = []
pos_0 = 'g' + random.choice(string.ascii_letters).upper() + random.choice(string.ascii_letters).upper() + random.choice(string.ascii_letters).upper() + '-' + random.choice(string.ascii_letters).upper() + str(random.randint(1, 9999))
gal_type = type_galaxy[random.randint(0,2)]
num_of_planets = random.randint(1,43)
for k in range(num_of_planets):
pos_1 = 'p' + random.choice(string.ascii_letters).upper() + random.choice(string.ascii_letters).upper() + '-' + random.choice(string.ascii_letters).upper() + str(random.randint(1, 99))
planet_names.append(pos_1)
if i < 1:
f.write('-----Galaxy '+pos_0+'----- \n')
else:
f.write('\n-----Galaxy '+pos_0+'----- \n')
f.write('Type: '+gal_type + ' \n')
f.write('There are '+str(num_of_planets)+' planets in the galaxy. Their names are: \n')
for x in planet_names:
f.write (x + ' and it has ' + str(random.randint(0,56)) + 'moons \n')
f.write('-----Thats all from Galaxy '+pos_0+'----- \n')
f.close()

How do I make random.randint refresh while program is running?

I'm making a small program that shoots out math problems and requires an answer to pass. It works fine, but all the randint values I generate stay static for as long as the progran is running. I figured if I change:
Tehtävä = random.choice(Laskut)
Into a function it should refresh with the loop. Problem is I can't for the life of me figure out how to do that. Would it even work for what I'm trying? The randint values are determined in a seperate list. Heres the rest of the code:
Peli = 1
while Peli != 2:
pulma = 1
refresh = 1
Tehtävä = random.choice(Laskut)
while pulma == 1:
ratkaisu = float(input(Tehtävä.problem + "\n:"))
if ratkaisu == Tehtävä.answer:
pulma += 1
refresh += 1
print("oikein")
elif ratkaisu == "loppu":
pulma += 1
refresh += 1
Peli += 1
else:
print("väärin")
Here are the values I used:
import random
class Algebra:
def __init__(self, problem, answer):
self.problem = problem
self.answer = answer
#Muuttujat
#erotus ja summa
a = random.randint(1,99)
b = random.randint(1,99)
c = random.randint(1,99)
d = random.randint(1,99)
#jako ja kerto
e = random.randint(1,10)
f = e*random.randint(1,10)
g = random.randint(1,10)
#Kysymykset
Kysymys_M = [str(a) + "+" + str(b) + "-x=" + str(c),
str(a) + "-" + str(b) + "-x=" + str(a),
str(a) + "-" + str(b) + "-" + str(c) + "-x=" + str(d),
str(e) + "*x=" + str(f),
str(f) + ":x=" + str(e),
"x:" + str(e) + "=" + str(g)]
#Vastaukset
Vastaus_M = [a+b-c,
-b,
a-b-c-d,
f/e,
f/e,
e*g]
Laskut = [
Algebra(Kysymys_M[0], Vastaus_M[0]),
Algebra(Kysymys_M[1], Vastaus_M[1]),
Algebra(Kysymys_M[2], Vastaus_M[2]),
Algebra(Kysymys_M[3], Vastaus_M[3]),
Algebra(Kysymys_M[4], Vastaus_M[4]),
Algebra(Kysymys_M[5], Vastaus_M[5]),]
(If I have packed too much information please let me know.)

Python formatting print

I'm having some formatting issues with my call to print function. For lack of knowledge of better ways to format, i've ended up with an issue. here is what it should look like
However the actual result of my print returns this.
def tupleMaker(inputString):
s1 = inputString.split()
# Adding the surname at the end of the string
s2 = [s1[len(s1) - 1]]
# Number of other names(no surname)
global noOfNames
noOfNames = len(s1) - 4
# Adding all the other names
for i in range(noOfNames):
s2.append((s1[i + 3]))
# Adding the Reg number
s2.append(s1[0])
# Adding the Degree scheme
s2.append(s1[2])
# Adding the year
s2.append("Year " + s1[1])
# Making it a tuple
t = ()
for i in range(len(s2)):
t = t + (s2[i],)
return t
def formatting(t):
s1 = ""
for i in range(len(t)):
s1 += t[i]
if (i == 0):
s1 += ", "
elif (i == len(t) - 4):
s1 += " "
else:
s1 += " "
#print(t[0] + ", ", end="")
#for i in range(noOfNames):
#print (t[i+1], end= " ")
#print(format(t[1+noOfNames], "<32s"))
#print(format(thenames, "<32d") + format(regNo, "<7d") + format(degScheme, ">6s") + format(year, ">1s")
print("")
print(s1)
I would recommend looking at using pythons built in string.format() function a small tutorial is located here: https://pyformat.info/

string index out of range list iteration

I am fairly new to python, I am not sure on how to fix a index string out of range. it happens right after the while loop when I want to send mylist[i][0] to formatting function. Any pointer on my code in general would be awesome!
def formatting(str1):
if str1 == '?':
return True
else:
return False
while(i <= len(mylist)):
val = formatting(mylist[i][0])
if val == True:
str1 = mylist[i]
str2 = mylist[i+1]
i = i + 2
format_set(str1, str2)
else:
if format == True:
if (margin + count + len(mylist[i])) <= width:
if (i == (len(mylist)-1)):
list2.append(mylist[i])
print(" " * margin + " ".join(list2))
break
list2.append(mylist[i])
count += len(mylist[i])
i += 1
else:
print(" " * margin + " ".join(list2))
list2 = []
count = 0
else:
temp_margin = margin
temp_width = width
width = 60
margin = 0
if (margin + count + len(mylist[i])) <= width:
if (i == (len(mylist)-1)):
list2.append(mylist[i])
print(" " * margin + " ".join(list2))
margin = temp_margin
width = temp_width
break
list2.append(mylist[i])
count += len(mylist[i])
i += 1
else:
print(" " * margin + " ".join(list2))
list2 = []
count = 0
change
i <= len(mylist)
to
i < len(mylist)
In the last iteration of the while loop, i is referring to the last value. Hence,
str2 = mylist[i+1]
is trying to reference a string outside the allowed range and you get an error.
EDIT: Also, as Wcrousse mentioned, the while (i <= len(...)) should be changed to i < len(...) because indexes go from 0 - (length-1).

New Hangman Python

I am working on a Hangman game, but I am having trouble replacing the dashes with the guessed letter. The new string just adds on new dashes instead of replacing the dashes with the guessed letter.
I would really appreciate it if anyone could help.
import random
import math
import os
game = 0
points = 4
original = ["++12345","+*2222","*+33333","**444"]
plusortimes = ["+","*"]
numbers = ["1","2","3"]
#FUNCTIONS
def firstPart():
print "Welcome to the Numeric-Hangman game!"
def example():
result = ""
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
return ori
# def actualGame(length):
#TOP LEVEL
firstPart()
play = raw_input("Do you want to play ? Y - yes, N - no: ")
while (play == "Y" and (points >= 2)):
game = game + 1
points = points
print "Playing game #: ",game
print "Your points so far are: ",points
limit = input("Maximum wrong guesses you want to have allowed? ")
length = input("Maximum length you want for the formulas (including symbols) (must be >= 5)? ")
result = "" #TRACE
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
test = eval(result[:-1])
v = random.choice(plusortimes) #start of randomly generated formula
va = random.choice(plusortimes)
formula = ""
while (len(formula) <= (length - 3)):
formula = formula + random.choice(numbers)
formula2 = str(v + va + formula)
kind = ""
for i in range(2,len(formula2)):
if i % 2 == 0:
kind = kind + formula2[i] + formula2[0]
else:
kind = kind + formula2[i] + formula2[1]
formula3 = eval(kind[:-1])
partial_fmla = "------"
print " (JUST TO TRACE, the program invented the formula: )" ,ori
print " (JUST TO TRACE, the program evaluated the formula: )",test
print "The formula you will have to guess has",length,"symbols: ",partial_fmla
print "You can use digits 1 to 3 and symbols + *"
guess = raw_input("Please enter an operation symbol or digit: ")
a = 0
new = ""
while a<limit:
for i in range(len(formula2)):
if (formula2[i] == partial_fmla[i]):
new = new + partial_fmla[i]
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
a = a+1
print new
guess = raw_input("Please enter an operation symbol or digit: ")
play = raw_input("Do you want to play ? Y - yes, N - no: ")
The following block seems problematic:
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
Python does not allow modification of characters within strings, as they are immutable (cannot be changed). Try appending the desired character to your new string instead. For example:
elif formula2[i] == guess:
new += guess
else:
new += '-'
Finally, you should put the definition of new inside the loop directly under, as you want to regenerate it after each guess.

Categories