def main(): x = math.sqrt(9) # Uses import math x1 = sqrt(16) # Usses from math import sqrt x2 = squareroot(64) # Uses from math import sqrt as squareroot print(x, x1, x2)
# According to "The Coder’s Apprentice" by Peter Spronck # It is possible to rename a function that you import from a module, using the #keyword as. This is helpful if using several modules that contain functions with #similar names. #I have included it to make my code easier to read for a beginner. from math import sqrt as squareroot # ask the user to input a floating-point number - that is a number with decimal #As all data stored from the input command is stored as a string variable #Use the conversion process known as TypeCasting #float() type casting will return the value between the parentheses as a floating-point number #even though it was not input as one. i = float( input( "Hello. Please input a positive whole number float i.e., a number with a decimal point. " )) print("Thanks. ") #x=(squareroot( i )) #print ("The square root of", i, "is approx. {:.2f}." .format (x)) #All the code can fit in one line like this print("The square root of", i, "is approximately {:.1f}.".format(squareroot(i))) #In order to show an approximation of the result with just one number to the right #of the decimal point use .format () command #this format was indicated in the example provided in problem set documentation #Use of .format method adapted from examples in Chapter 5 Simple Functions #"The Coder’s Apprentice" by Peter Spronck
def main(): print(math.sqrt(9)) # uses import math print(sqrt(16)) # uses from math import sqrt print(squareroot(25)) # uses from math import sqrt as squareroot print(m.sqrt(36)) # uses import math as m
a=int(input("ENTER THE NUMBER:")) # VALUE ERROR , if other data types is given as input print("number"+a) #TYPE ERROR print(b) #NAME ERROR print(a/0) #ZERO DIVISION ERROR if(a>0) #SYNTAX ERROR print(a) b=[a,23,4] print(b[0]) #INDEX ERROR print(squareroot(a)) #IMPORT ERROR ################# DESIGN A SIMPLE CALCULATOR WITH TRY AND EXCEPT ######################### print("CALCULATOR \n 1.addition \n 2.subtraction \n 3.multiplication \n 4.division") x=int(input("ENTER YOUR CHOICE OF OPERATION :")) a=int(input("ENTER THE FIRST VALUE :")) b=int(input("ENTER THE SECOND VALUE :")) if(x==1): try: c=a+b print("ADDITION OF TWO VALUES :",c) except: print("NOTHING WENT WRONG") else: print("addition is successfull")
def main(): print(math.sqrt(9)) # Uses import math print(sqrt(25)) # Uses from math import sqrt print(squareroot(25)) # Uses from math import sqrt as squareroot
# from module_name import var from math import pi print (pi) from math import pi,sqrt # to import all the objects from the module using * from math import * # not a best practise. # using alias name or assigning a different variable name - using as from math import sqrt as squareroot print(squareroot(9)) # sample import math as m print (m.sqrt(25)) # print (math.sqrt(25)) # error occurs in this case ########################## IMPORTANT - TYPES OF MODULES ################# # 1. USER DEVELOPED # 2. INSTALLED FROM EXTERNAL SOURCE # 3. PRE-INSTALLED WITH PYTHON # # last #3 is called standard library, example: random, math, os, string, multiprocessing # ,sys, subprocess, email, json, doctest, unittest, pdb, argparse and sys ######################################################################
from math import sqrt as squareroot i = 143 isFound = False while not isFound: i += 1 h = i * (2 * i - 1) if (1 + squareroot(1 + 24 * h)) % 6 == 0: isFound = True print h
import math print(math.sqrt(4)) from math import sqrt print(sqrt(4)) from math import sqrt as squareroot print(squareroot(4)) from math import exp, log print("The value of e is approximately", exp(1)) e_sqr = exp(2) print("e squared is", e_sqr) print("which means that log(", e_sqr, ") is", log(e_sqr))
def ShowReadability(): text.insert(END, "If this doesn't work, check NLTK is installed. If NLTK is installed, use nltk.download() to get cmudict and punkt sentence tokenizer. See Help for details \n\n\n") import nltk pattern = r'''(?x)([A-Z]\.)+|\w+([-']\w+)*|\$?\d+(\.\d+)?%?|\.\.\.|[][.,;"'?():-_']''' data = resultsbox.get(1.0,END) rawtext=nltk.regexp_tokenize(data, pattern) prepcolloc = (w.lower() for w in rawtext) text.delete(1.0, END) #sentences sentcountshort = 0 sent_tokenizer=nltk.data.load('tokenizers/punkt/english.pickle') sents = sent_tokenizer.tokenize(data) for sent in sents: if len(sent) < 2: sentcountshort = sentcountshort+1 numsents = len(sents) - sentcountshort numwords = len(p.split(data))-1 sentcountshort = 0 text.insert(END, "\nIgnoring one word sentences (like numbering), there are ") text.insert(END, numsents) text.insert(END, " sentences with an average of ") averagewordspersentence = numwords/numsents text.insert(END, averagewordspersentence) text.insert(END, " words per sentence.\n\n") #set up syllable dictionary from math import sqrt as squareroot from nltk.corpus import cmudict syllables = dict() numeral = re.compile(r'\d') for (word, phonemes) in cmudict.entries(): word = word.lower() count = len([x for x in list(''.join(phonemes)) if x >= '0' and x <= '9']) if syllables.has_key(word): count = min(count, syllables[word]) syllables[word] = count #count syllables numsyllables=0 wordsnotincmu=dict() for word in prepcolloc: if word in syllables: numsyllables = numsyllables + syllables[word] else: wordsnotincmu[word] = 1 #count three syllable words threesyllcount=0 for word in prepcolloc: if word in syllables and syllables[word] > 2: threesyllcount = threesyllcount + syllables[word] #calculate number of letters and numbers letnumcount=0 for word in rawtext: if word.isalpha(): letnumcount=letnumcount + len(word) #adapted from Java at http://www.editcentral.com/gwt1/EditCentral.html #Flesch Flesch = 206.835 - (1.015 * numwords) / numsents - (84.6 * numsyllables) / numwords Flesch = "%.1f" % Flesch #Automated readability index ARI = (4.71 * letnumcount) / numwords + (0.5 * numwords) / numsents -21.43; ARI = "%.1f" % ARI #Flesch-Kincaid grade level FK = (0.39 * numwords) / numsents + (11.8 * numsyllables) / numwords - 15.59; FK = "%.1f" % FK #Coleman-Liau index CL = (5.89 * letnumcount) / numwords - (30.0 * numsents) / numwords - 15.8; CL = "%.1f" % CL #gunning fog GunningFog = 0.4 * ( numwords / numsents + (100.0 * threesyllcount) / numwords ); GunningFog = "%.1f" %GunningFog #SMOG smog = squareroot( threesyllcount * 30.0 / numsents ) + 3.0; smog = "%.1f" % smog text.insert(END, "Flesch: ") text.insert(END, Flesch) text.insert(END, "\n") text.insert(END, "Automated readability index: ") text.insert(END, ARI) text.insert(END, "\n") text.insert(END, "Flesch-Kincaid grade level: ") text.insert(END, FK) text.insert(END, "\n") text.insert(END, "Coleman-Liau index: ") text.insert(END, CL) text.insert(END, "\n") text.insert(END, "Gunning fog index: ") text.insert(END, GunningFog) text.insert(END, "\n") text.insert(END, "Smog: ") text.insert(END, smog) text.insert(END, "\n\n") text.insert(END, "Following words not included in analysis - syllable count is missing from the cmudict database:\n\n") for k,y in sorted(wordsnotincmu.items()): text.insert(END, k)
Modules are pieces of code that other people have written to fulfill common tasks, such as generating random numbers, performing mathematical operations, etc. Modules are basically libraries and to use, you just import them. For example: import random :return: """ print(ayuda.__doc__) print("Printint random numbers from 0 to 10") for i in range(5): value = random.randint(0, 11) print(value) print("The square root of PI is: " + str(squareroot(pi))) def pascLine(depth): if depth <= 1: return [1] elif depth > 1: line = [1] prevLine = pascLine(depth - 1) for i in range(len(prevLine) - 1): line.append(prevLine[i] + prevLine[i + 1]) line.append(1) return line else: print("Input needs to be an integer") return "Input needs to be an integer"
def main(): print(math.sqrt(9)) # Uses import math print(sqrt(9)) # Uses from math import sqrt print(squareroot(9)) # Uses from math import sqrt as squareroot print(mathematics.sqrt(9)) # Uses import math as mathematics print(pi, pow(10, 2)) # Uses from math import pi, pow
from math import squareroot c = 300 000 000 # m/s v = 100 000 000 # m/s m = 0,14 # kg gamma = 1/squareroot(1-(v^2/c^2)) p = m*v*gamma print p
#Basic Python Varibales & Operators from math import sqrt as squareroot from numpy import multiply as mult print(5 + 2, ' Float div : ', 7 / 3, ' Round off quotient ', 7 // 3) wordarray = ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 't', 'e', 's', 't'] word = 'this is test' print('slice : --> ' + word[:4], ' give start -->', word[2:], 'Start end -->', word[2:5], 'Last 4 -> ', word[-4:]) print(' length : ', len(word)) print(wordarray[:5]) print(squareroot(5)) print(mult(2, 3)) print('---- Fibinacci ----') #print fibonacci limit = 10 start = 1 start, b = 0, 1 while start < limit: print(start) start, b = b, start + b