0% found this document useful (0 votes)
24 views

Py (1) Procedure 2024

sdgasfgsad

Uploaded by

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

Py (1) Procedure 2024

sdgasfgsad

Uploaded by

santo nino
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

13 Write programs using Python language.

13.1 Use Python from command line


13.1.1 Install, set up the environment & run Python. Use Command Line and IDE to create and
execute a python program.
Aim: to Install, set up the environment & run Python. Use Command Line and IDE to create and
execute a python program.
Tools/Equipments/Instruments: A working PC ,Python 3.11 application setup

PROCEDURE

Step 1 — Downloading the Python Installer


1. Go to the official Python download page for Windows.
2. Find a stable Python 3 release. This tutorial was tested with Python version 3.10.10.
3. Click the appropriate link for your system to download the executable file: Windows installer (64-
bit) or Windows installer (32-bit).
Step 2 — Running the Executable Installer
1. After the installer is downloaded, double-click the .exe file, for example python-3.10.10-amd64.exe,
to run the Python installer.
2. Select the Install launcher for all users checkbox, which enables all users of the computer to access
the Python launcher application.
3. Select the Add python.exe to PATH checkbox, which enables users to launch Python from the
command line.
4. If you’re just getting started with Python and you want to install it with default features as
described in the dialog, then click Install Now and go to Step 4 - Verify the Python Installation. To
install other optional and advanced features, click Customize installation and continue.
5. The Optional Features include common tools and resources for Python and you can install all of
them, even if you don’t plan to use them.
Select some or all of the following options:
 Documentation: recommended
 pip: recommended if you want to install other Python packages, such as NumPy or pandas
 tcl/tk and IDLE: recommended if you plan to use IDLE or follow tutorials that use it
 Python test suite: recommended for testing and learning
 py launcher and for all users: recommended to enable users to launch Python from the command
line
6. Click Next.
7. The Advanced Options dialog displays.
Select the options that suit your requirements:
 Install for all users: recommended if you’re not the only user on this computer
 Associate files with Python: recommended, because this option associates all the Python file types
with the launcher or editor
 Create shortcuts for installed applications: recommended to enable shortcuts for Python
applications
 Add Python to environment variables: recommended to enable launching Python
 Precompile standard library: not required, it might down the installation
 Download debugging symbols and Download debug binaries: recommended only if you plan to
create C or C++ extensions
Make note of the Python installation directory in case you need to reference it later.
8. Click Install to start the installation.
9. After the installation is complete, a Setup was successful message displays.
Step 3 — Adding Python to the Environment Variables (optional)
Skip this step if you selected Add Python to environment variables during installation.
If you want to access Python through the command line but you didn’t add Python to your
environment variables during installation, then you can still do it manually.
Before you start, locate the Python installation directory on your system. The following directories
are examples of the default directory paths:
 C:\Program Files\Python310: if you selected Install for all users during installation, then the
directory will be system wide
 C:\Users\Sammy\AppData\Local\Programs\Python\Python310: if you didn’t select Install for all
users during installation, then the directory will be in the Windows user path
Note that the folder name will be different if you installed a different version, but will still start
with Python.
1. Go to Start and enter advanced system settings in the search bar.
2. Click View advanced system settings.
3. In the System Properties dialog, click the Advanced tab and then click Environment Variables.
4. Depending on your installation:
 If you selected Install for all users during installation, select Path from the list of System
Variables and click Edit.
 If you didn’t select Install for all users during installation, select Path from the list of User
Variables and click Edit.
5. Click New and enter the Python directory path, then click OK until all the dialogs are closed.
Step 4 — Verify the Python Installation
You can verify whether the Python installation is successful either through the command line or
through the Integrated Development Environment (IDLE) application, if you chose to install it.
Go to Start and enter cmd in the search bar. Click Command Prompt.
Enter the following command in the command prompt:
python --version
An example of the output is:
Output
Python 3.10.10
You can also check the version of Python by opening the IDLE application. Go to Start and
enter python in the search bar and then click the IDLE app, for example IDLE (Python 3.10 64-bit).
You can start coding in Python using IDLE or your preferred code editor.

Result: Installed and set up the environment & run Python and Used Command Line and IDE to
create and execute a python program

13 Write programs using Python language.


13.2 Perform Operations using Data Types and Operators
13.2.1 Write and test a python program to demonstrate print statement, comments, different
types of variables.

Aim: to Write and test a python program to demonstrate print statement, comments, different
types of variables.
Tools/Equipments/Instruments: A working PC ,Python 3.11 application

PROCEDURE

Step 1 : Start python IDLE shell and click on file menu and select new file
Step 2: Type the below code in the opened window .
Step 3: save it. Select run module from run menu

#Program 1
A=10
B=20
C=a+b
Print(“the sum”,c)

#Print statement
# Python 3.x program showing
# how to print data on
# a screen

# One object is passed


print("GeeksForGeeks")

x=5
# Two objects are passed
print("x =", x)

# code for disabling the softspace feature


print('G', 'F', 'G', sep='')

# using end argument


print("Python", end='@')
print("GeeksforGeeks")

#commenting
#print("Hello, World!")
print("Cheers, Mate!")
#multiline
#This is a comment
#written in
#more than just one line
print("Hello, World!")

#Different type of variables

# An integer assignment
age = 45

# A floating point
salary = 1456.8

# A string
name = "John"

print(age)
print(salary)
print(name)

x = str("Hello World")
print(x)

x = int(20)
print(x)

x = float(20.5)
print(x)

x = complex(1j)
print(x)

x = list(("apple", "banana", "cherry"))


print(x)

x = tuple(("apple", "banana", "cherry"))


print(x)

x = range(6)
print(x)

x = dict(name="John", age=36)
print(x)

x = set(("apple", "banana", "cherry"))


print(x)

x = frozenset(("apple", "banana", "cherry"))


print(x)

x = bool(5)
print(x)

x = bytes(5)
print(x)

x = bytearray(5)
print(x)

x = memoryview(bytes(5))
print(x)

x=none
print(x)

Result: Wrote and tested python program to demonstrate print statement, comments, different
types of variables.

13 Write programs using Python language.


13.2 Perform Operations using Data Types and Operators
13.2.2 Write and test a python program to perform data and data type operations, string
operations, date, input and output, output formatting and operators.

Aim: to Write and test a python program to perform data and data type operations, string
operations, date, input and output, output formatting and operators.
Tools/Equipments/Instruments: A working PC ,Python 3.11 application
PROCEDURE

String operations
# Python Program for Creation of String

# Creating a String with single Quotes


String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String with double Quotes


String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)

# Creating a String with triple Quotes


String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)

# Creating String with triple Quotes allows multiple lines


String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)

# Python Program to Access


# characters of String

String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)

# Printing First character


print("\nFirst character of String is: ")
print(String1[0])

# Printing Last character


print("\nLast character of String is: ")
print(String1[-1])

#Program to reverse a string


gfg = "geeksforgeeks"
print(gfg[::-1])
# Python Program for
# Formatting of Strings

# Default order
String1 = "{} {} {}".format('Geeks', 'For', 'Life')
print("Print String in default order: ")
print(String1)

# Positional Formatting
String1 = "{1} {0} {2}".format('Geeks', 'For', 'Life')
print("\nPrint String in Positional order: ")
print(String1)

# Keyword Formatting
String1 = "{l} {f} {g}".format(g='Geeks', f='For', l='Life')
print("\nPrint String in order of Keywords: ")
print(String1)

Date and time operations


import datetime
x = datetime.datetime.now()
print(x)
import datetime
x = datetime.datetime.now()

print(x.year)
print(x.strftime("%A"))
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)

input output operations


x=input("Enter First number:")
y=input("Enter Second Number:")
i=int(x)
j=int(y)
print("The Sum:", i+j)

x=int(input("Enter Fisrt number:"))


y=int(input("Enter Second Number:"))
print("The Sum:", i+j)
# Python program showing how to
# multiple input using split

# taking two inputs at a time


x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)

# taking three inputs at a time


x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)

# taking two inputs at a time


a, b = input("Enter two values: ").split()
print("First number is {} and second number is {}".format(a, b))
# taking multiple inputs at a time
# and type casting using list() function
x = list(map(int, input("Enter multiple values: ").split()))
print("List of students: ", x)

output formatting

# Python program showing


# use of format() method

# using format() method


print('I love {} for "{}!"'.format('Geeks', 'Geeks'))

# using format() method and referring


# a position of the object
print('{0} and {1}'.format('Geeks', 'Portal'))

print('{1} and {0}'.format('Geeks', 'Portal'))

# the above formatting can also be done by using f-Strings


# Although, this features work only with python 3.6 or above.

print(f"I love {'Geeks'} for \"{'Geeks'}!\"")

# using format() method and referring


# a position of the object
print(f"{'Geeks'} and {'Portal'}")

operators in output formatting


# Python program showing how to use
# string modulo operator(%) to print
# fancier output

# print integer and float value


print("Geeks : %2d, Portal : %5.2f" % (1, 05.333))

# print integer value


print("Total students : %3d, Boys : %2d" % (240, 120))

# print octal value


print("%7.3o" % (25))

# print exponential value


print("%10.3E" % (356.08977))

Arithmatic operators
# Examples of Arithmetic Operator
a=9
b=4
# Addition of numbers
add = a + b

# Subtraction of numbers
sub = a - b

# Multiplication of number
mul = a * b

# Modulo of both number


mod = a % b

# Power
p = a ** b

# print results
print(add)
print(sub)
print(mul)
print(mod)
print(p)

comparison operators

# Examples of Relational Operators


a = 13
b = 33

# a > b is False
print(a > b)

# a < b is True
print(a < b)

# a == b is False
print(a == b)

# a != b is True
print(a != b)

# a >= b is False
print(a >= b)

# a <= b is True
print(a <= b)

logical operators

# Examples of Logical Operator


a = True
b = False
# Print a and b is False
print(a and b)

# Print a or b is True
print(a or b)

# Print not a is False


print(not a)

bitwise operators

# Examples of Bitwise operators


a = 10
b=4

# Print bitwise AND operation


print(a & b)

# Print bitwise OR operation


print(a | b)

# Print bitwise NOT operation


print(~a)

# print bitwise XOR operation


print(a ^ b)

# print bitwise right shift operation


print(a >> 2)

# print bitwise left shift operation


print(a << 2)

assignment operators

# Examples of Assignment Operators


a = 10

# Assign value
b=a
print(b)

# Add and assign value


b += a
print(b)

# Subtract and assign value


b -= a
print(b)

# multiply and assign


b *= a
print(b)

# bitwise lishift operator


b <<= a
print(b)

Result: successfully performed data and data type operations, string operations, date, input and
output, output formatting and operators

13 Write programs using Python language.


13.2 Perform Operations using Data Types and Operators
13.2.3 Determine the sequence of execution based on operator precedence.

Aim: to Determine the sequence of execution based on operator precedence


Tools/Equipments/Instruments: A working PC ,Python 3.11 application

PROCEDURE

operator precedence
# Examples of Operator Precedence

# Precedence of '+' & '*'


expr = 10 + 20 * 30
print(expr)

# Precedence of 'or' & 'and'


name = "Alex"
age = 0

if name == "Alex" or name == "John" and age >= 2:


print("Hello! Welcome.")
else:
print("Good Bye!!")

operator associativity
# Examples of Operator Associativity

# Left-right associativity
# 100 / 10 * 10 is calculated as
# (100 / 10) * 10 and not
# as 100 / (10 * 10)
print(100 / 10 * 10)

# Left-right associativity
# 5 - 2 + 3 is calculated as
# (5 - 2) + 3 and not
# as 5 - (2 + 3)
print(5 - 2 + 3)
# left-right associativity
print(5 - (2 + 3))

# right-left associativity
# 2 ** 3 ** 2 is calculated as
# 2 ** (3 ** 2) and not
# as (2 ** 3) ** 2
print(2 ** 3 ** 2)

Result: Determined the sequence of execution based on operator precedence.

13 Write programs using Python language.


13.3 Control Flow with Decisions and Loops
13.3.1 Construct and analyze code segments that use branching statements.
Aim: to Construct and analyze code segments that use branching statements
Tools/Equipments/Instruments: A working PC ,Python 3.11 application

PROCEDURE

if statement
# python program to illustrate If statement

i = 10

if (i > 15):
print("10 is less than 15")
print("I am Not in if")

if else

# python program to illustrate If else statement


#!/usr/bin/python

i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")

whether palindrome
# Program to check if a string is palindrome or not

my_str = 'aIbohPhoBiA'

# make it suitable for caseless comparison


my_str = my_str.casefold()

# reverse the string


rev_str = reversed(my_str)

# check if the string is equal to its reverse


if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

nested if
# python program to illustrate nested If statement
#!/usr/bin/python
i = 10
if (i == 10):

# First if statement
if (i < 15):
print("i is smaller than 15")

# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
if else if else
# Python program to illustrate if-elif-else ladder
#!/usr/bin/python

i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")

largest of three numbers

# Python program to find the largest number among the three input numbers

# change the values of num1, num2 and num3


# for a different result
num1 = 10
num2 = 14
num3 = 12

# uncomment following lines to take three numbers from user


#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number is", largest)

Result: successfully Construct and analyzed code segments that use branching statements.

13 Write programs using Python language.


13.3 Control Flow with Decisions and Loops
13.3.2 Construct and analyze code segments that perform iteration.
Aim: to Construct and analyze code segments that perform iteration
Tools/Equipments/Instruments: A working PC ,Python 3.11 application

PROCEDURE

sum of n numbers

# Python code to calculate sum of integer list


# Using for loop
# Declare list of numbers
numlist = [2,4,2,5,7,9,23,4,5]
# Calculate sum of list
numsum=0
for i in numlist:
numsum+=i
print('Sum of List: ',numsum)

Factorial of a Number using Loop


# Python program to find the factorial of a number provided by the user.

# change the value for a different result


num = 7

# To take input from the user


#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

Using a flag variable


# Program to check if a number is prime or not

num = 29

# To take input from the user


#num = int(input("Enter a number: "))

# define a flag variable


flag = False

if num == 1:
print(num, "is not a prime number")
elif num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break

# check if flag is True


if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")

Using a for...else statement


num = 407

# To take input from the user


#num = int(input("Enter a number: "))

if num == 1:
print(num, "is not a prime number")
elif num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")

# if input number is less than


# or equal to 1, it is not prime
else:
print(num,"is not a prime number")

# program to add natural numbers


print("Enter the Value of n: ")
n = int(input())

sum = 0
i=1
while i<=n:
sum = sum+i
i = i+1

print("\nSum =", sum)

# Sum of natural numbers up to num

num = 16

if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)

# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

#While loop with else

counter = 0

while counter < 3:


print('Inside loop')
counter = counter + 1
else:
print('Inside else')

#nested loop pattern


i=1
While(i=6)

for j in range(i+1):
print(j+1, end=" ")
print("\n")
i=i+1

#break statement in python


str = "python"
for i in str:
if i == 'o':
break ;
print(i);
print(“The end”);

#continue statement in python


str = "python"
for i in str:
if i == 'o':
break ;
print(i);
print(“The end”);

Result: successfully Construct and analyzed code segments that perform iteration.

13 Write programs using Python language.


13.4 Document and Structure Code
13.4.1 Document code segments using comments and documentation strings.
Aim: to Document code segments using comments and documentation strings
Tools/Equipments/Instruments: A working PC ,Python 3.11 application

PROCEDURE

#pass statement in python


x=int(input("Enter any number: "))
if x ==0:
pass
else:
print("non zero value is accepted")

# Single line comment used

# Program to print "Hello World"


print("Hello World")

# multi line comment used

"I am a single-line comment"

'''
I am a
multi-line comment!
'''

print("Hello World")
#docstring
def square(n):
'''Takes in a number n, returns the square of n'''
return n**2

print(square.__doc__)
# Multi-line Docstrings

def my_function(arg1):
"""
Summary line.

Extended description of function.

Parameters:
arg1 (int): Description of arg1

Returns:
int: Description of return value

"""

return arg1

print(my_function.__doc__)

#Docstrings for Python Functions

def add_binary(a, b):


'''
Returns the sum of two decimal numbers in binary digits.
Parameters:
a (int): A decimal integer
b (int): Another decimal integer

Returns:
binary_sum (str): Binary string of the sum of a and b
'''
binary_sum = bin(a+b)[2:]
return binary_sum

print(add_binary.__doc__)

#Docstrings for Python class


class Person:
"""
A class to represent a person.

...

Attributes
----------
name : str
first name of the person
surname : str
family name of the person
age : int
age of the person

Methods
-------
info(additional=""):
Prints the person's name and age.
"""

def __init__(self, name, surname, age):


"""
Constructs all the necessary attributes for the person object.

Parameters
----------
name : str
first name of the person
surname : str
family name of the person
age : int
age of the person
"""

self.name = name
self.surname = surname
self.age = age

def info(self, additional=""):


"""
Prints the person's name and age.

If the argument 'additional' is passed, then it is appended after the main info.

Parameters
----------
additional : str, optional
More info to be displayed (default is None)

Returns
-------
None
"""

print(f'My name is {self.name} {self.surname}. I am {self.age} years old.' + additional)

Result: successfully Documented code segments using comments and documentation strings
13 Write programs using Python language.
13.4 Document and Structure Code
13.4.2 Construct and analyze code segments that include List comprehensions,Construct and
analyze code segments that include tuple

Aim: to Construct and analyze code segments that include List comprehensions,Construct and
analyze code segments that include tuple

Tools/Equipments/Instruments: A working PC ,Python 3.11 application

PROCEDURE

# Python program to print even Numbers in a List


# using list comprehension
even_nos =[ n for n in range(1,11) if n% 2 == 0]
print(even_nos)

# using list comprehension square


square=[ x*x for x in range(1,11)]
print(square)

# Python program to print even Numbers in a List return


l1=[[n for n in range(10) if n %2==0] for n1 in range(3)]
print (l1)

# List Comprehension with two ‘for’ clause:


a1=['red','green','blue']

b1=[0,1,2]

a2=[(a,b) for a in a1 for b in b1]


print (a2)

#Example tuple comprehension Python


tuple1 = (1, 6, 5, 9, 9, 1, 25, 76)
tuple2 = tuple((i for i in tuple1 if i % 5 == 0))
print(tuple2)

#How to find even numbers using set Comprehension:


s1={n for n in range(1,11) if n%2==0}
print (s1)

#How to find the square of numbers using Set Comprehension.


s1={n*n for n in range(1,11)}

#Sets are unordered.


print (s1)

Result: successfully Construct and analyzed code segments that include List
comprehensions,Construct and analyze code segments that include tuple

13 Write programs using Python language.


13.4 Document and Structure Code
13.4.3 Construct and analyze code segments that include Dictionary comprehensions.

Aim: to Construct and analyze code segments that include List comprehensions,Construct and
analyze code segments that include tuple

Tools/Equipments/Instruments: A working PC ,Python 3.11 application

PROCEDURE

#How to find the square of numbers using Dictionary Comprehension.


d1={n:n*n for n in range(1,11)}
print (d1)

#How to iterate through two sets using dictionary comprehension:


d1={'color','shape','fruit'}
d2={'red','circle','apple'}
d3={k:v for (k,v) in zip(d1,d2)}
print (d3)

Result: successfully Construct and analyzed code segments that include Dictionary
comprehensions

13 Write programs using Python language.


13.5 Perform Operations Using Modules and Tools
13.5.1 Perform basic operations using built-in modules.

Aim: to Perform basic operations using built-in modules


Tools/Equipments/Instruments: A working PC ,Python 3.11 application

PROCEDURE

# Fibonacci numbers module

def fib(n): # write Fibonacci series up to n


a, b = 0, 1
while b < n:
print(b, end =" ")
a, b = b, a+b
print()

def fib2(n): # return Fibonacci series up to n


result=[]
a, b = 0, 1
while b < n:
result.append(a)
a, b = b, a+b

return result
Save as fibo.py
import fibo
fibo.fib(5)

Result: to Perform basic operations using built-in modules

13 Write programs using Python language.


13.5 Perform Operations Using Modules and Tools
13.5.2 Solve complex computing problems by using built-in modules.

Aim: to Solve complex computing problems by using built-in modules.

Tools/Equipments/Instruments: A working PC ,Python 3.11 application

PROCEDURE

#Write a Python program to generate a random color hex, a random alphabetical string, random
value between two integers (inclusive) and a random multiple of 7 between 0 and 70.

import random
import string
print("Generate a random color hex:")
print("#{:06x}".format(random.randint(0, 0xFFFFFF)))
print("\nGenerate a random alphabetical string:")
max_length = 255
s = ""
for i in range(random.randint(1, max_length)):
s += random.choice(string.ascii_letters)
print(s)
print("Generate a random value between two integers, inclusive:")
print(random.randint(0, 10))
print(random.randint(-7, 7))
print(random.randint(1, 1))
print("Generate a random multiple of 7 between 0 and 70:")
print(random.randint(0, 10) * 7)

#Python Program to find the area of a triangle given all three sides

import math
a=int(input("Enter first side: "))
b=int(input("Enter second side: "))
c=int(input("Enter third side: "))
s=(a+b+c)/2
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
print("Area of the triangle is: ",round(area,2))

# Write a program to find roots of a quadratic equation in Python

a = float(input("Insert coefficient a: "))


b = float(input("Insert coefficient b: "))
c = float(input("Insert coefficient c: "))

if a == 0:
print("Invalid")
return -1

d=b*b-4*a*c
sqrt_val = math.sqrt(abs(d))

if d > 0:
print("Roots are real and different ")
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif d == 0:
print("Roots are real and same")
print(-b / (2*a))
else: # d<0
print("Roots are complex")
print(- b / (2*a), " + i", sqrt_val)
print(- b / (2*a), " - i", sqrt_val)

#Circle of Squares using Python

from turtle import *

# loop for number of squares


for i in range(60):

# loop for drawing each square


for j in range(4):

# drawing each side of


# square of length 100
fd(100)

# turning 90 degrees
# to the right
rt(90)

# turning 6 degrees for


# the next square
rt(6)

#Write a Python program to generate a random integer between 0 and 6 - excluding 6, random
integer between 5 and 10 - excluding 10, random integer between 0 and 10, with a step of 3 and
random date between two dates.
import random
import datetime
print("Generate a random integer between 0 and 6:")
print(random.randrange(5))
print("Generate random integer between 5 and 10, excluding 10:")
print(random.randrange(start=5, stop=10))
print("Generate random integer between 0 and 10, with a step of 3:")
print(random.randrange(start=0, stop=10, step=3))
print("\nRandom date between two dates:")
start_dt = datetime.date(2019, 2, 1)
end_dt = datetime.date(2019, 3, 1)
time_between_dates = end_dt - start_dt
days_between_dates = time_between_dates.days
random_number_of_days = random.randrange(days_between_dates)
random_date = start_dt + datetime.timedelta(days=random_number_of_days)
print(random_date)

Result: Successfully Solved complex computing problems by using built-in modules.

You might also like