Variable keeps its value - python

I need some help once again. The problem is, when I call a function that should add to a variable, the variable stays at its original value.
Code:
import random
def christncombat(x,y,z):
x += 1
if x > 26:
x = 1
y += 1
if y > 26:
y = 1
z += 1
if z > 26:
z = 1
x = 1
y = 1
encrypt = {65:90, 66:90, 67:72, 68:78, 69:77, 70:83, 71:87, 72:67, 73:73, 74:89, 75:84,
76:81, 77:69, 78:68, 79:79, 80:66, 81:76, 82:82, 83:70, 84:75, 85:85, 86:86,
87:71, 88:88, 89:74, 90:65}
encrypted = []
r1 = random.randint(1,26)
r2 = random.randint(1,26)
r3 = random.randint(1,26)
security = str(r1) + "a" + "-" + str(r2) + "b" + "-" + str(r3) + "c"
input_en = input("Zadejte text, ktery chcete zasifrovat (pouzivejte velka pismena): ")
for i in range(0,len(input_en)):
coded = input_en[i]
coded = ord(coded)
coded = encrypt[coded]
full = r1 + r2 + r3
coded += full
while(coded > 90):
rekt = coded - 90
coded = 65 + rekt
christncombat(r1,r2,r3)
full1 = r1 + r2 + r3
coded += full1
while(coded > 90):
rekt = coded - 90
coded = 65 + rekt
done = chr(coded)
encrypted.append(done)
print(encrypted)
print("Bezpecnostni kod je",security)
Although the issue is probably in this part:
def christncombat(x,y,z):
x += 1
if x > 26:
x = 1
y += 1
if y > 26:
y = 1
z += 1
if z > 26:
z = 1
x = 1
y = 1

You need to return the modified values from the function, like this:
def christncombat(x,y,z):
x += 1
if x > 26:
x = 1
y += 1
if y > 26:
y = 1
z += 1
if z > 26:
z = 1
x = 1
y = 1
return x, y, z
Then in the calling code you can capture those returned values like this:
r1, r2, r3 = christncombat(r1, r2, r3)

Perhaps you want to return values from your function? You could put the values in a list and return the list:
def christncombat(x,y,z):
x += 1
if x > 26:
x = 1
y += 1
if y > 26:
y = 1
z += 1
if z > 26:
z = 1
x = 1
y = 1
value_list = [x, y, z]
return value_list
now, you can call the function in the main part of your code:
new_value_list = christncombat(r1,r2,r3)
now, in your new_value_list, you have r1, r2, and r3 all changed to what you want them to be. Now, you can access all the variables:
new_r1 = new_value_list[0]
new_r2 = new_value_list[1]
new_r3 = new_value_list[2]

Related

IndexError: list index out of range error while enter value like 1 2 3 in Python

I am generating a graph/drawing using pyhton.
When I am entering value from backward like 6 5 4 3 it's working fine but When I am giving input like 1 2 3 it's throwing list index out of range error.
I am new to python. Please help me to fix this.
**EDIT : ** it's only accepting when first value is greater than second value for example it's working with 7 6 but not with 6 7.
here is my python code:
HUMAN_HEIGHT = 3
HUMAN_WIDTH = 3
HUMAN_LEG_OFFSET = 1
def print_2d_array(arr):
"""Print the 2D Array"""
print(f"Height = {len(arr)}, Width = {len(arr[0])}")
for row in arr:
for item in row:
print(f"{item}", end="")
print()
def increasing_slope(index):
"""Returns if the slope is increasing which is the even number"""
return index % 2 == 0
def get_indicator(index):
"""Returns the indicator for increasing or decreasing slope"""
return "/" if increasing_slope(index) else "\\"
def add_human_at(new_arr, human_location, height):
"""Adds Human to the Array"""
human_x = human_location[0]
human_y = human_location[1]
new_arr[height - human_y - 1][human_x - 1] = " "
new_arr[height - human_y - 1][human_x] = "○"
new_arr[height - human_y - 1][human_x + 1] = " "
new_arr[height - human_y][human_x - 1] = "/"
new_arr[height - human_y][human_x] = "|"
new_arr[height - human_y][human_x + 1] = "\\"
new_arr[height - human_y + 1][human_x - 1] = "<"
new_arr[height - human_y + 1][human_x] = " "
new_arr[height - human_y + 1][human_x + 1] = ">"
def create_line(y0, x0, y1, x1, index):
"""Generator that Returns the diagonal line from x,y to x1,y1"""
yield y0, x0
while y0 != y1 and x0 != x1:
y0 = y0 + (-1 if increasing_slope(index) else 1)
x0 += 1
yield y0, x0
def get_2d_mountains_from_1d_sum(arr, height, width, human_location):
new_arr = []
for i in range(height + HUMAN_HEIGHT):
mountain_row = []
for j in range(width + HUMAN_LEG_OFFSET):
mountain_row.append(" ")
new_arr.append(mountain_row)
ground = height + HUMAN_HEIGHT
prev_x, prev_y = 0, 0
for index, [x, y] in enumerate(arr):
indicator = get_indicator(index)
if prev_x >= human_location[0]:
start_x, start_y = ground - prev_y - 1, prev_x + HUMAN_LEG_OFFSET
end_x, end_y = ground - y - 1, x - 1 + HUMAN_LEG_OFFSET
else:
start_x, start_y = ground - prev_y - 1, prev_x
end_x, end_y = ground - y - 1, x - 1
for (point_y, point_x) in create_line(start_x, start_y, end_x, end_y, index):
new_arr[point_y][point_x] = indicator
prev_y = y
prev_x = x
add_human_at(new_arr, human_location, height)
print_2d_array(new_arr)
def generate_mountains(nums):
sum_nums = []
sum_at_position = 0
previous_sum = 0
total_width = 0
max_height = 0
human_location = []
for index, item in enumerate(nums):
# + or - numbers to get prefix list
if index % 2 == 0:
sum_at_position += (item - 1)
else:
sum_at_position -= (item - 1)
total_width += abs(sum_at_position - previous_sum) + 1
if sum_at_position > max_height:
max_height = sum_at_position
human_location = [total_width, max_height]
previous_sum = sum_at_position
sum_nums.append([total_width, sum_at_position])
get_2d_mountains_from_1d_sum(sum_nums, max_height + 1, total_width, human_location)
def print_mountains_human_from_input(nums):
generate_mountains(nums)
print("Enter the inputs")
a = [int(x) for x in input().split()]
print_mountains_human_from_input(a)
I added the screenshot of error..
thanks in advance.
You can add a sorting to your function to avoid a wrong input error but it will not fix the actual error:
def print_mountains_human_from_input(nums):
nums.sort(reverse=True)
generate_mountains(nums)

How do you look and see if there is a number in a raw_input for an equation calculator

I am trying to make an equation calculator I am trying to have a checker for the equation to see if there is a number before an x or y so that it can multiply it.
how would I check to see if there is any number in the raw_input?
def x_pluse_y(total):
x = raw_input('what is your x? ' )
y = raw_input('what is your y? ' )
if x == 'x':
x = 0
if y == 'y':
y = 0
float(x) + float(y) == float(total)
step1 = float(total) - float(y)
x = step1
step2 = int(total) - int(x)
y = step2
print 'Your x is ' + str(x)
print 'Your y is ' + str(y)
def x_minus_y(total):
x = raw_input('what is your x? ' )
y = raw_input('what is your y? ' )
if x == 'x':
x = float(0)
if y == 'y':
y = float(0)
if x > 0:
x == x
elif y > 0:
y == y
if float(x) > 0:
y = float(total) - float(x)
if float(y) > 0 :
x = float(total) - float(y)
print 'Your x is ' + str(x)
print 'Your y is ' + str(y)
def multi_x(equation):
x = raw_input('what is your x? ' )
y = raw_input('what is your y? ' )
if x == 'x':
x = float(0)
if y == 'y':
y = float(0)
if x > 0:
x == x
elif y > 0:
y == y
if float(x) > 0:
y = float(equation) - float(x)
if float(y) > 0 :
x = float(equation) - float(y)
print 'Your x is ' + str(x)
print 'Your y is ' + str(y)
This will only work for an input of only numbers, not a mix of number or letters (but I can modify this to allow for that)
def CheckStrIfVar(var):
try:
#If it is not a number this will raise an error, hence why I'm using exceptions
test = int(var)
return True
except:
#Will run if it cannot convert it to a var
return False

PYTHON 3.0 Negative numbers aren't working as inputs

I'm trying to make a factoring program, but it doesn't seem to work with negative number a-, b- and c-inputs.
from fractions import gcd
factor = -1
opp = 0
number = 1
success = 0
a = int(input("a-value: "))
b = int(input("b-value: "))
c = int(input("c-value: "))
factors = []
d = 0
e = 0
while number <= abs(a*c):
#Checking for multiples
if abs(a*c) % number == 0:
factor += 1
factors.append(number)
number += 1
while (factor-opp) >= 0:
#Checking for actual factors
d = int(factors[factor])
e = int(factors[opp])
if (abs(d+e) or abs(d-e)) == abs(b):
success += 1
break
else:
factor -= 1
opp += 1
if success > 0:
if (d+e) == b:
e = e
elif (d-e) == b:
e -= 2*e
elif (e-d) == b:
d -= 2*d
elif (-d-e) == b:
d -= 2*d
e -= 2*e
#Figuring out the equation
if d % a == 0:
d /= a
f = 1
else:
f = a/gcd(d,a)
d /= gcd(d,a)
if e % a == 0:
e /= a
g = 1
else:
g = a/gcd(e,a)
e /= gcd(e,a)
#Displaying the answer
if d >= 0:
d = str("+" + str(int(d)))
if e >= 0:
e = str("+" + str(int(e)))
elif e < 0:
e = str(int(e))
else:
d = str(int(d))
if e >= 0:
e = str("+" + str(int(e)))
elif e < 0:
e = str(int(e))
if f == 1:
if g == 1:
print ("(x" + d + ")(x" + e + ")")
else:
g = str(int(g))
print ("(x" + d + ")(" + g + "x" + e + ")")
elif g == 1:
f = str(int(f))
print ("(" + f + "x" + d + ")(x" + e + ")")
else:
f = str(int(f))
g = str(int(g))
print ("(" + f + "x" + d + ")(" + g + "x" + e + ")")
else:
print("This equation cannot be factored into integers.")
More specifically, the problem is somewhere within this block, I think. I've tested it out with print statements:
while (factor-opp) >= 0:
#Checking for actual factors
d = int(factors[factor])
e = int(factors[opp])
if (abs(d+e) or abs(d-e)) == abs(b):
success += 1
break
else:
factor -= 1
opp += 1
I've searched everywhere: my programming textbook, online searches about inputting negatives, everything. What am I doing wrong here?
Ok I am able to reproduce your issue for a simple testcase like - a=1 , b=0, c=-4 .
The issue is in the line -
if (abs(d+e) or abs(d-e)) == abs(b):
This does not check whether abs(b) is equal to abs(d+e) or abs(d-e) , instead it first evaluates the result of (abs(d+e) or abs(d-e)) , which would return the first non-zero result , and then compare that against abs(b) , so for negative numbers this does not evaluate the result correctly. Change that condition to -
if abs(d+e) == abs(b) or abs(d-e) == abs(b):
or you can also use a set -
if abs(b) in {abs(d+e), abs(d-e)}: #Though I doubt if using set would give any performance improvement because of the overhead of creating a set.
Demo after changes -
a-value: 1
b-value: 0
c-value: -4
(x+2)(x-2)
a-value: 1
b-value: -1
c-value: -6
(x-3)(x+2)
One more thing, there is something you have not considered , when a=-1 , b=-4 , c=-4 , the result should come to -(x+2)(x+2) , but the current program results in (x+2)(x+2) .

print values after each 1000 step

I want to print value after every certain interval (1000) on last line of code than every single value.
DARTS=200000
hits = 0
throws = 0
rangen = RanGenerator()
pi = 0
avg = 0
mu = 0
var = 0
dev = 1
for i in range (1, DARTS):
throws += 1
x = rangen.rand()
y = rangen.rand()
z = rangen.rand()
tt = x**2 + y**2 + z**2
dist = sqrt(tt)
if dist <= 1.0:
hits = hits + 1.0
pi = 6 * (hits / throws)
avg = avg + pi
mu = avg/throws
var = (var+(mu-pi)**2)/throws
dev = sqrt(var)
print("%d: %s" % (i,dev))
This is easy with the modulo operator - it will print the values only when i is divisible by 1000:
if i % 1000 == 0:
print("%d: %s" % (i,dev))

simple archery game in python

I'm just starting out with python and I'm trying to make a little archery game. However, it creates an error at this point: d = math.sqrt(x*x + y*y) (i.e. the distance between the new point and the original center of the cirlce) Any ideas on why this doesn't work?
def archery():
win = GraphWin("Archery Game", 500,500)
win.setCoords(-50, -50, 50, 50)
circle1 = Circle(Point(0,0), 40)
circle1.setFill("white")
circle1.draw(win)
circle2 = Circle(Point(0,0), 35)
circle2.setFill("black")
circle2.draw(win)
circle3 = Circle(Point(0,0), 30)
circle3.setFill("blue")
circle3.draw(win)
circle4 = Circle(Point(0,0), 25)
circle4.setFill("red")
circle4.draw(win)
circle5 = Circle(Point(0,0), 20)
circle5.setFill("yellow")
circle5.draw(win)
score = 0
for i in range(5):
p = win.getMouse()
p.draw(win)
x = p.getX
y = p.getY
d = math.sqrt(x*x + y*y)
if 40 >= d > 35:
score = score + 1
elif 35 >= d > 30:
score = score + 3
elif 30 >= d > 25:
score = score + 5
elif 25 >= d > 20:
score = score + 7
elif 20 >= d >= 0:
score = score + 9
else:
score = score + 0
print("Your current score is:", score)
win.getMouse()
win.close()
x = p.getX
y = p.getY
will return the function getX and getY instead of executing it. As Mike Steder said, try getX(), that should return a value.
First, you probably need to do:
x = p.getX()
y = p.getY()
i.e. call the functions and use the return value, instead of using the functions themselves.
Second, you can change the math.sqrt(x*x + y*y) call to:
d = math.hypot(x, y)

Categories