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

Com Prog

The document discusses the key elements of computer programming languages including their alphabets, lexicons, syntax, and semantics. It explains how programs are executed through compilation or interpretation and outlines some advantages and disadvantages of each approach. Python is introduced as an interpreted, object-oriented programming language created by Guido van Rossum.

Uploaded by

Renz Abrigo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Com Prog

The document discusses the key elements of computer programming languages including their alphabets, lexicons, syntax, and semantics. It explains how programs are executed through compilation or interpretation and outlines some advantages and disadvantages of each approach. Python is introduced as an interpreted, object-oriented programming language created by Guido van Rossum.

Uploaded by

Renz Abrigo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Program- makes a computer usable 2.

Lexis: (aka a dictionary) a set of words the


- Without a program, a computer, even the language offers its users (e.g., the word
most powerful one, is nothing more than an "computer" comes from the English
object. Similarly, without a player, a piano is language dictionary, while "cmoptrue"
nothing more than a wooden box. doesn't; the word "chat" is present both in
Computers- are able to perform very complex English and French dictionaries, but their
tasks, but this ability is not innate. meanings are different)
- A computer's nature is quite different. 3. Syntax: a set of rules (formal or informal,
- It can execute only extremely simple written or felt intuitively) used to determine if
operations. For example, a computer cannot a certain string of words forms a valid
understand the value of a complicated sentence (e.g., "I am a python" is a
mathematical function by itself, although this syntactically correct phrase, while "I a
isn't beyond the realms of possibility in the python am" isn't)
near future. 4. Semantics: a set of rules determining if a
- Contemporary computers can only evaluate certain phrase makes sense (e.g., "I ate a
the results of very fundamental operations, doughnut" makes sense, but "A doughnut
like adding or dividing, but they can do it ate me" doesn't)
very fast, and can repeat these actions
virtually any number of times. - The IL is, in fact, the alphabet of a
machine language. This is the simplest
it is necessary to instruct the computer to: and most primary set of symbols we can
1. accept a number representing the distance; use to give commands to a computer. It's
2. accept a number representing the travel the computer's mother tongue.
time; - A program written in a high-level
3. divide the former value by the latter and programming language is called a source
store the result in the memory; code (in contrast to the machine code
4. display the result (representing the average executed by computers). Similarly, the file
speed) in a readable format. containing the source code is called the
source file.
Language- a means (and a tool) for expressing and
recording thoughts. Computer programming is the act of composing the
- Another language you use each day is your selected programming language's elements in the
mother tongue, which you use to manifest order that will cause the desired effect. The effect
your will and to ponder reality. Computers could be different in every specific case - it's up to
have their own language, too, called the programmer's imagination, knowledge and
machine language, which is very experience.
rudimentary.
Instruction List- A complete set of known Of course, such a composition has to be correct in
commands sometimes abbreviated to IL. many senses:
- Different types of computers may vary
depending on the size of their ILs, and the alphabetically - a program needs to be written in a
instructions could be completely different in recognizable script, such as Roman, Cyrillic, etc.
different models. lexically - each programming language has its
dictionary and you need to master it; thankfully, it's
Note: machine languages are developed by much simpler and smaller than the dictionary of any
humans. natural language;
Moreover, they are still evolving, and new words syntactically - each language has its rules and they
are created every day as old words disappear. must be obeyed;
These languages are called natural languages. semantically - the program has to make sense.
There are two different ways of transforming a
We can say that each language (machine or program from a high-level programming language
natural, it doesn't matter) consists of the following into machine language:
elements:
1. Alphabet: a set of symbols used to build COMPILATION - the source program is translated
words of a certain language (e.g., the Latin once (however, this act must be repeated each time
alphabet for English, the Cyrillic alphabet for you modify the source code) by getting a file (e.g.,
Russian, Kanji for Japanese, and so on) an .exe file if the code is intended to be run under
MS Windows) containing the machine code; now
you can distribute the file worldwide; the program - don't expect that interpretation will ramp
that performs this translation is called a compiler or your code to high speed - your code will
translator; share the computer's power with the
interpreter, so it can't be really fast;
INTERPRETATION - you (or any user of the code) - both you and the end user have to have the
can translate the source program each time it has interpreter to run your code.
to be run; the program performing this kind of
transformation is called an interpreter, as it Python is an interpreted language. This means that
interprets the code every time it is intended to be it inherits all the described advantages and
executed; it also means that you cannot just disadvantages. Of course, it adds some of its
distribute the source code as-is, because the unique features to both sets.
end-user also needs the interpreter to execute it. - If you want to program in Python, you'll
need the Python interpreter. You won't be
What does an interpreter do? able to run your code without it. Fortunately,
Computer file- a computer program is actually a Python is free. This is one of its most
piece of text, so the source code is usually placed important advantages.
in text files - Due to historical reasons, languages
- it has to be pure text designed to be utilized in the interpretation
1. The interpreter reads the source code in a manner are often called scripting
way that is common in Western culture: languages, while the source programs
from top to bottom and from left to right. encoded using them are called scripts.
There are some exceptions - they'll be Python- is a widely-used, interpreted,
covered later in the course. object-oriented, and high-level programming
2. If the interpreter finds an error, it finishes its language with dynamic
work immediately. The only result in this semantics, used for general-purpose
case is an error message. programming.
- the name of the Python programming
COMPILATION language comes from an old BBC television
Advantages comedy sketch series called Monty Python's
- the execution of the translated code is Flying Circus.
usually faster; Monty Python- considered one of the two
- only the user has to have the compiler - the fundamental nutrients to a programmer (the other
end-user may use the code without it; being pizza)
- the translated code is stored using machine - Python's creator named the language in
language - as it is very hard to understand honor of the TV show.
it, your own inventions and programming
tricks are likely to remain your secret. There are not many languages whose authors are
Disadvantages known by name. Python was created by Guido van
- the compilation itself may be a very Rossum, born in 1956 in Haarlem, the
time-consuming process - you may not be Netherlands. Of course, Guido van Rossum did
able to run your code immediately after any not develop and evolve all the Python components
amendment; himself.
- you have to have as many compilers as In 1999, Guido van Rossum defined his goals for
hardware platforms you want your code to Python:
be run on. - an easy and intuitive language just as
powerful as those of the major competitors;
INTERPRETATION - open source, so anyone can contribute to its
Advantages development;
- you can run the code as soon as you - code that is as understandable as plain
complete it - there are no additional phases English;
of translation; - suitable for everyday tasks, allowing for
- the code is stored using programming short development times.
language, not the machine one - this means
that it can be run on computers using Python isn't a young language anymore. It is
different machine languages; you don't mature and trustworthy. It's not a one-hit wonder.
compile your code separately for each It's a bright star in the programming firmament, and
different architecture. time spent learning Python is a very good
Disadvantages investment.
What makes Python special? They rather fix any freshly discovered bugs
1. it's easy to learn and security holes. Python 2's development
2. it's easy to teach path has reached a dead end already, but
3. it's easy to use for writing new software Python 2 itself is still very much alive.
4. it's easy to understand 2. Python 3 is the newer (to be precise, the
5. it's easy to obtain, install and deploy current) version of the language. It's going
through its own evolution path, creating its
Drawbacks of Python: own standards and habits.
1. it's not a speed demon - Python does not
deliver exceptional performance; These two versions of Python aren't compatible
2. in some cases it may be resistant to some with each other. Python 2 scripts won't run in a
simpler testing techniques Python 3 environment and vice versa

Python’s two direct competitors Python 3 isn't just a better version of Python 2 - it is
1. Perl - a scripting language originally a completely different language, although it's very
authored by Larry Wall; similar to its predecessor. When you look at them
2. Ruby - a scripting language originally from a distance, they appear to be the same, but
authored by Yukihiro Matsumoto. when you look closely, though, you notice a lot of
differences.
The former is more traditional, more conservative
than Python, and resembles some of the good old Canonical- They are also considered to be
languages derived from the classic C programming reference Pythons, as any other implementation of
language. In contrast, the latter is more innovative the language should follow all standards
and more full of fresh ideas than Python. Python established by the PSF.
itself lies somewhere between these two creations.
Guido van Rossum used the "C" programming
The Internet is full of forums with infinite language to implement the very first version of his
discussions on the superiority of one of these three language and this decision is still in force. All
over the others, should you wish to learn more Pythons coming from the PSF are written in the "C"
about each of them. language. There are many reasons for this
approach and it has many consequences.
Where can we see Python in action?
We see it every day and almost everywhere. It's This is why the PSF implementation is often
used extensively to implement complex Internet referred to as CPython. This is the most influential
services like search engines, cloud storage and Python among all the Pythons in the world.
tools, social media and so on. Whenever you use
any of these services, you are actually very close to Cython- one of a possible number of solutions to
Python, although you wouldn't know it. the most painful of Python's trait - the lack of
efficiency. Large and complex mathematical
niches where Python is absent, or is rarely seen: calculations may be easily coded in Python (much
1. low-level programming (sometimes called easier than in "C" or any other traditional
"close to metal" programming): if you want language), but the resulting code's execution may
to implement an extremely effective driver be extremely time-consuming.
or graphical engine, you wouldn't use - This is what Cython is intended to do - to
Python; automatically translate the Python code
2. applications for mobile devices: although (clean and clear, but not too swift) into "C"
this territory is still waiting to be conquered code (complicated and talkative, but agile).
by Python, it will most likely happen
someday. Another version of Python is called Jython.
"J" is for "Java". Imagine a Python written in Java
Two main kinds of Python, called Python 2 and instead of C. This is useful, for example, if you
Python 3: develop large and complex systems written entirely
1. Python 2- older version of the original in Java and want to add some Python flexibility to
Python. Its development has since been them. The traditional CPython may be difficult to
intentionally stalled, although that doesn't integrate into such an environment, as C and Java
mean that there are no updates to it. On the live in completely different worlds and don't share
contrary, the updates are issued on a many common ideas. Jython can communicate with
regular basis, but they are not intended to existing Java infrastructure more effectively. This is
modify the language in any significant way. why some projects find it usable and needful.
String- delimited with quotes
PyPy - a Python within a Python. In other words, it
represents a Python environment written in print() function
Python-like language named RPython (Restricted What is the effect the print() function causes?
Python). It is actually a subset of Python. The - takes its arguments (it may accept more
source code of PyPy is not run in the interpretation than one argument and may also accept
manner, but is instead translated into the C less than one argument)
programming language and then executed - converts them into human-readable form if
separately. PyPy is rather a tool for people needed (as you may suspect, strings don't
developing Python than for the rest of the users. require this action, as the string is already
PyPy is compatible with the Python 3 language. readable)
- sends the resulting data to the output device
Editor- which will support you in writing the code (it (usually the console); in other words,
should have some special features, not available in anything you put into the print() function will
simple tools); this dedicated editor will give you appear on your screen.
more than the standard OS equipment; What arguments does print() expect?
Console- which you can launch your newly written - Any. We'll show you soon that print() is able
code and stop it forcibly when it gets out of control; to operate with virtually all types of data
Debugger- able to launch your code step by step offered by Python. Strings, numbers,
and allowing you to inspect it at each moment of characters, logical values, objects - any of
execution. these may be successfully passed to print().

IDLE is an acronym: Integrated Development and print()- to produce a new line


Learning Environment. \n- new line character
.py- Python file extension
Editor window- its only purpose is to be a print("My name is", "Python.", end=" ")
workplace in which your source code is treated. print("Monty Python.")
My name is Python. Monty Python.
The message (in red) shows (in the subsequent
lines): print("My", "name", "is", "Monty", "Python.", sep="-")
1. Traceback (which is the path that the code My-name-is-Monty-Python.
traverses through different parts of the
program print("My", "name", "is", sep="_", end="*")
2. Location of the error (the name of the file print("Monty", "Python.", sep="*", end="*\n")
containing the error, line number and My_name_is*Monty*Python.*
module name)
3. Content of the erroneous line; note: IDLE’s print("Programming","Essentials","in", sep="***",
editor window doesn’t show line numbers end="...")
4. Name of the error and a short explanation. print("Python")
Programming***Essentials***in...Python
print(“Hello, World”)
the word print; print ("Lesson 1")
an opening parenthesis; print("Hello World")
a quotation mark;
a line of text: Hello, World!; #displays string
another quotation mark; print ("2")
a closing parenthesis.
#displays an integer
A function (in this context) is a separate part of the print (2)
computer code able to:
cause some effect (e.g., send text to the terminal, #displays octal to decimal value
create a file, draw an image, play a sound, etc.); print (0o123)
this is something completely unheard of in the
world of mathematics; #displays hexa to decimal value
evaluate a value (e.g., the square root of a value or print (0x123)
the length of a given text) and return it as the
function's result; this is what makes Python #displays a float
functions the relatives of mathematical concepts. print(.4)
#displays a scientific notation print("Name:", client_name)
print (3E8) print("Account Balance:", account_balance)

#displays double quotation ver="3.8"


print ("I like \"Monty Python\"") #escape character print("Python Version " + ver)
print ('I like "Monty Python"') #apostrophe
#Sample 1 - Pythagorean Theorem
#displays apostrophe #assigning values to a variable
print ("I'm Monty Python.") #double quotation a=3
print ('I\'m Monty Python.') #backslash b=4
c=(((a**2)+(b**2))**0.5)
#boolean values print("The value of c:", c) #this prints the result c
print (True > False) #True
print (True < False) #False #Sample 2
#assigning values to a variable
#activity #\n for new line john= 3
print("\"I'm\"\n\"\"learning\"\"\n\"\"\"Python\"\"\"") mary= 5
print('"I\'m"\n""learning""\n"""Python"""') adam= 6
print(john,mary,adam) #this prints the number of
apples of john, mary, and adam
total_apples=john+mary+adam #adding the total
print ("Lesson 2 - Arithmetic Operations and number of apples of john, mary , and adam
Hierarchy of Priorities") print("Total number of apples:", total_apples) #this
#Basic Operators (+, -, *, /, %, **, //) prints the total number of apples

print(2+2) #addition #Sample 3


print (-3.0+2.0) #adding float numbers axcel=1
print(5-3) #subtraction laica=2
print(9*3) #multiplication gab=3
janelle=((axcel**2)+(laica**2)+(gab**2)**0.5)
#division print("The value of Janelle:", janelle)
print(18/2)
print(19/2) print("Lesson 3")
#Comments
#integer division or floor division
print(19//2) #This program evaluates hypotenuse c
print(18//2) #where a and b are the length of the legs

#exponentiation #assigning variables


print(2**5) a=3
print(2.5**5) b=4
c=(a**2 + b**2)**0.5 # We use ** instead of square
print("2+2") root
print("2"+"2") print("c =", c)

#Hierarchy of Priorities #Input


#1, ** #reads the user Input
#2, +-, unary print("What is your name?")
#3, +*/ // anything = input()
#4, +-, binary print("Hi,", anything, "!")
print(5*((25%13)+100/(2*13))//2)
print(5*25%13+100/2*13//2) num = float(input("Enter a number: ")) #int() or
float() can be used
#Variables - containers for storing data values result = num ** 2.0
num= 2 print(num, "to the power of 2 is", result)
client_name= "Axcel Landicho"
account_balance= 100000.0 leg_a = float(input("Input first leg length: "))
print(num, client_name, account_balance) leg_b = float(input("Input second leg length: "))
print("Number:", num) hypo = (leg_a**2 + leg_b**2) ** .5
print("Hypotenuse length is", hypo)
end1 = (dura%hour)
#Concatenation end2 = (dura%mins)
#string + string
#combining first and last name print("If an event starts at",hour,":",mins, "and
fnam = input("Enter your first name: ") lasts",dura,"minutes, it will end at",end1,":",end2,".")
lnam = input("Enter your last name: ")
print("\nYour name is " + fnam + " " + lnam + ".")

#Replication
#string * number
#number * string
print("Axcel"*5) print("Lesson 4 - Comparison Conditional
print("+" + 10 * "-" + "+") Statement")
print(("|" + " " * 10 + "|\n") * 5, end="")
print("+" + 10 * "-" + "+") #Comparison Operators
print("This is a ", " rectangle", sep="-") #(==,!=,>,<,>=,<=)
num=5 #Assignment Operator
#Type Conversion print(num == 5) #Equality Operator
leg_a = float(input("Input first leg length: ")) print(num != 5) #Inequality Operator
leg_b = float(input("Input second leg length: ")) print(num > 4) #Greater than Operator
print("Hypotenuse length is " + str((leg_a**2 + print(num < 2) #Less than Operator
leg_b**2) ** .5)) print(num >= 4) #Greater than Equal Operator
print(num <= 7) #Less than Equal Operator
#Lab 1
# input a float value for variable a here #Conditional Statements
# input a float value for variable b here #if...else statement - checks if true or False
vara=float(input("Enter your first number: ")) #Syntax
varb=float(input("Enter your second number: ")) #if(condition):
# codes here - Execute when true
# output the result of addition here #else:
print("\nThe sum of", vara, "and", varb, "is", # codes here - Execute when False
str(vara+varb))
# output the result of subtraction here #if(weather_is_good):
print("\nThe difference of", vara, "and", varb, "is", # go_for_walk()
str(vara-varb)) #else:
# output the result of multiplication here # stay_at_home()
print("\nThe product of", vara, "and", varb, "is",
str(vara*varb)) #this code defines age category
# output the result of division here #age=int(input("Enter your age: ")) #reads user
print("\nThe quotient of", vara, "and", varb, "is", input
str(vara/varb))
#checks the user's age
print("\nThat's all, folks!") #13-19 below... teen
#20-59... adult
#Lab 2 #60-100... senior
x = float(input("Enter value for x: ")) #out of range

a = (x+(1/x)) #if (age >= 13) and (age <= 19): #checks teen
b = (x+(1/a)) category
c = (x+(1/b)) # print("teen...")
y = (1/c) #elif (age >= 20) and (age <= 59): #checks adult
category
print("y =", y) # print("adult...")
#elif (age >= 60) and (age <= 100): #checks senior
#Lab 3 category
hour = int(input("Starting time (hours): ")) # print("senior...")
mins = int(input("Starting time (minutes): ")) #else:
dura = int(input("Event duration (minutes): ")) # print("out of age...")
a = 200 # Store the current largest number here.
b = 33 #largest_number = -999999999
if b > a:
print("b is greater than a") # Input the first value.
elif a == b: #number = int(input("Enter a number or type -1 to
print("a and b are equal") stop: "))
else:
print("a is greater than b") # If the number is not equal to -1, continue.
while number != -1:
#this code defines grade category # Is number larger than largest_number?
grade=float(input("Enter your grade:")) if number > largest_number:
# Yes, update largest_number.
#Grading System largest_number = number
if (grade >= 98) and (grade <= 100): #checks # Input the next number.
Excellent category number = int(input("Enter a number or type -1 to
print("Excellent, grade point is 1.00") stop: "))
elif (grade >= 94) and (grade <= 97): #checks
Superior category # Print the largest number.
print("Superior, grade point is 1.25") #print("The largest number is:", largest_number)
elif (grade >= 90) and (grade <= 93): #checks Very
Good category #for loop
print("Very Good, grade point is 1.50") #browse large collections of data item by item
elif (grade >= 88) and (grade <= 89): #checks Good #syntax
category #for i in range():
print("Good, grade point is 1.75") # do something()
elif (grade >= 85) and (grade <= 87): #checks # pass
Meritorious category
print("Meritorius, grade point is 2.00") #range() function
elif (grade >= 83) and (grade <= 84): #checks Very #pass one, two, three arguments
Satisfactory category
print("Very Satisfactory, grade point is 2.25") #Example 1
elif (grade >= 80) and (grade <= 82): #checks for i in range(10): #i == 0; i+1
Satisfactory category print("The value i is currently,", i)
print("Satisfactory, grade point is 2.50")
elif (grade >= 78) and (grade <= 79): #checks Fairly for q in range(2, 8):
Satisfactory category print("The value of q is currently", q)
print("Fairly Satisfactory, grade point is 2.75")
elif (grade >= 75) and (grade <= 77): #checks for n in range(2, 8, 3):
Passing category #first argument is the initialization
print("Passing, grade point is 3.00") #second argument is the range
elif (grade <= 70): #checks Failure category #third argument is the value of the increment
print("Failure, grade point is 5.00") print("The value of n is currently", n)
else:
print("Incomplete") power = 1
for expo in range(16):
print("Landicho, Axcel M.") print("2 to the power of", expo, "is", power)
power *= 2

print("Lesson 5 - Loops") #Lab3.2.1.6


#while, for import time
for i in range(1,6):
#while loop print(i, "Mississippi")
#while conditional_expression time.sleep(1)
# instruction... print("Ready or not, here I come!")

#infinite loop #Lab3.2.1.9


#while True: while True:
# print("Im stuck inside a loop...") word = input("Guess the secret word to exit: ")
if word.lower() == "chupacabra": #continue -> the next turn is start and the condition
print("You've successfully left the loop.") expression is tested immediately
break
#Break Example
#Lab3.2.1.10 print("The Break instruction:")
user_word = input("Enter a word: ") for i in range (1,6):
user_word = user_word.upper() if i == 3: #when i == 3, it exits the loop
break
for letter in user_word: print("Inside the loop.", i)
if letter in ['A', 'E', 'I', 'O', 'U']: print ("Outside the loop.")
continue
print(letter) #continue example
print("\nThe continue instruction:")
#Lab3.2.1.11 for i in range(1, 6):
user_word = input("Enter a word: ") if i == 3:
user_word = user_word.upper() continue
word_without_vowels = "" print("Inside the loop.", i)
print("Outside the loop.")
for letter in user_word:
if letter in ['A', 'E', 'I', 'O', 'U']: #The largest number (break)
continue largest_number = -99999999
word_without_vowels += letter counter = 0
print(word_without_vowels)
while True:
#Lab3.2.1.3 number = int(input("Enter a number or type -1 to
secret_number = 777 end program: "))
if number == -1:
print( break
""" counter += 1 #counter = counter + 1; counter = 0
+================================+ +1
| Welcome to my game, muggle! | if number > largest_number:
| Enter an integer number | largest_number = number
| and guess what number I've |
| picked for you. | if counter != 0:
| So, what is the secret number? | print("The largest number is", largest_number)
+================================+ else:
""") print("You haven't entered any number.")

number = int(input("Guess the secret number to #The largest number (continue)


exit: ")) largest_number = -99999999
counter = 0
while number != secret_number:
if number != secret_number: number = int(input("Enter a number or type -1 to
print("Ha ha! You're stuck in my loop!") end program: "))
number = int(input("Guess the secret number
to exit: ")) while number != -1:
if number == -1:
print("The secret number,", secret_number, ",is continue
inputted successfully. \nWell done, muggle! You are counter += 1
free now.")
if number > largest_number:
largest_number = number
number = int(input("Enter a number or type -1 to
end program: "))
#These two instructions
#break and continue if counter:
print("The largest number is", largest_number)
#break -> exits the loop immediately, and else:
unconditionally ends the loop operation print("You haven't entered any number.")

You might also like