0% found this document useful (0 votes)
14 views8 pages

Python Code for Basic Operations

The document contains various Python code snippets demonstrating different functionalities such as swapping values, rotating lists, calculating distances, and manipulating dictionaries and lists. It also includes user input prompts for various calculations, string manipulations, and library management. Additionally, it covers mathematical operations and the installation of packages like numpy.

Uploaded by

krishna16.rani
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views8 pages

Python Code for Basic Operations

The document contains various Python code snippets demonstrating different functionalities such as swapping values, rotating lists, calculating distances, and manipulating dictionaries and lists. It also includes user input prompts for various calculations, string manipulations, and library management. Additionally, it covers mathematical operations and the installation of packages like numpy.

Uploaded by

krishna16.rani
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

x= int(input("enter X value:"))

Y= int(input("enter Y value:"))
temp=x
x=y
y=temp
print("/nAfter swapping value of x=",x)
print("After swapping value of y=",y)

enter X value:9
enter Y value:8
/nAfter swapping value of x= 8
After swapping value of y= 9

n=int(input("enter n value:"))
list_1=[1,2,3,4,5,6]
list_2=(list_1[-n:]+list_1[:n])
print("Rotating{} by {} position is {}".format(list_1,n,list_2))

enter n value:7
Rotating[1, 2, 3, 4, 5, 6] by 7 position is [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]

x1=float(input("enter x1:"))
y1=float(input("enter y1:"))
x2=float(input("enter x2:"))
y2=float(input("enter y2:"))
distance=((x1-x2)**2+(y1-y2)**2**0.5)
print("Distance between points({},{}) and ({},{}) is {}".format(x1,y1,x2,y2,distance))

enter x1:8
enter y1:5
enter x2:9
enter y2:7
Distance between points(8.0,5.0) and (9.0,7.0) is (0.29039113469833866-2.568939189549123j)

N = int(input("please enter the value of N:"))


square=0
sum=0
print('The sum of the given number',N,'is:')
for i in range(1,N+1):
square=square+(i*i)
print(square,end='')
print('\n',end='')
print('The sum pf the given number',N,'is:')
for i in range(1,N+1):
sum=sum+i
print(sum,end='')
please enter the value of N:10
The sum of the given number 10 is:
1
The sum pf the given number 10 is:
136101521283645555
The sum pf the given number 10 is:
565861657076839110011014
The sum pf the given number 10 is:
11111311612012513113814615516530
The sum pf the given number 10 is:
16616817117518018619320121022055
The sum pf the given number 10 is:
22122322623023524124825626527591
The sum pf the given number 10 is:
276278281285290296303311320330140
The sum pf the given number 10 is:
331333336340345351358366375385204
The sum pf the given number 10 is:
386388391395400406413421430440285
The sum pf the given number 10 is:
441443446450455461468476485495385
The sum pf the given number 10 is:
496498501505510516523531540550
X=int(input("please enter the value of X:"))
Y=int(input("please enter the value of Y:"))
print('The series for',X,'and',Y,'is:',end='')
for i in range(0,X*2+Y,Y):
if X-i>=0:
a=X-i
print(a,end='')
elif X-i < 0:
a=X-i
a=a+a*-2
print(a,end='')
please enter the value of X:5
please enter the value of Y:4
The series for 5 and 4 is:5137
n = int(input("please enter the value of N:"))
k = n - 1
for i in range(0, n):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i+1):
print("* ", end="")
print("\r")

please enter the value of N:5


*
* *
* * *
* * * *
* * * * *
n = int(input("please enter the value of N:"))
k = n - 1
for i in range(0, n):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i+1):
print("* ", end="")
print("\r")
please enter the value of N:5
*
* *
* * *
* * * *
* * * * *
library = list(map(str,input("Enter the items in the library seperated by space:").split()))
print("list of items in the library:",library)
[Link]("Newspaper")
print("list of items in the library after appending new item:",library)
[Link](3,"eAssets")
print("list of items in the library after adding new item at 3rd index:",library)
[Link]("eAssets")
print("list of items in the library after removing new item:",library)
del library[2]
print("list of items in the library after removing an item at 2nd index:")
print("The list library is converted to tuple library now")
libraryt=tuple(library)
print("The items in the tuple library is",libraryt)
print("length of the tuple library is:",len(libraryt))
if "newspaper" in libraryt:
print("yes,'newspaper' is an item in the library tuple")
else:
print("No,'newspaper' is not an item in the library tuple")

str_x ="common materials required for construction"


print("Actual string:",str_x)
obj_slice=slice(7,25)
print("The substring after slice(7,25):",str_x[obj_slice])
materiallist = list(map(str, input("Enter the materiallist required for construction seperated by space:").split()))
print("original list:",materiallist)
obj_slice=slice(1,5,1)
print("sliced list with slice(1,5,1):",materiallist[obj_slice])
obj_slice = slice(-1,-4,-1)
print("The list after negative values for slice:" ,materiallist[obj_slice])
print("sliced list with[2:6:1:",materiallist[2:6:1])
print("sliced list with[1::]:",materiallist[1::])
materialtuple = list(map(str, input("Enter the materialtuple required for construction seperated by space:").split()))
print("original tuple:",materialtuple)
obj_slice = slice(4)
print("The tuple after slice:",materialtuple[obj_slice])
print("Sliced tuple with [:]",materialtuple[:])
print("sliced tuple with[::-1]=",materialtuple[::-1])
print("sliced tuple with[-1:-4:-1]=",materialtuple[-1:-4:-1])
list = list(map(str,input("Enter the languages seperated by space:").split()))
language = set(list)
print(language)
print("german" in Language)
[Link]("chinese")
print(language)
[Link](["Tamil","Telugu","Malayalam"])
print(language)
print(len(language))
[Link]("chinese")
print(language)
[Link]("French")
print(language)
x = [Link]()
print(x)
print(language)
[Link]()
print(language)
del language
print(language)
v1=input("Enter input pair for keys'chasis':")
v2=input("Enter input pair for keys'engine':")
v3=input("Enter input pair for keys'capacity':")
v4=input("Enter input pair for keys'variant':")
automobile={"chasis":v1,"Engine":v2,"capacity":v3,"variant":v4}
print(automobile)
x = automobile["Engine"]
print(x)
x=[Link](Eengine")
print(x)
automobile['cost'] ='75000'
print(automobile)
automobile['Engine']="Twincyclinder"
print(automobile)
print([Link]("cost"))
print(automobile)
print([Link]())
print(automobile)
del automobile["Engine"]
print(automobile)
[Link]()
print(automobile)
del automobile
print(automobile)
v1=input("Enter number of 'pillars':")
v2=input("Enter number of 'Floors':")
v3=input("Enter number of 'Windows':")
civilelements={"pillars":v1, "floors":v2, "windows":v3}
print(civilelements)
print("contents of the dictionary =",civilelements)
print("checking if pillars is a key in dictionary =", "pillars" in civilelements)
print("checking if walls is not a key in dictionary=","walls" not in civilelements)
print("cannot check with pair value 50 in dictionary(true-pair can be checked, false pair cannot be checked =","50" in civilelements)
print("pair values in the dictionary=")
for i in civilelements:
print(civilelements[i])
print("Length of the dictionary =",len(civilelements))
print("sort the keys of the dictionary in alphabetical order=",sorted(civilelements))

Enter number of 'pillars':2


Enter number of 'Floors':3
Enter number of 'Windows':5
{'pillars': '2', 'floors': '3', 'windows': '5'}
contents of the dictionary = {'pillars': '2', 'floors': '3', 'windows': '5'}
checking if pillars is a key in dictionary = True
checking if walls is not a key in dictionary= True
cannot check with pair value 50 in dictionary(true-pair can be checked, false pair cannot be checked = False
pair values in the dictionary=
2
Length of the dictionary = 3
sort the keys of the dictionary in alphabetical order= ['floors', 'pillars', 'windows']
3
Length of the dictionary = 3
sort the keys of the dictionary in alphabetical order= ['floors', 'pillars', 'windows']
5
Length of the dictionary = 3
sort the keys of the dictionary in alphabetical order= ['floors', 'pillars', 'windows']
def factorial(n):
if n<0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n>1):
fact*= n
n -= 1
return fact
num = 5;
print("Factorial of",num,"is",factorial(num))
list1=[]
num = int(input("Enter number of elements in list:"))
for i in range(1,num+1):
ele = int(input("Enter elements:"))
[Link](ele)
print("largest elements is:", max(list1))

def calculate_area(name):\
name = [Link]
if name == "rectangle":
l = int(input("Enter rectangle length:"))
b = int(input("Enter rectangle breadth:"))
rect_area = l * b
print("Area of rectangle is{rect_area}.")
elif name == "square":
s = int(input("Enter square side length:"))
sqt_area = s * s
print("Area of square is{sqt_area}.")
elif name == "triangle":
h = int(input("enter the triangle height length:"))
b = int(input("enter the triangle breadth length:"))
tri_area = 0.5 * b * h
print("Area of a triangle is{tri_area}.")
elif name == "circle":
r = int(input("Enter circle radius length":))
pi = 3.14
circ_area = pi * r * r
print("The area of circle is{circ_area}.")
else:
print(" Not available ")
if__name__ == "__main__":
print("Calculate shape area")
shape_name = input("Enter the name of shape whose area you want to find:")
calculate_area(shape_name)
a = input("please enter the string a:")
x = a[::-1]
print("Reverse string is:",x)
please enter the string a:python
Reverse string is: nohtyp
def palindrome(x):
return x == x[::-1]
x = input("please enter the stirng x:")
y = palindrome(x)
if y:
print("Yes, The string is palindrome")
else:
print("no, The string is not a palindrome")

x = input("Please enter the string X:")


y = input("Please enter the char to be count:")
counter = [Link](y)
print("count of " + y +" in given string is:", str(counter))
Please enter the string X:hello
Please enter the char to be count:e
count of e in given string is: 1
x = input("please enter the string x:")
a,b = input("Please enter which the char to be replace:").split()
re = [Link](a,b)
print("The replaced string is",re)
please enter the string x:stick
Please enter which the char to be replace:i u
The replaced string is stuck
import math as m
a,b,c = input('Enter the set of 3 numbers for finding the square root, factorial and log base2:').split(',')
a = int(a)
b = int(b)
c = int(c)
print('square root',[Link](a))
print('Factorial',[Link](b))
print('Log base 2',m.log2(c))
Enter the set of 3 numbers for finding the square root, factorial and log base2:100, 2, 50
square root 10.0
Factorial 2
Log base 2 5.643856189774724
pip install numpy
Collecting numpyNote: you may need to restart the kernel to use updated packages.
[notice] A new release of pip is available: 23.1.2 -> 23.3.1
[notice] To update, run: [Link] -m pip install --upgrade pip
Downloading numpy-1.26.2-cp311-cp311-win_amd64.whl (15.8 MB)
0.0/15.8 MB ? eta -:--:--
0.3/15.8 MB 21.2 MB/s eta 0:00:01
0.3/15.8 MB 21.2 MB/s eta 0:00:01
- 0.4/15.8 MB 3.8 MB/s eta 0:00:05
-- 1.0/15.8 MB 6.9 MB/s eta 0:00:03
-- 1.0/15.8 MB 6.9 MB/s eta 0:00:03
-- 1.1/15.8 MB 5.2 MB/s eta 0:00:03
-- 1.1/15.8 MB 5.2 MB/s eta 0:00:03
---- 1.7/15.8 MB 4.8 MB/s eta 0:00:03
------ 2.5/15.8 MB 6.3 MB/s eta 0:00:03
-------- 3.2/15.8 MB 7.6 MB/s eta 0:00:02
---------- 4.1/15.8 MB 8.7 MB/s eta 0:00:02
------------ 4.9/15.8 MB 9.8 MB/s eta 0:00:02
-------------- 5.6/15.8 MB 10.1 MB/s eta 0:00:02
--------------- 6.1/15.8 MB 10.5 MB/s eta 0:00:01
---------------- 6.6/15.8 MB 10.5 MB/s eta 0:00:01
----------------- 7.0/15.8 MB 10.4 MB/s eta 0:00:01
------------------ 7.4/15.8 MB 10.6 MB/s eta 0:00:01
-------------------- 8.1/15.8 MB 10.8 MB/s eta 0:00:01
--------------------- 8.6/15.8 MB 11.0 MB/s eta 0:00:01
----------------------- 9.1/15.8 MB 11.0 MB/s eta 0:00:01
------------------------ 9.7/15.8 MB 11.1 MB/s eta 0:00:01
------------------------- 10.2/15.8 MB 11.3 MB/s eta 0:00:01
-------------------------- 10.8/15.8 MB 12.4 MB/s eta 0:00:01
--------------------------- 11.3/15.8 MB 13.1 MB/s eta 0:00:01
----------------------------- 11.8/15.8 MB 14.9 MB/s eta 0:00:01
------------------------------ 12.5/15.8 MB 14.6 MB/s eta 0:00:01
-------------------------------- 13.0/15.8 MB 14.6 MB/s eta 0:00:01
--------------------------------- 13.5/15.8 MB 13.9 MB/s eta 0:00:01
---------------------------------- 14.1/15.8 MB 13.6 MB/s eta 0:00:01
------------------------------------ 14.6/15.8 MB 13.6 MB/s eta 0:00:01
------------------------------------- 15.1/15.8 MB 13.1 MB/s eta 0:00:01
-------------------------------------- 15.7/15.8 MB 13.1 MB/s eta 0:00:01
-------------------------------------- 15.8/15.8 MB 13.1 MB/s eta 0:00:01
-------------------------------------- 15.8/15.8 MB 13.1 MB/s eta 0:00:01
--------------------------------------- 15.8/15.8 MB 11.9 MB/s eta 0:00:00
Installing collected packages: numpy
Successfully installed numpy-1.26.2
pip install counter
Collecting counterNote: you may need to restart the kernel to use updated packages.
[notice] A new release of pip is available: 23.1.2 -> 23.3.1
[notice] To update, run: [Link] -m pip install --upgrade pip
Downloading [Link] (5.2 kB)
Installing build dependencies: started
Installing build dependencies: finished with status 'done'
Getting requirements to build wheel: started
Getting requirements to build wheel: finished with status 'done'
Preparing metadata ([Link]): started
Preparing metadata ([Link]): finished with status 'done'
Building wheels for collected packages: counter
Building wheel for counter ([Link]): started
Building wheel for counter ([Link]): finished with status 'done'
Created wheel for counter: filename=[Link] size=5425 sha256=648dae8509839c6ec2adf4b5e5f37e977bde9380da541c92d30394206bb4d781
Stored in directory: c:\users\laksh\appdata\local\pip\cache\wheels\08\5b\a0\8f15503db6a45a1d8747bf0f1438411cb37484ac4dfdfe6c0b
Successfully built counter
Installing collected packages: counter
Successfully installed counter-1.0.0
pip install stats
Collecting statsNote: you may need to restart the kernel to use updated packages.
[notice] A new release of pip is available: 23.1.2 -> 23.3.1
[notice] To update, run: [Link] -m pip install --upgrade pip
Downloading [Link] (127 kB)
0.0/127.6 kB ? eta -:--:--
-------------------------------------- 127.6/127.6 kB 3.8 MB/s eta 0:00:00
Installing build dependencies: started
Installing build dependencies: finished with status 'done'
Getting requirements to build wheel: started
Getting requirements to build wheel: finished with status 'done'
Preparing metadata ([Link]): started
Preparing metadata ([Link]): finished with status 'done'
Building wheels for collected packages: stats
Building wheel for stats ([Link]): started
Building wheel for stats ([Link]): finished with status 'done'
Created wheel for stats: filename=[Link] size=24297 sha256=4deb14eb59e57cfd242213b5108017ed4846f80c2192323b88bc3be8c6187023
Stored in directory: c:\users\laksh\appdata\local\pip\cache\wheels\57\7d\91\f1d0158783f74ab6ad725b00aa6a2c6e976cea652eb72616c6
Successfully built stats
Installing collected packages: stats
Successfully installed stats-0.1.2a0
import numpy as n
from collections import counter
from scipy import stats
a = [11,21,34,22,27,11,23,21]
mean = sum(a)/len(a)
print(mean)
def median(nums):
[Link]()
if len(nums)%2 == 0:
return int(nums[len(nums)//2-1]+nums[len(nums)//2])/2
else:
return nums[len(nums)//2]
print(median(a))
data = dict(counter(a))
mode = [K for K, V in [Link]() if v == max(list([Link]()))]
print(mode)
print([Link](a)[0][0])
def quartiles(nums):
nums = sorted(nums)
Q1 = median(nums[:len(nums)//2])
Q2 = median(nums)
if len(nums)%2 == 0:
Q3 = median(nums[len(nums)//2+1:])
return Q1,Q2,Q3
def median(nums):
[Link]()
if len(nums)%2 == 0:
return int(nums[len(nums)//2-1]+nums[len(nums)//2])/2
else:
return nums[len(nums)//2]
print(quartiles(a))
n = len(a)
std = (sum(map(lambda x:(x-sum(a)/n)**2,a))/n)**0.5
print(std)
print([Link](a))
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
Cell In[1], line 2
1 import numpy as n
----> 2 from collections import counter
3 from scipy import stats
4 a = [11,21,34,22,27,11,23,21]

ImportError: cannot import name 'counter' from 'collections' (C:\Users\laksh\AppData\Local\Programs\Python\Python311\Lib\collections\__init__.py)


Counter is only supported python 2.7 and higher and is not available in earlier versions.
output_file = open("C://Nanda/[Link]","w")
with open("C://Nanda/[Link]","r") as scan:
output_file.write([Link]())
output_file.close()
test_string ="Tutorials point is a learning platform"
print("The original string is:"+ test_string)
res = len(test_string.split())
print("The number of words in string are:"+str(res))
The original string is:Tutorials point is a learning platform
The number of words in string are:6
sentence = input("Enter sentence:")
longest = max([Link](),key=len)
print("Longest word is: ",longest)
print("And its length is: ",len(longest))
Enter sentence:Python programming and problem solving
Longest word is: programming
And its length is: 11
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
except exception as e:
print("can't divide by zero")
print(e)
else:
print("Will not throw division by zero")
Enter a:10
Enter b:5
a/b = 2
Will not throw division by zero
age = int(input("Enter Age:"))
if age>=18:
status = "Eligible"
print("You are eligible for vote")
else:
Status = "Not Eligible"
print("You are",status,"For vote.")
sub1=int(input("Enter marks of the first subject: "))
sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=90):
print("Grade: A")
elif(avg>=80 and avg<90):
print("Grade: B")
elif(avg>=70 and avg<80):
print("Grade: C")
elif(avg>=60 and avg<70):
print("Grade: D")
else:
print("Grade: F")
pip install pygame
Collecting pygameNote: you may need to restart the kernel to use updated packages.
[notice] A new release of pip is available: 23.1.2 -> 23.3.1
[notice] To update, run: [Link] -m pip install --upgrade pip
Downloading pygame-2.5.2-cp311-cp311-win_amd64.whl (10.8 MB)
0.0/10.8 MB ? eta -:--:--
0.3/10.8 MB 7.9 MB/s eta 0:00:02
-- 0.7/10.8 MB 8.8 MB/s eta 0:00:02
----- 1.6/10.8 MB 11.4 MB/s eta 0:00:01
--------- 2.5/10.8 MB 13.3 MB/s eta 0:00:01
---------- 2.8/10.8 MB 13.9 MB/s eta 0:00:01
---------- 2.8/10.8 MB 13.9 MB/s eta 0:00:01
---------- 2.8/10.8 MB 13.9 MB/s eta 0:00:01
---------- 2.8/10.8 MB 13.9 MB/s eta 0:00:01
---------- 2.8/10.8 MB 13.9 MB/s eta 0:00:01
---------- 2.8/10.8 MB 13.9 MB/s eta 0:00:01
---------- 2.8/10.8 MB 13.9 MB/s eta 0:00:01
---------- 2.8/10.8 MB 13.9 MB/s eta 0:00:01
---------- 2.8/10.8 MB 13.9 MB/s eta 0:00:01
---------- 2.8/10.8 MB 13.9 MB/s eta 0:00:01
---------- 2.9/10.8 MB 4.2 MB/s eta 0:00:02
------------ 3.4/10.8 MB 4.5 MB/s eta 0:00:02
--------------- 4.3/10.8 MB 5.4 MB/s eta 0:00:02
------------------- 5.2/10.8 MB 6.1 MB/s eta 0:00:01
---------------------- 6.1/10.8 MB 6.8 MB/s eta 0:00:01
------------------------- 7.0/10.8 MB 7.4 MB/s eta 0:00:01
---------------------------- 7.8/10.8 MB 7.9 MB/s eta 0:00:01
------------------------------- 8.4/10.8 MB 8.1 MB/s eta 0:00:01
--------------------------------- 9.0/10.8 MB 8.4 MB/s eta 0:00:01
----------------------------------- 9.6/10.8 MB 8.6 MB/s eta 0:00:01
-------------------------------------- 10.3/10.8 MB 8.6 MB/s eta 0:00:01
--------------------------------------- 10.8/10.8 MB 8.8 MB/s eta 0:00:01
---------------------------------------- 10.8/10.8 MB 8.5 MB/s eta 0:00:00
Installing collected packages: pygame
Successfully installed pygame-2.5.2
import pygame
# initialize pygame
[Link]()
# define width of screen
width = 1000
# define height of screen
height = 600
screen_res = (width, height)
screen = [Link].set_mode(screen_res)

# define colors
red = (255, 0, 0)
black = (0, 0, 0)

# define ball
ball_obj = [Link](
surface=screen, color=red, center=[100, 100], radius=40)
# define speed of ball
# speed = [X direction speed, Y direction speed]
speed = [1, 1]

# game loop
while True:
# event loop
for event in [Link]():
# check if a user wants to exit the game or not
if [Link] == [Link]:
exit()

# fill black color on screen


[Link](black)

# move the ball


# Let center of the ball is (100,100) and the speed is (1,1)
ball_obj = ball_obj.move(speed)
# Now center of the ball is (101,101)
# In this way our wall will move

# if ball goes out of screen then change direction of movement


if ball_obj.left <= 0 or ball_obj.right >= width:
speed[0] = -speed[0]
if ball_obj.top <= 0 or ball_obj.bottom >= height:
speed[1] = -speed[1]

# draw ball at new centers that are obtained after moving ball_obj
[Link](surface=screen, color=red,
center=ball_obj.center, radius=40)

# update screen
[Link]()
import pygame,sys
[Link]()
size = width,height =10000,6000
speed = [2,2]
screen = [Link].set_mode(size)
[Link].set_caption("Bouncing Ball")
ball = [Link]("C://Nanda/[Link]")
ballrect = ball.get_rect()
while True:
for event in [Link]():
if [Link] == [Link]:
[Link]()
ballrect = [Link](speed)
if [Link]<0 or [Link]>width:
speed[0] =-speed[0]
if [Link]<0 or [Link]>height:
speed[1] = -speed[1]
[Link]("white")
[Link](ball,ballrect)
[Link]()
import pygame
import math
import sys
[Link]()
width = 1000
height = 600
screen_res = (width, height)
[Link].set_caption("Elliptical orbit")
clock = [Link]()
while True:
for event in [Link]():
if [Link] == [Link]:
[Link]()
Xradius = 250
Yradius = 100
for degree in range(0,360,10):
X1 = int([Link](degree*2*[Link]/360*xradius)+300)
X2 = int([Link](degree*2*[Link]/360*xradius)+150)
[Link]("black")
[Link](screen,(255,70,0),[300,150],40)
[Link](screen,[Link]("red"),[50,50,500,200],1)
[Link](screen,(0,255,0),[x1,y1],20)
[Link]()
[Link](5)

import pygame
import math

# initialize the pygame


[Link]()
# define width of screen
width = 1000
# define height of screen
height = 600
screen_res = (width, height)

[Link].set_caption("GFG Elliptical orbit")


screen = [Link].set_mode(screen_res)

# define colors in RGB format


# These colors will be used in our game
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
cyan = (0, 255, 255)

# centers of screen
X_center = width//2
Y_center = height//2

# radius of ellipse
# X_ellipse is major radius of ellipsis
X_ellipse = 400
# Y_ellipse is minor radius of ellipsis
Y_ellipse = 225

# [Link]() will be used further


# in the game loop to control
# the speed of the planet.
clock = [Link]()
while True:
for degree in range(0, 360, 1):
# event loop
for event in [Link]():
if [Link] == [Link]:
exit()

# fill black color on screen


[Link]([0, 0, 0])

# We will find coordinates of 2 planet


# that will rotate in same ellipse
# calculate coordinates of planet 1
# x_planet is x coordinate
x_planet_1 = int([Link](degree * 2 * [Link]/360)
* X_ellipse) + X_center
# y_planet is y coordinate
y_planet_1 = int([Link](degree * 2 * [Link]/360)
* Y_ellipse) + Y_center

# calculate coordinates of planet 2


# As we want our planets to be opposite to
# each other so we will maintain a difference
# of 180 degrees between then
degree_2 = degree+180
# degree will be always between 0 and 360
if degree > 180:
degree_2 = degree-180

# x_planet is x coordinate
x_planet_2 = int([Link](degree_2 * 2 * [Link]/360)
* X_ellipse) + X_center
# y_planet is y coordinate
y_planet_2 = int([Link](degree_2 * 2 * [Link]/360)
* Y_ellipse) + Y_center
# draw circle in center of screen
[Link](surface=screen, color=red, center=[
X_center, Y_center], radius=60)

# draw ellipse
# Coordinate of left topmost point is (100,75)
# width of ellipse = 2*(major radius of ellipse)
# height of ellipse = 2*(minor radius of ellipse)
[Link](surface=screen, color=green,
rect=[100, 75, 800, 450], width=1)

# draw both planets


# x_planet_1, y_planet_1, x_planet_2
# and y_planet_2 are calculated above
[Link](surface=screen, color=blue, center=[
x_planet_1, y_planet_1], radius=40)
[Link](surface=screen, color=cyan, center=[
x_planet_2, y_planet_2], radius=40)

# Frame Per Second /Refresh Rate


[Link](5)
# update screen
[Link]()

You might also like