python 3: import module - python

I'm working on a small program that evaluates the area of two rectangles. The user enters the length and the width of the rectangle (my first module), then the program calculates the area of the rectangles (second module), and finally after calculating the difference between both of the areas, display the result, telling which one is the bigger.
But after entering the lengths and widths, the program displays an error message, telling that my module is not defined as:
ImportError: No module named 'inputRect'
My Code:
#Project M04: Rectangle with the bigger area
#Python 3.4.3
#Module that asks width and lenght of the two rectangles
def inputRect():
width1 = int(input("Enter the width of the first rectangle: "))
length1 = int(input("Enter the length of the first rectangle: "))
width2 = int(input("Enter the width of the second rectangle: "))
lenght2 = int(input("Enter the length of the second rectangle: "))
inputRect()
#import the fonction "inputRect"
import inputRect
#calcule the area of the two rectangles
def calcArea():
rect1 = int(width1) * int(length1)
rect2 = int(width2) * int(length2)
calcArea()
#import the fonction "calcArea"
import calcArea
#Calcul the difference between the two rectangles (rectangle 1 - rectangle 2 = difference)
#if > 0
def difference():
difference = int(rect1) - int(rect2)
# if ifference > 0 : rectangle 1 has a bigger area
if (difference) > 0 :
print ("Rectangle numer 1 is bigger than rectangle 2")
# if ifference < 0 : rectangle 2 has a bigger area
if (difference) < 0 :
print ("Rectangle numer 2 is bigger than rectangle 1")
# else : both rectangles have the same area
else:
print ("Both rectangles have the same area")
difference()

Notes:
understand difference between module and function. You can't import a function, in this case inputRect and calcArea
since you want to create function for each process, try to utilize return in your function to get data that you need
still in the spirit using function, you can separate some calculations. For example, instead of compute two rectangles in one function, create a function that only calculate an area, given width and length
Something like this could be an example:
def get_rect_input():
width1 = int(input("Enter the width of the first rectangle: "))
length1 = int(input("Enter the length of the first rectangle: "))
width2 = int(input("Enter the width of the second rectangle: "))
lenght2 = int(input("Enter the length of the second rectangle: "))
return width1, length1, width2, lenght2
def calculate_area(width, length):
return width * length
def show_comparation(width1, length1, width2, lenght2):
area1 = calculate_area(width1, lenght2)
area2 = calculate_area(width2, lenght2)
if area1 > area2:
print ("Rectangle number 1 is bigger than rectangle 2")
elif area1 < area2:
print ("Rectangle number 2 is bigger than rectangle 1")
else:
print ("Both rectangles have the same area")
if __name__ == "__main__":
width1, lenght1, width2, lenght2 = get_rect_input()
show_comparation(width1, lenght1, width2, lenght2)

Importing
You don't have to import a function that is in the module you are using (i.e.: the code of the file that you launch).
def inputRect():
"Returns width and lenght in 2 tuples"
w1 = int(input("Width 1st rectangle: "))
l1 = int(input("Lenght 1st rectangle: "))
w2 = int(input("Width 2nd rectangle: "))
l2 = int(input("Lenght 2nd rectangle: "))
# tuple 1 (w & l of rect 1) - tuple 2 (w & l of r2)
return (w1, l1), (w2, l2)
# get the 2 tuple into r1 and r2 to calculate the area
r1, r2 = inputRect()
def calcArea():
"Uses the tuples to calculate area and returns results"
area1, area2 = r1[0] * r1[1], r2[0] * r2[1]
return area1, area2
# This variable memorizes the two areas
rect = calcArea()
def difference():
"Calculates which one area is bigger"
difference = rect[0] - rect[1]
# if ifference > 0 : rectangle 1 has a bigger area
if (difference) > 0:
print("Rectangle numer 1 is bigger than rectangle 2 by", rect[0] - rect[1])
# if ifference < 0 : rectangle 2 has a bigger area
elif (difference) < 0:
print("Rectangle numer 2 is bigger than rectangle 1 by", rect[1] - rect[0])
# else : both rectangles have the same area
else:
print("Both rectangles have the same area")
difference()
OUTPUT:
Width 1st rectangle: 10
Lenght 1st rectangle: 10
Width 2nd rectangle: 20
Lenght 2nd rectangle: 20
Rectangle numer 2 is bigger than rectangle 1 by 300

Related

How to find/calculate the shaded area of this shape in python?

I'm trying to write a python program to calculate the shaded area of the circle in this picture:
[![enter image description here][1]][1]
Here is the input and output:
Enter the radius of a circle: 10
Enter the side of square :3
Enter the width of a rectangle :4
Enter the length of a rectangle :2
The shaded area is : 12.0
Here is my code:
PI = 3.14
radius = float(input("Enter the radius of a circle:"))
area = PI * radius ** 2
side = int(input("Enter the side of square:"))
area = side*side
width = float(input("Enter the width of a rectangle:"))
length = float(input("Enter the length of a rectangle:"))
area = width * length
perimeter = (width + length) * 2
print("The shaded area is :", perimeter)
Problem
You are overwriting the value of area and the previous assigned values are lost.
Example
area = input('enter first value')
10
# the value of area is 10
area = input('enter second value')
3
# the value of area is now 3 and 10 is lost
However you can use area -= number or area += number to substract or add a number to the current value of the variable like so:
area = input('enter first value')
10
# the value of area is 10
area -= input('enter second value')
3
# the value of area is now 10 - 3 = 7
As correctly pointed out in the comments you should also import math and use math.pi instead of using the value 3.14
The correct output for the shaded area is:
Enter the radius of a circle:10
Enter the side of square:3
Enter the width of a rectangle:4
Enter the length of a rectangle:2
The shaded area is : 297.1592653589793
>
I would recommend solution 1 as variables should have meaningful names (unlike solution 2):
Meaningful Variable Names
and solution 3 is a bit harder to read and understand:
Make your code easy to read/understand
Solution 1 (Using different variable names)
import math
def findDimensions():
radius = float(input("Enter the radius of a circle:"))
# radius = 10
circle_area = math.pi * radius ** 2
side = int(input("Enter the side of square:"))
# side = 3
square_area = side * side
# but you could use square_area = side ** 2 as well
width = float(input("Enter the width of a rectangle:"))
# width = 4
length = float(input("Enter the length of a rectangle:"))
# length = 2
rectangle_area = width * length
shaded_area = circle_area - square_area - rectangle_area
print("The shaded area is :", shaded_area)
findDimensions()
Solution 2 (Updating the area variable instead of overwriting it)
import math
def findDimensions():
radius = float(input("Enter the radius of a circle:"))
# radius = 10
area = math.pi * radius ** 2
side = int(input("Enter the side of square:"))
# side = 3
area -= side * side
# but you could use area -= side ** 2 as well
width = float(input("Enter the width of a rectangle:"))
# width = 4
length = float(input("Enter the length of a rectangle:"))
# length = 2
area -= width * length
print("The shaded area is :", area)
findDimensions()
Solution 3 (Moving calculations to the end)
import math
def findDimensions():
radius = float(input("Enter the radius of a circle:"))
# radius = 10
side = int(input("Enter the side of square:"))
# side = 3
width = float(input("Enter the width of a rectangle:"))
# width = 4
length = float(input("Enter the length of a rectangle:"))
# length = 2
shaded_area = (math.pi * radius ** 2) - (side * side) - (width * length)
print("The shaded area is :", shaded_area)
findDimensions()

Python Turtle: how can I coordinate the maximum and minimum sized circle to thier colour?

This is for a school task I have completed all the tasks except this one "Determine the colour of the minimum and maximum sized dots and output the result e.g. The maximum sized dot was orange with a size of 100". I have already found the minimum and maximum sized circles I just can't figure out how to also find the colour of the maximum and minimum sized circles so that I can print ('The maximum size circle is',size,'and it is',colour)
from turtle import *
import random
randomSize=[]
randomColour=[]
countr=0
countg=0
question=input('Do you want to run the program?')
while question=='yes':
#this function will calculate the minimum and maximum circle size form the list randomSize
def minMax(sizes):
minimum=maximum=sizes[0]
for i in sizes[1:]:
if i<minimum:
minimum=i
#im having trouble coordinating the circles size to its colour
elif i> maximum:
maximum=i
print('The maximum size of circles was',maximum)
print('The minimum size of circles was',minimum)
#this function is used to find out whether the there are an even or odd number of red or green
dots
def oddoreven(count,colour1):
result=count%2
if result==0:
print('There were an EVEN number of',colour1, 'dots',count)
else:
print('There were an ODD number of',colour1, 'dots',count)
number=int(input('How many dots do you want?'))
for i in range (number):
x=random.randint(-100,100)
y=random.randint(-100,100)
hideturtle()
penup()
colours=['pink','purple','black','red','green','blue']
colour=random.choice(colours)
if colour=='red':
countr+=1
elif colour=='green':
countg+=1
size=random.randint(0,100)
randomSize.append(size)
randomColour.append(colour)
totalarea=0
goto(x,y)
dot(size,colour)
print("There were",countr,"red dots and", countg,"green dots")
oddoreven(count=countr, colour1='red')
oddoreven(count=countg,colour1='green')
minMax(randomSize)
#this works out the cumulative area for all the values in the list of sizes
for i in randomSize[1:]:
area=3.14*(i**2)
totalarea=totalarea+area
print('The cumulative area for all of the circles is',totalarea)
question= input('Do you want to run the program again?')
Since these are parallel arrays:
randomSize.append(size)
randomColour.append(colour)
A simple fix might be to pass randomColour into minMax() as well and track the index as you loop:
def minMax(sizes, colours):
minimum = maximum = sizes[0]
minColour = maxColour = colours[0]
for index, i in enumerate(sizes[1:], start=1):
if i < minimum:
minimum = i
minColour = colours[index]
elif i > maximum:
maximum = i
maxColour = colours[index]
print('The maximum size of circles was', maximum, "in", maxColour)
print('The minimum size of circles was', minimum, "in", minColour)
Of course, when we see parallel arrays, it usually implies a missing data structure of some sort. Beyond this there are bugs in your code, the most glaring of which is:
randomSize.append(size)
# ...
dot(size,colour)
# ...
for i in randomSize[1:]:
area = 3.14 * (i**2)
The dot() method treats its size argument as a diameter but in your calculation of area, you're treating it as a radius. (The turtle circle() method takes a radius as its argument.) Below is my rework of your code to address the above and other issues:
import math
import turtle
import random
COLOURS = ['pink', 'purple', 'black', 'red', 'green', 'blue']
def minMax(diameters, colours):
''' calculate the minimum and maximum circle diameters and their colours '''
minimumDiameter = maximumDiameter = diameters[0]
minimumColour = maximumColour = colours[0]
for index, diameter in enumerate(diameters[1:], start=1):
if diameter < minimumDiameter:
minimumDiameter = diameter
minimumColour = colours[index]
elif diameter > maximumDiameter:
maximumDiameter = diameter
maximumColour = colours[index]
print("The maximum diameter of circles was", maximumDiameter, "in", maximumColour)
print("The minimum diameter of circles was", minimumDiameter, "in", minimumColour)
def oddOrEven(count, colour):
''' find out whether the there are an even or odd number of red or green dots '''
result = count % 2
if result == 0:
print("There were an EVEN number of", colour, "dots", count)
else:
print("There were an ODD number of", colour, "dots", count)
randomDiameters = []
randomColours = []
countRed = 0
countGreen = 0
answer = 'yes'
while answer.lower().startswith('y'):
number = int(input("How many dots do you want? "))
for _ in range(number):
x = random.randint(-100, 100)
y = random.randint(-100, 100)
turtle.hideturtle()
turtle.penup()
colour = random.choice(COLOURS)
diameter = random.randint(0, 100)
# parallel arrays
randomDiameters.append(diameter)
randomColours.append(colour)
turtle.goto(x, y)
turtle.dot(diameter, colour)
if colour == 'red':
countRed += 1
elif colour == 'green':
countGreen += 1
print("There were", countRed, "red dots and", countGreen, "green dots.")
oddOrEven(count=countRed, colour='red')
oddOrEven(count=countGreen, colour='green')
minMax(randomDiameters, randomColours)
# work out the cumulative area for all the values in the list of diameters
totalArea = 0
for diameter in randomDiameters:
area = math.pi * (diameter / 2) ** 2
totalArea += area
print("The cumulative area for all of the circles is", totalArea)
answer = input("Do you want to run the program again? ")
Since you appended the values in the list, I can only assume that randomSize[0] is the size of randomColour[0], so on and so forth.
randomSize.append(size)
randomColour.append(colour)

I tried creating an area calculator, it keeps stating invalid syntax for a correct code

I started a project in Codeacademy to create an area calculator. However the code elif option == "T": keeps producing syntax error. I looked at the solution but it looks exactly the same. Can anyone please help?
Thanks in advance.
I've tried changing indentation and spacing and changing it from double quotes to single quotes. I even copied and pasted the solution but it still doesn't work.
# it calculates area of circle and triangle
print"Calculator, Ready!"
option = raw_input("What shape. Enter C for Circle or T for triangle: ")
if option == "C":
radius = float(raw_input(" What is the radius: "))
area = 3.14159 * radius ** 2
print area
elif option == 'T':
base = float(raw_input("Base: "))
height = float(raw_input("Height: "))
area = .5 * base * height
print area
You need to indent the area calculations since they're part of the if and elif blocks. You're getting a syntax error because an elif statement must follow an if block.
Also since you're doing print area in both cases, you only need to write it once.
The important bits fixed:
if option == "C":
radius = float(raw_input(" What is the radius: "))
area = 3.14159 * radius ** 2
elif option == 'T':
base = float(raw_input("Base: "))
height = float(raw_input("Height: "))
area = .5 * base * height
print area
In Pythhon, a elif statement can only follow a elif or if statement, but in your code, it follows a print.
You may indent or remove the two following lines:
area = 3.14159 * radius ** 2
print area
My understanding of your code makes me propose you this solution:
# ==========================================
# It calculates area of circle and triangle
# A good practice is to initialise all your variable at the begining
option = None
radius = None
area = None
base = None
height = None
print("Calculator, Ready!")
option = raw_input("What shape. Enter C for Circle or T for triangle: ")
if option == "C":
radius = float(raw_input(" What is the radius: "))
area = 3.14159 * radius ** 2
elif option == 'T':
base = float(raw_input("Base: "))
height = float(raw_input("Height: "))
area = .5 * base * height
print ("The calculated area is: {}".format(area))

"IndexError: list index out of range" For planetary simulator

Traceback (most recent call last):
File "N:\Starry\Planetary Orbits Ver 8.py", line 121
UpdateDisplay(pos) # Updates the 3D displays position of Masses
File "N:\Starry\Planetary Orbits Ver 8.py", line 100, in UpdateDisplay
Stars[i].pos = pos[i]
IndexError: list index out of range
I've been getting this error and I can't find out why, I've checked to see that the Numpy Arrays and Lists have values in them, as shown below in the Python Shell:
Number of stars: 2
Please enter The x position of the Star: 0
Please enter The y position of the Star: 0
Please enter The z position of the Star: 0
Please enter the Radius of the Star: 10
Please enter the Mass of the Star: 5000000
Please enter the X speed of Star: 0
Please enter the Y speed of Star: 0
Please enter the Z speed of Star: 0
Please enter The x position of the Star: 100
Please enter The y position of the Star: 0
Please enter The z position of the Star: 0
Please enter the Radius of the Star: 10
Please enter the Mass of the Star: 5000000
Please enter the X speed of Star: 0
Please enter the Y speed of Star: 0
Please enter the Z speed of Star: 0
[(0, 0, 0), (100, 0, 0)] # Printed PositionList #
[(0, 0, 0), (0, 0, 0)] # Printed MomentumList #
[5000000, 5000000] # Printed MassList #
[10, 10] # Printed RadiusList #
[[ 0 0 0] # Printed Pos Array#
[100 0 0]]
[[0 0 0] # Printed Momentum Array #
[0 0 0]]
[[5000000] # Printed Masses Array #
[5000000]]
[10 10] # Printed Radii Array #
These values show items are going into the lists and arrays, so surely this code would select an item inside the array?
for i in range(Nstars):
UpdateDisplay(pos)
Here is the full program for reference:
Nstars = int(input("Number of stars: ")) # change this to have more or fewer stars
G = 6.7e-11 # Universal gravitational constant
# Typical values
Msun = 2E30
Rsun = 2E9
vsun = 0.8*sqrt(G*Msun/Rsun)
dt = 10.0 #Reprensents the change in time
Nsteps = 0
time = clock()
Nhits = 0
#~~~~~~~~~~~~~~~~~~~~~~~~~~~ Global Data ~~~~~~~~~~~~~~~~~~~~~~~~~~~#
Stars = []
colors = [color.red, color.green, color.blue,
color.yellow, color.cyan, color.magenta]
PositionList = []
MomentumList = []
MassList = []
RadiusList = []
pos = None
Radii = None
Masses = None
F = None
Momentum = None
#~~~~~~~~~~~~~~~~~~~~~~~~~~~ Global Data ~~~~~~~~~~~~~~~~~~~~~~~~~~~#
def Calculations(SpeedX, SpeedY, SpeedZ, x, y, z, Mass, Radius):
px = Mass*(SpeedX)
py = Mass*(SpeedY)
pz = Mass*(SpeedZ)
PositionList.append((x,y,z))
MomentumList.append((px,py,pz))
MassList.append(Mass)
RadiusList.append(Radius)
def StarCreation(Stars,x,y,z,Radius):
Stars = Stars+[sphere(pos=(x,y,z), radius=Radius, color=colors[i % 6],
make_trail=True, interval=10)]
def DataCollection():
x = input("Please enter The x position of the Star: ")
y = input("Please enter The y position of the Star: ")
z = input("Please enter The z position of the Star: ")
Radius = input("Please enter the Radius of the Star: ")
StarCreation(Stars,x,y,z,Radius)
Mass = input("Please enter the Mass of the Star: ")
SpeedX = input("Please enter the X speed of Star: ")
SpeedY = input("Please enter the Y speed of Star: ")
SpeedZ = input("Please enter the Z speed of Star: ")
Calculations(SpeedX, SpeedY, SpeedZ, x, y, z, Mass, Radius)
def Momenta(Momentum, Masses):
vcm = sum(Momentum)/sum(Masses) # velocity of center of mass
Momentum = Momentum-Masses*vcm # make total initial momentum equal zero
def ListToArray(PositionList, MomentumList, MassList, RadiusList):
global pos
pos = array(PositionList)
global Momentum
Momentum = array(MomentumList)
global Masses
Masses = array(MassList)
Masses.shape = (Nstars,1) # Numeric Python: (1 by Nstars) vs. (Nstars by 1)
global Radii
Radii = array(RadiusList)
Momenta(Momentum, Masses)
def Forces(pos, Radii, Masses):
# Compute all forces on all stars
r = pos-pos[:,newaxis] # all pairs of star-to-star vectors (Where r is the Relative Position Vector
for n in range(Nstars):
r[n,n] = 1e6 # otherwise the self-forces are infinite
rmag = sqrt(sum(square(r),-1)) # star-to-star scalar distances
hit = less_equal(rmag,Radii+Radii[:,newaxis])-identity(Nstars)
hitlist = sort(nonzero(hit.flat)[0]).tolist() # 1,2 encoded as 1*Nstars+2
global F
F = G*Masses*Masses[:,newaxis]*r/rmag[:,:,newaxis]**3 # all force pairs
def SelfForces(F):
F[n,n] = 0
def UpdateMomentaPositions(Momentum, pos, Masses):
Momentum = Momentum+sum(F,1)*dt
pos = pos+(Momentum/Masses)*dt
def UpdateDisplay(pos):
Stars[i].pos = pos[i]
#~~~~~~~~~~~~~~~~~~~~~~~~~ Actual Proagram ~~~~~~~~~~~~~~~~~~~~~~~~~#
for i in range(Nstars):
DataCollection()
ListToArray(PositionList, MomentumList, MassList, RadiusList)
print (PositionList)
print (MomentumList)
print (MassList)
print (RadiusList)
print (pos)
print (Momentum)
print (Masses)
print (Radii)
while True:
rate(100) # No more than 100 loops per second on fast computers
Forces(pos, Radii, Masses)# Computes all the forces between masses
for n in range(Nstars):
SelfForces(F) # No self forces
UpdateMomentaPositions(Momentum, pos, Masses) # Updates the Momentum and Positions of Stars
for i in range(Nstars):
UpdateDisplay(pos) # Updates the 3D displays position of Masses
Your issue is that you never actually add any stars to Stars when you call StarCreation function. You actually only reassign a local Stars list that shadows the global Stars with that line :
Stars = Stars+[sphere(pos=(x,y,z), radius=Radius, color=colors[i % 6],
make_trail=True, interval=10)]
You have two solutions to that issue :
You can modify global Stars list inplace via either Stars+=[sphere(...)] or Stars.append(sphere(...))
Or tell python that Stars is a global variable and that it shouldn't be shadowed, like this :
.
def StarCreation(Stars,x,y,z,Radius):
global Stars
Stars = Stars+[sphere(pos=(x,y,z), radius=Radius, color=colors[i % 6],
make_trail=True, interval=10)]
Edit : the mistake I assumed didn't exist , sorry.

repeating pattern with variables in python

I'm trying to make a repeating pattern program in Python that asks you for how many sides you want the repeated shape to be, how many times it should be repeated and the color of the background and shape fill. It should draw the shape before turning by 360 divided by the amount of sides. However, it keeps repeating on the spot continually. My code is below.
from turtle import*
bgColor = input("What colour background do you want?: ")
fillColor = input("What colour shape fill do you want?: ")
numberOfSides = int(input("How many sides?: "))
rotationsWanted = int(input("How many rotations?: "))
rotationsCompleted = 0
def drawshape():
fillcolor(fillColor)
bgcolor(bgColor)
begin_fill()
while (rotationsCompleted < rotationsWanted):
for x in range(numberOfSides):
forward (100)
right(360/numberOfSides)
end_fill()
drawshape()
right(360/rotationsWanted)
rotationsCompleted = rotationsCompleted + 1
Try to modify the while-loop
rotationsCompleted = 0
while (rotationsCompleted < rotationsWanted):
rotationsCompleted = rotationsCompleted + 1
and after end_fill() you should go to an other position maybe using goto(100, 100) to draw the next shape at a different position.

Categories

Resources