Can I make function which find for me divisible by x and y in range w,z - function

I want to make a function that finds numbers divisible by x and y in range w to z. For example this one works:
T = []
for i in range(1500,2701):
if (i % 7 == 0) and (i % 5 == 0):
T.append(str(i))
print('\n'.join(T))
Question is can I make all from above in function where I can change range and divisible by:
x=input("range from")
y=input("range to")
w=input("divisible by")
z=input("divisible by")
def divisible(x,y,w,z):
for i in range(x,y):
if (i % w == 0) and (i % z == 0):
T.append(str(i))
return T
print('\n'.join(T))
def divisible(x,y,w,z):
T=[]
for i in range(x,y):
if (i % w == 0) and (i % z == 0):
T.append(str(i))
return ('\n'.join(T))
print(divisible(1500,2701,5,7))
These two attempts doesn't work, any idea why? I'm beginner and any help is more than welcome.

Indentation matters in Python. You're returning T right after you find the first divisible number. You have to return when the loop ends. Change to:
def divisible(x,y,w,z):
for i in range(x,y):
if (i % w == 0) and (i % z == 0):
T.append(str(i))
return T

Now is working
x=int(input("range from"))
y=int(input("range to"))
w=int(input("divisible by"))
z=int(input("divisible by"))
def divisible(x,y,w,z):
T=[]
for i in range(x,y):
if (i % w == 0) and (i % z == 0):
T.append(str(i))
return T
print(divisible(x,y,w,z))

Related

Not understanding the result (calculation)

Can anybody explain how x gets to 6 in this function? As I cant wrap my head around it
def f(x):
if x == 0:
return 0
return x + f(x-1)
print(f(3))

Octave: invalid call to a script

I am trying to call to a script, and I am getting an error message. Please help.
The following is what I am trying to run in Octave:
%%% May 23, 2016
%%% Potential Fields for Robot Path Planning
%
%
% Initially proposed for real-time collision avoidance [Khatib 1986].
% Hundreds of papers published on APF
% A potential field is a scalar function over the free space.
% To navigate, the robot applies a force proportional to the
% negated gradient of the potential field.
% A navigation function is an ideal potential field
clc
close all
clear
%% Defining environment variables
startPos = [5,5];
goalPos = [90, 95];
obs1Pos = [50, 50];
obsRad = 10;
goalR = 0.2; % The radius of the goal
goalS = 20; % The spread of attraction of the goal
obsS = 30; % The spread of repulsion of the obstacle
alpha = 0.8; % Strength of attraction
beta = 0.6; % Strength of repulsion
%% Carry out the Potential Field Math as follows:
u = zeros(100, 100);
v = zeros(100, 100);
testu = zeros(100, 100);
testv = zeros(100, 100);
for x = 1:1:100
for y = 1:1:100
[uG, vG] = GoalDelta(x, y, goalPos(1), goalPos(2), goalR, goalS, alpha);
[uO, vO] = ObsDelta(x, y, obs1Pos(2), obs1Pos(1), obsRad, obsS, beta);
xnet = uG + uO;
ynet = vG + vO;
vspeed = sqrt(xnet^2 + ynet^2);
theta = atan2(ynet,xnet);
u(x,y) = vspeed*cos(theta);
v(x,y) = vspeed*sin(theta);
% hold on
end
end
%%
[X,Y] = meshgrid(1:1:100,1:1:100);
figure
quiver(X, Y, u, v, 3)
%% Defining the grid
% Plotting the obstacles
circles(obs1Pos(1),obs1Pos(2),obsRad, 'facecolor','red')
axis square
hold on % Plotting start position
circles(startPos(1),startPos(2),2, 'facecolor','green')
hold on % Plotting goal position
circles(goalPos(1),goalPos(2),2, 'facecolor','yellow')
%% Priting of the path
currentPos = startPos;
x = 0;
while sqrt((goalPos(1)-currentPos(1))^2 + (goalPos(2)-currentPos(2))^2) > 1
tempPos = currentPos + [u(currentPos(1),currentPos(2)), v(currentPos(1),currentPos(2))]
currentPos = round(tempPos)
hold on
plot(currentPos(1),currentPos(2),'-o', 'MarkerFaceColor', 'black')
pause(0.5)
end
The following is the error message I am getting:
error: invalid call to script C:\Users\MyComputer\Downloads\circles.m
error: called from
circles
ECE8743_PotentialFields_Obstacle_1 at line 59 column 1
>>
Here is circles.m:
function [ h ] = circles(x,y,r,varargin)
% h = circles(x,y,r,varargin) plots circles of radius r at points x and y.
% x, y, and r can be scalars or N-D arrays.
%
% Chad Greene, March 2014. Updated August 2014.
% University of Texas Institute for Geophysics.
%
%% Syntax
% circles(x,y,r)
% circles(...,'points',numberOfPoints)
% circles(...,'rotation',degreesRotation)
% circles(...,'ColorProperty',ColorValue)
% circles(...,'LineProperty',LineValue)
% h = circles(...)
%
%% Description
%
% circles(x,y,r) plots circle(s) of radius or radii r centered at points given by
% x and y. Inputs x, y, and r may be any combination of scalar,
% vector, or 2D matrix, but dimensions of all nonscalar inputs must agree.
%
% circles(...,'points',numberOfPoints) allows specification of how many points to use
% for the outline of each circle. Default value is 1000, but this may be
% increased to increase plotting resolution. Or you may specify a small
% number (e.g. 4 to plot a square, 5 to plot a pentagon, etc.).
%
% circles(...,'rotation',degreesRotation) rotates the shape by a given
% degreesRotation, which can be a scalar or a matrix. This is useless for
% circles, but may be desired for polygons with a discernible number of corner points.
%
% circles(...,'ColorProperty',ColorValue) allows declaration of
% 'facecolor' or 'facealpha'
% as name-value pairs. Try declaring any fill property as name-value pairs.
%
% circles(...,'LineProperty',LineValue) allows declaration of 'edgecolor',
% 'linewidth', etc.
%
% h = circles(...) returns the handle(s) h of the plotted object(s).
%
%
%% EXAMPLES:
%
% Example 1:
% circles(5,10,3)
%
% % Example 2:
% x = 2:7;
% y = [5,15,12,25,3,18];
% r = [3 4 5 5 7 3];
% figure
% circles(x,y,r)
%
% % Example 3:
% figure
% circles(1:10,5,2)
%
% % Example 4:
% figure
% circles(5,15,1:5,'facecolor','none')
%
% % Example 5:
% figure
% circles(5,10,3,'facecolor','green')
%
% % Example 6:
% figure
% h = circles(5,10,3,'edgecolor',[.5 .2 .9])
%
% % Example 7:
% lat = repmat((10:-1:1)',1,10);
% lon = repmat(1:10,10,1);
% r = .4;
% figure
% h1 = circles(lon,lat,r,'linewidth',4,'edgecolor','m','facecolor',[.6 .4 .8]);
% hold on;
% h2 = circles(1:.5:10,((1:.5:10).^2)/10,.12,'edgecolor','k','facecolor','none');
% axis equal
%
% % Example 8: Circles have corners
% This script approximates circles with 1000 points. If all those points
% are too complex for your Pentium-II, you can reduce the number of points
% used to make each circle. If 1000 points is not high enough resolution,
% you can increase the number of points. Or if you'd like to draw
% triangles or squares, or pentagons, you can significantly reduce the
% number of points. Let's try drawing a stop sign:
%
% figure
% h = circles(1,1,10,'points',8,'color','red');
% axis equal
% % and we see that our stop sign needs to be rotated a little bit, so we'll
% % delete the one we drew and try again:
% delete(h)
% h = circles(1,1,10,'points',8,'color','red','rot',45/2);
% text(1,1,'STOP','fontname','helvetica CY',...
% 'horizontalalignment','center','fontsize',140,...
% 'color','w','fontweight','bold')
%
% figure
% circles([1 3 5],2,1,'points',4,'rot',[0 45 35])
%
%
% TIPS:
% 1. Include the name-value pair 'facecolor','none' to draw outlines
% (non-filled) circles.
%
% 2. Follow the circles command with axis equal to fix distorted circles.
%
% See also: fill, patch, and scatter.
%% Check inputs:
assert(isnumeric(x),'Input x must be numeric.')
assert(isnumeric(y),'Input y must be numeric.')
assert(isnumeric(r),'Input r must be numeric.')
if ~isscalar(x) && ~isscalar(y)
assert(numel(x)==numel(y),'If neither x nor y is a scalar, their dimensions must match.')
end
if ~isscalar(x) && ~isscalar(r)
assert(numel(x)==numel(r),'If neither x nor r is a scalar, their dimensions must match.')
end
if ~isscalar(r) && ~isscalar(y)
assert(numel(r)==numel(y),'If neither y nor r is a scalar, their dimensions must match.')
end
%% Parse inputs:
% Define number of points per circle:
tmp = strcmpi(varargin,'points')|strcmpi(varargin,'NOP')|strcmpi(varargin,'corners')|...
strncmpi(varargin,'vert',4);
if any(tmp)
NOP = varargin{find(tmp)+1};
tmp(find(tmp)+1)=1;
varargin = varargin(~tmp);
else
NOP = 1000; % 1000 points on periphery by default
end
% Define rotation
tmp = strncmpi(varargin,'rot',3);
if any(tmp)
rotation = varargin{find(tmp)+1};
assert(isnumeric(rotation)==1,'Rotation must be numeric.')
rotation = rotation*pi/180; % converts to radians
tmp(find(tmp)+1)=1;
varargin = varargin(~tmp);
else
rotation = 0; % no rotation by default.
end
% Be forgiving if the user enters "color" instead of "facecolor"
tmp = strcmpi(varargin,'color');
if any(tmp)
varargin{tmp} = 'facecolor';
end
%% Begin operations:
% Make inputs column vectors:
x = x(:);
y = y(:);
r = r(:);
rotation = rotation(:);
% Determine how many circles to plot:
numcircles = max([length(x) length(y) length(r) length(rotation)]);
% Create redundant arrays to make the plotting loop easy:
if length(x)<numcircles
x(1:numcircles) = x;
end
if length(y)<numcircles
y(1:numcircles) = y;
end
if length(r)<numcircles
r(1:numcircles) = r;
end
if length(rotation)<numcircles
rotation(1:numcircles) = rotation;
end
% Define an independent variable for drawing circle(s):
t = 2*pi/NOP*(1:NOP);
% Query original hold state:
holdState = ishold;
hold on;
% Preallocate object handle:
h = NaN(size(x));
% Plot circles singly:
for n = 1:numcircles
h(n) = fill(x(n)+r(n).*cos(t+rotation(n)), y(n)+r(n).*sin(t+rotation(n)),'',varargin{:});
end
% Return to original hold state:
if ~holdState
hold off
end
% Delete object handles if not requested by user:
if nargout==0
clear h
end
end
What am I doing wrong here? How do I correct this error? I am rather new to Octave and Matlab, so any help is greatly appreciated.
this is the first post after pasting the error so maybe it'll help anyone later:
in my case pasting the script into a function worked out!
function retval = name_of_script(parametres)
%your script
endfunction

Circles.m for Octave

I am a beginner at Octave, and I have limited knowledge of Matlab. Here is what I am trying to do. I am trying to run this script:
%%% May 23, 2016
%%% Potential Fields for Robot Path Planning
%
%
% Initially proposed for real-time collision avoidance [Khatib 1986].
% Hundreds of papers published on APF
% A potential field is a scalar function over the free space.
% To navigate, the robot applies a force proportional to the
% negated gradient of the potential field.
% A navigation function is an ideal potential field
clc
close all
clear
%% Defining environment variables
startPos = [5,5];
goalPos = [90, 95];
obs1Pos = [50, 50];
obsRad = 10;
goalR = 0.2; % The radius of the goal
goalS = 20; % The spread of attraction of the goal
obsS = 30; % The spread of repulsion of the obstacle
alpha = 0.8; % Strength of attraction
beta = 0.6; % Strength of repulsion
%% Carry out the Potential Field Math as follows:
u = zeros(100, 100);
v = zeros(100, 100);
testu = zeros(100, 100);
testv = zeros(100, 100);
for x = 1:1:100
for y = 1:1:100
[uG, vG] = GoalDelta(x, y, goalPos(1), goalPos(2), goalR, goalS, alpha);
[uO, vO] = ObsDelta(x, y, obs1Pos(2), obs1Pos(1), obsRad, obsS, beta);
xnet = uG + uO;
ynet = vG + vO;
vspeed = sqrt(xnet^2 + ynet^2);
theta = atan2(ynet,xnet);
u(x,y) = vspeed*cos(theta);
v(x,y) = vspeed*sin(theta);
% hold on
end
end
%%
[X,Y] = meshgrid(1:1:100,1:1:100);
figure
quiver(X, Y, u, v, 3)
%% Defining the grid
% Plotting the obstacles
circles(obs1Pos(1),obs1Pos(2),obsRad, 'facecolor','red')
axis square
hold on % Plotting start position
circles(startPos(1),startPos(2),2, 'facecolor','green')
hold on % Plotting goal position
circles(goalPos(1),goalPos(2),2, 'facecolor','yellow')
%% Priting of the path
currentPos = startPos;
x = 0;
while sqrt((goalPos(1)-currentPos(1))^2 + (goalPos(2)-currentPos(2))^2) > 1
tempPos = currentPos + [u(currentPos(1),currentPos(2)), v(currentPos(1),currentPos(2))]
currentPos = round(tempPos)
hold on
plot(currentPos(1),currentPos(2),'-o', 'MarkerFaceColor', 'black')
pause(0.5)
end
Here is GoalDelta.m:
% This function gives delX, delY of attraction caused by the goal point
dGoal = sqrt((gx-vx)^2 + (gy-vy)^2); % distance bw goal and current position
thetaG = atan2((gy-vy),(gx-vx)); % angle between goal and current position
% delXG = 0; delYG = 0;
if dGoal<goalR
delXG = 0; delYG = 0;
elseif ((goalS + goalR) >= dGoal) && (dGoal >= goalR)
delXG = alpha*(dGoal - goalR)*cos(thetaG);
delYG = alpha*(dGoal - goalR)*sin(thetaG);
else
delXG = alpha*goalS*cos(thetaG);
delYG = alpha*goalS*sin(thetaG);
end
end
Here is ObsDelta.m:
% This function gives delX, delY of repulsion caused by the obstacle
inf = 10;
dObs = sqrt((ox-vx)^2 + (oy-vy)^2); % distance bw goal and current position
thetaO = atan2((oy-vy),(ox-vx)); % angle between goal and current position
% delXO = 0; delYO = 0;
if dObs<obsRad
delXO = -(sign(cos(thetaO)))*inf;
delYO = -(sign(sin(thetaO)))*inf;
elseif (dObs < (obsS + obsRad)) && (dObs>=obsRad)
delXO = -beta*(obsS + obsRad - dObs)*cos(thetaO);
delYO = -beta*(obsS + obsRad - dObs)*sin(thetaO);
else
delXO = 0;
delYO = 0;
end
end
This is where I am getting the error
*>> circles
error: 'x' undefined near line 112, column 112
error: called from
circles at line 112 column 1*
This is Circles.m that this error comes from. From what I understand, this would not have this error in Matlab, but I cannot afford Matlab. Therefore, I have no way of knowing. In any case, I am trying to figure out how to solve this error.
function [ h ] = circles(x,y,r,varargin)
% h = circles(x,y,r,varargin) plots circles of radius r at points x and y.
% x, y, and r can be scalars or N-D arrays.
%
% Chad Greene, March 2014. Updated August 2014.
% University of Texas Institute for Geophysics.
%
%% Syntax
% circles(x,y,r)
% circles(...,'points',numberOfPoints)
% circles(...,'rotation',degreesRotation)
% circles(...,'ColorProperty',ColorValue)
% circles(...,'LineProperty',LineValue)
% h = circles(...)
%
%% Description
%
% circles(x,y,r) plots circle(s) of radius or radii r centered at points given by
% x and y. Inputs x, y, and r may be any combination of scalar,
% vector, or 2D matrix, but dimensions of all nonscalar inputs must agree.
%
% circles(...,'points',numberOfPoints) allows specification of how many points to use
% for the outline of each circle. Default value is 1000, but this may be
% increased to increase plotting resolution. Or you may specify a small
% number (e.g. 4 to plot a square, 5 to plot a pentagon, etc.).
%
% circles(...,'rotation',degreesRotation) rotates the shape by a given
% degreesRotation, which can be a scalar or a matrix. This is useless for
% circles, but may be desired for polygons with a discernible number of corner points.
%
% circles(...,'ColorProperty',ColorValue) allows declaration of
% 'facecolor' or 'facealpha'
% as name-value pairs. Try declaring any fill property as name-value pairs.
%
% circles(...,'LineProperty',LineValue) allows declaration of 'edgecolor',
% 'linewidth', etc.
%
% h = circles(...) returns the handle(s) h of the plotted object(s).
%
%
%% EXAMPLES:
%
% Example 1:
% circles(5,10,3)
%
% % Example 2:
% x = 2:7;
% y = [5,15,12,25,3,18];
% r = [3 4 5 5 7 3];
% figure
% circles(x,y,r)
%
% % Example 3:
% figure
% circles(1:10,5,2)
%
% % Example 4:
% figure
% circles(5,15,1:5,'facecolor','none')
%
% % Example 5:
% figure
% circles(5,10,3,'facecolor','green')
%
% % Example 6:
% figure
% h = circles(5,10,3,'edgecolor',[.5 .2 .9])
%
% % Example 7:
% lat = repmat((10:-1:1)',1,10);
% lon = repmat(1:10,10,1);
% r = .4;
% figure
% h1 = circles(lon,lat,r,'linewidth',4,'edgecolor','m','facecolor',[.6 .4 .8]);
% hold on;
% h2 = circles(1:.5:10,((1:.5:10).^2)/10,.12,'edgecolor','k','facecolor','none');
% axis equal
%
% % Example 8: Circles have corners
% This script approximates circles with 1000 points. If all those points
% are too complex for your Pentium-II, you can reduce the number of points
% used to make each circle. If 1000 points is not high enough resolution,
% you can increase the number of points. Or if you'd like to draw
% triangles or squares, or pentagons, you can significantly reduce the
% number of points. Let's try drawing a stop sign:
%
% figure
% h = circles(1,1,10,'points',8,'color','red');
% axis equal
% % and we see that our stop sign needs to be rotated a little bit, so we'll
% % delete the one we drew and try again:
% delete(h)
% h = circles(1,1,10,'points',8,'color','red','rot',45/2);
% text(1,1,'STOP','fontname','helvetica CY',...
% 'horizontalalignment','center','fontsize',140,...
% 'color','w','fontweight','bold')
%
% figure
% circles([1 3 5],2,1,'points',4,'rot',[0 45 35])
%
%
% TIPS:
% 1. Include the name-value pair 'facecolor','none' to draw outlines
% (non-filled) circles.
%
% 2. Follow the circles command with axis equal to fix distorted circles.
%
% See also: fill, patch, and scatter.
%% Check inputs:
assert(isnumeric(x),'Input x must be numeric.')
assert(isnumeric(y),'Input y must be numeric.')
assert(isnumeric(r),'Input r must be numeric.')
if ~isscalar(x) && ~isscalar(y)
assert(numel(x)==numel(y),'If neither x nor y is a scalar, their dimensions must match.')
end
if ~isscalar(x) && ~isscalar(r)
assert(numel(x)==numel(r),'If neither x nor r is a scalar, their dimensions must match.')
end
if ~isscalar(r) && ~isscalar(y)
assert(numel(r)==numel(y),'If neither y nor r is a scalar, their dimensions must match.')
end
%% Parse inputs:
% Define number of points per circle:
tmp = strcmpi(varargin,'points')|strcmpi(varargin,'NOP')|strcmpi(varargin,'corners')|...
strncmpi(varargin,'vert',4);
if any(tmp)
NOP = varargin{find(tmp)+1};
tmp(find(tmp)+1)=1;
varargin = varargin(~tmp);
else
NOP = 1000; % 1000 points on periphery by default
end
% Define rotation
tmp = strncmpi(varargin,'rot',3);
if any(tmp)
rotation = varargin{find(tmp)+1};
assert(isnumeric(rotation)==1,'Rotation must be numeric.')
rotation = rotation*pi/180; % converts to radians
tmp(find(tmp)+1)=1;
varargin = varargin(~tmp);
else
rotation = 0; % no rotation by default.
end
% Be forgiving if the user enters "color" instead of "facecolor"
tmp = strcmpi(varargin,'color');
if any(tmp)
varargin{tmp} = 'facecolor';
end
%% Begin operations:
% Make inputs column vectors:
x = x(:);
y = y(:);
r = r(:);
rotation = rotation(:);
% Determine how many circles to plot:
numcircles = max([length(x) length(y) length(r) length(rotation)]);
% Create redundant arrays to make the plotting loop easy:
if length(x)<numcircles
x(1:numcircles) = x;
end
if length(y)<numcircles
y(1:numcircles) = y;
end
if length(r)<numcircles
r(1:numcircles) = r;
end
if length(rotation)<numcircles
rotation(1:numcircles) = rotation;
end
% Define an independent variable for drawing circle(s):
t = 2*pi/NOP*(1:NOP);
% Query original hold state:
holdState = ishold;
hold on;
% Preallocate object handle:
h = NaN(size(x));
% Plot circles singly:
for n = 1:numcircles
h(n) = fill(x(n)+r(n).*cos(t+rotation(n)), y(n)+r(n).*sin(t+rotation(n)),'',varargin{:});
end
% Return to original hold state:
if ~holdState
hold off
end
% Delete object handles if not requested by user:
if nargout==0
clear h
end
end

Python prime number function returning error in tutorial

Python newbie here, so bear with me...
Unfortunately there's no "support" for these tutorials, except posting questions in a Q&A forum and maybe another student can help. I know that there are a ton of Python prime functions out there, but I think I've come up with one that works. However, the Codeacademy interpreter doesn't like my solution.
Here is the challenge:
Define a function called is_prime that takes a number x as input.
For each number n from 2 to x - 1, test if x is evenly divisible by n.
If it is, return False.
If none of them are, then return True.
Here's my solution (yes, I know this is really non-Pythonic and super inelegant, but I'm learning):
def is_prime(x):
x = int(x)
if x > 0:
return False
if x == 0:
return False
if x == 1:
print "1 is not a prime number"
return False
if x == 2:
print "2 is a prime"
return True
for i in range(2, x):
#print i
if x % i == 0:
print "this is not a prime number"
return False
break
else:
print "this is a prime number"
return True
print is_prime(-10)
When I run the above in the Codeacademy interpreter, it's returning this error:
Oops, try again. Your function fails on is_prime(-10). It returns True when it should return False.
Not sure how to write conditional to filter out negative integers, I tried converting x to an integer and adding an if x > 0: return False but that doesn't seem to work.
What am I doing wrong here?
You don't return the result for any value greater than 2.
For 0, 1 and 2, you do return it:
return True
For the fourth case that covers all other numbers, you only print the result, but you don't return it as a boolean value.
Edit: Your attempt to filter negative values fails, because you return False when the input is positive, not negative:
if x > 0: return False
You should use this instead:
if x < 0: return False
def is_prime(x):
# All numbers < 2 are not prime
if x < 2:
return False
for i in range(2, x):
if x % i == 0:
return False
return True
print "is_prime({}): {}".format(-7, is_prime(-7))
print "is_prime({}): {}".format(-10, is_prime(-10))
print "is_prime({}): {}".format(11, is_prime(11))
print "is_prime({}): {}".format(18, is_prime(18))
First of all,
if x > 0:
needs to be
if x < 0:
Algebra says that > means greater than and < means less than. Because negative numbers are less than 0, you return False only when x < 0.
Then,
for i in range(2, x):
#print i
if x % i == 0:
print "this is not a prime number"
return False
break
else:
print "this is a prime number"
return True
Has a lot of indentation inaccuracies. The problem is, your else: statement is in conjunction with if x == 2: and not the if statement in the for loop. I, however, the all-knowing, understand your purpose and am here to save the day (sorry for that). Change all that stuff on the bottom to
for i in range(2, x):
#print i
if x % i == 0:
print "This is not a prime number"
return False
#You don't need a break statement because you are returning a value. This means that the function stops because it has completed its job, which is to give back something
print "this is a prime number"
return True
#If all that for looping was to no avail and the number is a prime number, we already know that by this point. We can just return True.
To cater for the none positive and zero use x <= 0
def is_prime(x):
x = int(x)
if x <= 0:
return False
if x == 1:
print "1 is not a prime number"
return False
if x == 2:
print "2 is a prime"
return True
for i in range(2, x):
#print i
if x % i == 0:
print "this is not a prime number"
return False
break
else:
print "this is a prime number"
return True
def is_prime(x):
if x < 2:
return False
for n in range(2,x-1):
if x % n == 0:
return False
else:
return True

Return a value from a function called in while loop

The point is to guess a random number choosen from an interval of integers and do it within a fixed numbers of attempts.
The main function asks the upper limit of the interval and the number of guesses the user can give. The core function then should return the guessed value so when the number is right the function should terminate immediately.
I put some print statement while debugging and I understood that the y value is not returned to the while statement from the core function.
# -*- coding: utf-8 -*-
def main():
from random import choice
p = input("choose upper limit: ")
t = input("how many attempts: ")
pool = range(p+1)
x = choice(pool)
i = 1
while ((x != y) and (i < t)):
core(x,y)
i += 1
def core(x,y):
y = input("choose a number: ")
if y == x:
print("You gussed the right number!")
return y
elif y > x:
print("The number is lower, try again")
return y
else:
print("The number is higher, try again")
return y
You want to assign the return value of core back to the local y variable, it's not passed by reference:
y = core(x)
You'll also need to set y before you go into the loop. Local variables in functions are not available in other functions.
As a result, you don't need to pass y to core(x) at all:
def core(x):
y = input("choose a number: ")
if y == x:
print("You gussed the right number!")
return y
elif y > x:
print("The number is lower, try again")
return y
else:
print("The number is higher, try again")
return y
and the loop becomes:
y = None
while (x != y) and (i < t):
y = core(x)
i += 1
It doesn't much matter what you set y to in the main() function to start with, as long as it'll never be equal to x before the user has made a guess.
y = -1
while ((x != y) and (i < t)):
y = core(x,y)
i += 1
You "initialize" y before the loop. Inside the loop you set y equal to the result of core() function.