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

Week 6 First Year

Programming languages allow us to write programs that specify computations for computers to perform. A program breaks tasks into smaller subtasks represented through basic instructions in the programming language. Programs are first written in high-level languages that are then translated into binary for the computer to execute directly. Python is a popular general-purpose programming language used for websites, automation, and data analysis. Programming requires understanding concepts like data types, variables, operators, and program flow and structure.

Uploaded by

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

Week 6 First Year

Programming languages allow us to write programs that specify computations for computers to perform. A program breaks tasks into smaller subtasks represented through basic instructions in the programming language. Programs are first written in high-level languages that are then translated into binary for the computer to execute directly. Python is a popular general-purpose programming language used for websites, automation, and data analysis. Programming requires understanding concepts like data types, variables, operators, and program flow and structure.

Uploaded by

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

Programming

What is a program?
A program is a sequence of instructions that specifies how to perform a computation.
The computation might be something mathematical, such as solving a system of
equations or finding the roots of a polynomial, but it can also be a symbolic computation,
such as searching and replacing text in a document.
Programming languages are formal languages that have been designed to express
computations. The details look different in different languages, but a few basic
instructions appear in just about every language. we can describe programming as the
process of breaking a large, complex task into smaller and smaller subtasks until the
subtasks are simple enough to be performed with basic instructions.
We can choose any language for writing a program according to the need. But a
computer executes programs only after they are represented internally in binary form
(sequences of 1s and 0s). Programs written in any other language must be translated to
the binary representation of the instruction before the computer can execute them.
Programs written for a computer may be in one of the following categories of
languages:
• Machine Language: a sequence of instructions written in the form of binary numbers
consisting of 1s, 0s to which the computer responds directly
• Assembly Language: consists of a set of symbols and letters and requires translation to
machine language
• High-level Language: is a programming language that uses English and mathematical
symbols in its instructions.

Python is a computer programming language often used to build websites, automate


tasks, and conduct data analysis. Python is a general-purpose language, meaning it can
be used to create a variety of different programs and isn’t specialized for any specific
problems.

1 29
Elements of a Programming Language

Learning a programming language requires understanding of concepts such as


representation of different types of data in the computer, various methods of
expressing mathematical and logical relationship among data elements and the
mechanics for controlling the sequence in which operations can be executed for
inputting, processing and outputting of data.

1. Variables and values:

variables are the smallest components of a programming language. we must learn how
to use the internal memory of a computer in writing a program. Computer memory is
divided into several locations. Each location has got its own address.
Python variables do not need explicit declaration to reserve memory space. variable is
created automatically when you assign a value to it. The equal sign (=) is used to assign
values to variables.
The operand to the left of the = operator is the name of the variable and the operand to
the right of the = operator is the value stored in the variable. For example –

It is possible to assign a single value to several variables simultaneously which means


you can create multiple variables at a time. For example –

(The print statement also works with variables)


This produces the following result:

2 30
You can also assign multiple objects to multiple variables. For example –

This produces the following result:

Variable names

Every variable should have a unique name like a, b, c. A variable name can be
meaningful like color, age, name etc. There are certain rules which should be taken
care while naming a Python variable:

• A variable name must start with a letter or the underscore character


• A variable name cannot start with a number or any special character like $, (, *
% etc.
• A variable name can only contain alpha-numeric characters and underscores (A-
z, 0-9, and _ )
• Python variable names are case-sensitive which means Name and NAME are
two different variables in Python.
• Python reserved keywords cannot be used naming the variable.

Keywords define the language’s rules and structure, they cannot be used as variable
names. Python has twenty-nine keywords:

and def exec if not


return
assert del finally import or
try
break elif for in pass
while
class else from is print
yield
continue except global lambda raise

3 31
Example: Following are valid Python variable names:

This will produce the following result

Example: Following are invalid Python variable names:

This will produce the following result:

4 32
2. Data Types:

Data Types are used to define the type of a variable. It defines what type of data
are going to store in a variable. The data stored in memory can be of several types. For
example, a person's age is stored as a numeric value and his or her address is stored as
alphanumeric characters.
2.1 Boolean Data Types
Boolean type is one of built-in data types which represents one of the two values
either True or False. bool() function allows to evaluate the value of any expression and
returns either True or False based on the expression.
Examples: Following is a program which prints the value of boolean variables a and b

This produce the following result

Following is another program which evaluates the expressions and prints the return
values:

5 33
This produce the following result

2.2 Numeric Data Type


Numeric data types store numeric values. Number objects are created when you assign
a value to them. For example:
var1 = 1

var2 = 10

var3 = 10.023

Python supports four different numerical types:


• int (signed integers)
• long (long integers, they can also be represented in octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)
A complex number consists of an ordered pair of real floating-point numbers
denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.
Example: Following is an example to show the usage of Integer, Float and Complex
numbers:
# integer variable.

a=100

print("The type of variable having value", a, " is ", type(a))

# float variable.

b=20.345

print("The type of variable having value", b, " is ", type(b))

# complex variable.

c=10+3j

print("The type of variable having value", c, " is ", type(c))

6 34
2.3 String Data Type
Strings are identified as a contiguous set of characters represented in the quotation
marks. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes
starting at 0 in the beginning of the string and working their way from -1 at the end.
. For example: -
str = 'Hello World!'

print (str) # Prints complete string

print (str[0]) # Prints first character of the string

print (str[2:5]) # Prints characters starting from 3rd to 5th

print (str[2:]) # Prints string starting from 3rd character

print (str * 2) # Prints string two times

print (str + "TEST") # Prints concatenated string


This will produce the following result: -
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

2.4 List Data Type


Lists are the most multipurpose compound data types. A list contains items separated
by commas and enclosed within square brackets ([])..All the items belonging to a list
can be of different data type.
. For example: -
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times

print (list + tinylist) # Prints concatenated lists

7 35
This produce the following result:-
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

3. Operators

Arithmetic operators are used to perform mathematical operations on numerical values.


These operations are Addition, Subtraction, Multiplication, Division, Modulus,
Exponents and Floor Division

Operator Name Example

+ Addition 10 + 20 = 30

- Subtraction 20 – 10 = 10

* Multiplication 10 * 20 = 200

/ Division 20 / 10 = 2

% Modulus 22 % 10 = 2

** Exponent 4**2 = 16

// Floor Division 9//2 = 4

8 36
Example: Following is an example which shows all the above operations:
a = 21
b = 10
# Addition
print ("a + b : ", a + b)
# Subtraction
print ("a - b : ", a - b)
# Multiplication
print ("a * b : ", a * b)
# Division
print ("a / b : ", a / b)
# Modulus
print ("a % b : ", a % b)
# Exponent
print ("a ** b : ", a ** b)
# Floor Division
print ("a // b : ", a // b)

This produce the following result −


a + b : 31
a - b : 11
a * b : 210
a / b : 2.1
a%b: 1
a ** b : 16679880978201
a // b : 2

Comparison operators compare the values on either sides of them and decide the
relation among them Operator Name Example

== Equal 4 == 5 is not true.

!= Not Equal 4 != 5 is true.

> Greater Than 4 > 5 is not true.

< Less Than 4 < 5 is true.

>= Greater than or Equal to 4 >= 5 is not true.

<= Less than or Equal to 4 <= 5 is true.

9 37
4.Input and Output
Developers often have a need to interact with users, either to get data or to provide some
sort of result. Most programs today use a dialog box as a way of asking the user to
provide some type of input.
input ( prompt )
This function first takes the input from the user and converts it into a string. Python
provides a built-in function called input which takes the input from the user.
When the input function is called it stops the program and waits for the user’s input.
When the user presses enter, the program resumes and returns what the user typed.
Example:
# Program to check input
# type in Python
num = input ("Enter number :")
print(num)
name1 = input("Enter name : ")
print(name1)
# Printing type of input value
print ("type of number", type(num))
print ("type of name", type(name1))

Output
In Python, we can simply use the print() function to print output. It allows us to add
specific values:
• object - value(s) to be printed
• sep (optional) - allows us to separate multiple objects inside print().
• end (optional) - allows us to add specific values like new line "\n", tab "\t"
print('Good Morning! \n')
print('It is rainy today')
print('New Year', 2023, 'See you soon!', sep= '. ')

This produce the following result −


Good Morning!
It is rainy today'
New Year. 2023. See you soon!

1041
5. Comments
As programs get bigger and more complicated, they get more difficult to read. Formal
languages are dense, and it is often difficult to look at a piece of code and figure out
what it is doing, or why. For this reason, it is a good idea to add notes to your programs
to explain in natural language what the program is doing. These notes are called
comments, and they are marked with the # symbol:
Example: Following is an example of a single line comment
# This is a single line comment in python
print ("Hello, World!")

This produces the following result:-


Hello, World!
A triple-quoted string is also ignored, and can be used as a multiline comment
Example: Following is the example to show the usage of multi-line comments:
'''
This is a multiline
comment.
'''
print ("Hello, World!")
This produces the following result −
Hello, World!

1142

You might also like