0% found this document useful (0 votes)
55 views19 pages

Lec 1

Computer programming involves writing code using programming languages to solve problems and perform tasks. It involves defining the problem, designing an algorithm to solve it, coding the solution, testing and debugging the code, and maintaining the program. Programming languages provide communication between humans and computers. Common languages include Python, Java, C++, JavaScript, and Ruby. The Python programming language is high-level, object-oriented, and supports multiple paradigms. It has a simple syntax, large standard library, and is used widely for data science, machine learning, web development, and automation. Key concepts in programming include variables to store and manipulate data, data types that determine what type of data a variable can hold, and naming conventions for readable code.
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)
55 views19 pages

Lec 1

Computer programming involves writing code using programming languages to solve problems and perform tasks. It involves defining the problem, designing an algorithm to solve it, coding the solution, testing and debugging the code, and maintaining the program. Programming languages provide communication between humans and computers. Common languages include Python, Java, C++, JavaScript, and Ruby. The Python programming language is high-level, object-oriented, and supports multiple paradigms. It has a simple syntax, large standard library, and is used widely for data science, machine learning, web development, and automation. Key concepts in programming include variables to store and manipulate data, data types that determine what type of data a variable can hold, and naming conventions for readable code.
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
You are on page 1/ 19

Introduction to Programming

Computer Programming
Computer programming, also known as coding, is the process of designing, writing, testing, and
maintaining instructions (code) that a computer can understand and execute. It involves creating
sequences of instructions using programming languages to solve specific problems or perform certain
tasks. These instructions are written in a structured and logical manner to achieve desired outcomes.

Programming languages are used as a means of communication between humans and computers. They
provide a way to express complex algorithms and processes in a way that a computer can interpret and
execute. Some common programming languages include Python, Java, C++, JavaScript, Ruby, and many
others.

The process of computer programming typically involves the following steps:

1. Problem Definition: Clearly defining the problem you want to solve with programming. This step
involves understanding the requirements and constraints of the task.

2. Algorithm Design: Creating a high-level plan or algorithm that outlines the steps required to
solve the problem. This involves breaking down the problem into smaller, manageable tasks.

3. Coding: Writing the actual code using a programming language based on the algorithm you've
designed. This involves using the syntax and rules of the chosen language to create a set of
instructions that the computer can understand.

4. Testing: Running the code and testing it under various conditions to identify and fix errors
(bugs) and ensure that it behaves as expected.

5. Debugging: Identifying and correcting errors in the code that may cause the program to produce
incorrect results or crash.

6. Optimization: Refining and improving the code to make it more efficient, faster, or use fewer
resources.

7. Documentation: Creating documentation to explain how the code works, its purpose, and how
to use it. This is helpful for other programmers who might work on the code in the future or for
yourself if you need to revisit the code later.

8. Maintenance: Over time, programs might need updates, bug fixes, or enhancements.
Maintenance involves making necessary changes to keep the program functioning correctly.
What is Python Programming Language?
 Python is a high-level, object-oriented programming language with built-in data structures and
dynamic semantics. It supports multiple programming paradigms, such as structures, object-
oriented, and functional programming.

 Python supports different modules and packages, which allows program modularity and code
reuse.

 Python was created by Guido van Rossum.

Why learn Python?


1. Career Opportunities and Salary

Python language provides several job opportunities and promises high growth with huge salary
prospects. Some of the big and renowned companies that use Python for their development are

2. Data Science

Python is known for being robust, scalable and provides extensible visualization and graphics
options. Hence it’s widely used in Data Science. Python supports several popular libraries. Some
of them are as follows:

3. Machine Learning

Python is among the programming languages most preferred for Machine Learning because of
its simple syntax and its support of several machine-learning libraries.

4. Web Development

Python provides a vast collection of frameworks that makes it much easier for developers to
develop web applications.
5. Scripting and Automation

Python language can be used for writing scripts and automating workflows without human
intervention. This makes it very convenient

6. Portable and Extensible

A code developed in Python is often compatible with most of non-native platforms. It can be
integrated with Java, .NET components, or C/C++ libraries.

7. Active Community

Python has a massive community that can help you in programming errors or issues with the
software. You can post your queries in community forums, and community members will
address it in real quick time.

8. Easy to Use

Python has a simple syntax and hence is easy to understand and learn. Thus, making it a popular
pick when it comes to programming languages.

Java Python

public class welcome {


public static void main (String args[ ] ) { print ( ‘ Welcome to
System.out.println (“ Welcome to Simplilearn ”) ; } Simplilearn ‘
}
Writing and running their first Python program ("Hello, World!").
Open your chosen text editor or IDE (Thonny) and create a new file with a .py extension. This extension
indicates that the file contains Python code. Type the following line of code to print "Hello, World!" to the
console:

Intelligence snippets

Step 1. Open Thonny


Step 2. Select File menu then click New or simply press Ctrl + N
Step 3. At this moment your Thonny IDE should look like this.

Step 4. Type the following code:


print("My first python program")

Step 5. Save the file and name it as MyFirstProgram. Automatically, Thonny will supply a .py
extension name.

Step 6. Run the program by clicking the Run menu and selecting Run current script or simply
press F5
Step 7. Your shell section should look like this:

What is an IDE?
An integrated development environment (IDE) is a software application that helps programmers develop
software code efficiently. It increases developer productivity by combining capabilities such as software
editing, building, testing, and packaging in an easy-to-use application. Just as writers use text editors and
accountants use spreadsheets, software developers use IDEs to make their job easier.

Basic Syntax

What is Syntax in programming?


Syntax refers to the rules that define the structure of a language. Syntax in computer programming
means the rules that control the structure of the symbols, punctuation, and words of a programming
language. Without syntax, the meaning or semantics of a language is nearly impossible to understand.

If the syntax of a language is not followed, the code will not be understood by a compiler or interpreter.

Why Is Syntax Important in Programming?


Syntax improves code readability. It ensures that the four C’s of coding are maintained:

 Communication

 Code integration
 Consistency

 Clarity

The concept behind conventions is to make the code explain itself. If the code is self-explanatory, the
focus can be on design and program improvements and not on what does this mean?

Using consistent standards means that code is predictable and discoverable when read by other
programmers.

When code does not follow conventions, it becomes disorganized and difficult to read. It becomes what
is known as the spaghetti code.

The term has a negative connotation indicating that the programmer did not have the skills or
experience needed to write readable code.

Variables and Data Types


In programming, a variable is a named storage location that holds a value or data. It's used to store
information that your program can later access, modify, or
manipulate. Think of a variable as a labeled container that holds
different types of data, such as numbers, text, or more complex
structures.

Here are some key points to understand about variables:

1. Declaration: To use a variable, you need to declare it. Declaration involves giving the variable a
name and specifying its data type (in languages that require explicit typing). For example, in
Python, you don't need to explicitly declare the data type; you can directly assign a value to a
variable.

2. Assignment: After declaring a variable, you can assign a value to it. The value could be a
number, text, or any other data type that the variable can hold.

3. Value Storage: The variable holds the value you've assigned to it. This value can be changed or
updated as your program runs.

4. Data Types: Variables have associated data types that determine the type of data they can
store. Common data types include integers, floating-point numbers, strings (text), booleans
(true/false), lists, dictionaries, and more.

5. Memory Location: Behind the scenes, a variable corresponds to a memory location in the
computer's memory. The value is stored in this memory location, allowing your program to
access and modify it.

6. Naming Rules: Variable names have to follow certain rules. They usually start with a letter (or
underscore), followed by letters, digits, or underscores. Variable names are case-sensitive,
meaning myVar and myvar would be considered different variables.
In computer programming, a naming convention is a set of rules for choosing the character
sequence to be used for identifiers that denote variables, types, functions, and other entities in
source code and documentation.

Among the common ones are the following:

 Camel Case: First letter of every word is capitalized with no spaces or symbols between
words. Examples: UserAccount, FedEx, WordPerfect. A variation common in
programming is to start with a lower case: iPad, eBay, fileName,
userAccount. Microsoft uses the term Camel Case to refer strictly to this variation.

 Pascal Case: Popularized by Pascal programming language, this is a subset of Camel Case
where the word starts with uppercase. Thus, UserAccount is in Pascal Case but
not userAccount.

 Snake Case: Words within phrases or compound words are separated with an
underscore. Examples: first_name, error_message, account_balance.

 Kebab Case: Like Snake Case, but using hyphens instead. Examples: first-
name, main-section.

 Screaming Case: This refers to names in


uppercase. Examples: TAXRATE, TAX_RATE.

Example 1-1
# Declaration and assignment
MyAge = 25

# Using the variable


print("I am", age, "years old.")

In this example, the variable MyAge is declared and assigned the value 25. Later, the value of
the age variable is used in the print() statement to display the person's age.

Variables are a fundamental concept in programming, and they allow your programs to work
with and manipulate data dynamically, making your code more flexible and adaptable.

Data Types
Data types are crucial in programming because they define the kind of data a variable can hold and the
operations that can be performed on that data. Properly using data types is essential for writing correct
and efficient code. Here's why data types are important:

1. Memory Allocation: Different data types require varying amounts of memory. Specifying the
correct data type ensures that the appropriate amount of memory is allocated for each variable,
optimizing memory usage.
2. Type Safety: Data types prevent unintended operations or conversions that could lead to errors
or unexpected behavior. For example, trying to add a string to an integer without proper
conversion could result in an error.

3. Operations: Different data types support different operations. For instance, you can perform
mathematical operations on numbers but not on strings. Data types ensure that the right
operations are applied to the right types of data.

4. Code Clarity: Explicitly defining data types in your code makes it more readable and
understandable for both you and other programmers. It provides context and clarity about the
kind of data a variable is expected to hold.

5. Data Integrity: Using appropriate data types helps maintain data integrity by enforcing
constraints on the acceptable values a variable can hold. For instance, if you define a variable as
an integer, it won't accept non-integer values.

6. Function Interactions: When functions are used, data types help ensure that the correct
arguments are passed and that the function operates as expected. This reduces errors and
debugging time.

7. Type Conversion: Data types allow you to convert values from one type to another when needed.
This is important for performing various tasks like input/output formatting and mathematical
operations involving mixed data types.

8. Compatibility: Data types play a significant role in ensuring compatibility when working with
external data sources or APIs (Application Programming Interface). They help with parsing,
serialization, and deserialization of data.

9. Performance: Using appropriate data types can lead to improved performance. For example,
using integers instead of floating-point numbers for integer operations can be more efficient.

Different programming languages have different data types and rules for handling them, so understanding
and using data types effectively is essential for writing correct and efficient code.

Python provides several basic data types to represent different kinds of values. Here are some of the
fundamental data types in Python:

1. Integers (int): Integers represent whole numbers without decimal points. For example -5, 0, 42.

2. Floating-Point Numbers (float): Floating-point numbers represent real numbers with decimal
points. For example 3.14, 0.001, -2.5.

3. Strings (str): Strings represent sequences of characters, typically used to represent text. They
are enclosed in either single or double quotes. For example: 'Hello, World!', "Python is fun".

4. Booleans (bool): Booleans represent either True or False. They are used in logical operations
and conditional statements. For example: True, False.

5. Lists (list): Lists are ordered collections of items, which can be of different data types. Lists are
mutable, meaning you can change their contents after creation. For example: [1, 2, 3], ['apple',
'banana', 'cherry'].
6. Tuples (tuple): Tuples are similar to lists but are immutable, meaning their contents cannot be
changed after creation. They are defined using parentheses. For example: (1, 2, 3), ('red',
'green', 'blue').

7. Dictionaries (dict): Dictionaries store key-value pairs. Keys are unique identifiers for values, and
dictionaries are unordered collections. For example: {'name': 'Alice', 'age': 30}.

8. Sets (set): Sets are unordered collections of unique elements. They are useful for storing distinct
values and performing set operations. For example: {1, 2, 3}, {'apple', 'banana', 'cherry'}.

Example 1-2
x = 10 # x is an integer
y = 3.14 # y is a float
name = "John" # name is a string
is_ready = True # is_ready is a boolean

These basic data types serve as the building blocks for more complex data structures and
operations in Python.

Basic Input and Output function


Input and output (I/O) are fundamental concepts in programming that allow you to interact with the
user and display information. In Python, you can use the input() function to take user input and the
print() function to display output. Here's how to use basic input and output in Python:

Input:

The input() function is used to take input from the user. It reads a line of text entered by the user and
returns it as a string. You can optionally provide a prompt to display to the user.

Example 1-3
name = input("Enter your name: ")
print("Hello, " + name + "! Nice to meet you.")

Output: The print() function is used to display output to the screen. You can pass one or more
arguments separated by commas, and they will be concatenated and displayed.

Example 1-4
print("Hello, World!")
print("The answer is", 7)

You can also format the output using string formatting techniques like f-strings (available in Python 3.6
and later) or the format() method:

Example 1-5
name = "Alice"
age = 30
print(f"{name} is {age} years old.") # Using f-string
print("{} is {} years old.".format(name, age)) # Using format()
method

Output:

Alice is 30 years old.


Alice is 30 years old.

String Formatting with % Operator: This is an older way to format strings and is less recommended for
new code. It uses the % operator:

Example 1-5b
name = "Charlie"
age = 22
formatted_string = "My name is %s and I am %d years old." % (name,
age)
print(formatted_string)

Output:

My name is Charlie and I am 22 years old.

Float Number Formatting: You can control how numbers are formatted when they are printed using
formatting options. For instance, you can use the format() method for strings, or the % operator, to
control the precision of floating-point numbers:

Example 1-5c
pi = 3.14159265
formatted_pi = "{:.2f}".format(pi) # Formats pi to 2 decimal places
print(formatted_pi)

Output:

3.14

Remember that the print() function automatically adds a newline character (\n) at the end of the
output by default. You can change this behavior by modifying the end parameter:

Example 1-6
print("Hello", end=" ")
print("World")

Output:

Hello World
Operator
In computer programming, an operator is a symbol or keyword that represents a specific action to be
performed on one or more operands. Operators are fundamental components of programming
languages and are used to manipulate data and perform calculations. They define the operations that can
be executed on various types of data, such as numbers, strings, and more complex data structures.

Operators can be categorized into several types based on the type of operation they perform:

1. Arithmetic Operators: These operators are used for mathematical calculations. These
operators take numerical values as operands and return a single unique numerical value,
meaning there can only be one correct answer.

The standard arithmetic operators and their symbols are given below.
Symbol Operation Explanation
This operation adds both operands on either side of
+ Addition (a+b)
the + operator.
This operation subtracts the right-hand operand from
- Subtraction (a-b)
the left.
* Multiplication (a*b) This operation multiplies both operands.
This operation divides the left-hand operand by the
/ Division (a/b)
operand on the right.
This operation returns the remainder after dividing the
% Modulus (a%b)
left-hand operand by the right operand.

Example 1-7
a = 7
b = 2

# addition
print ('Sum: ', a + b)

# subtraction
print ('Subtraction: ', a - b)

# multiplication
print ('Multiplication: ', a * b)

# division
print ('Division: ', a / b)

# floor division
print ('Floor Division: ', a // b)

# modulo
print ('Modulo: ', a % b)
# a to the power b
print ('Power: ', a ** b)

Output:

Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49

2. Assignment Operators: Assignment operators are used to assign a value to a variable.

Operator Name Example


= Assignment Operator a=7
+= Addition Assignment a += 1 # a = a + 1
-= Subtraction Assignment a -= 3 # a = a - 3
*= Multiplication Assignment a *= 4 # a = a * 4
/= Division Assignment a /= 3 # a = a / 3
%= Remainder Assignment a %= 10 # a = a % 10
**= Exponent Assignment a **= 10 # a = a ** 10

Example 1-8
# assign 10 to a
a = 10

# assign 5 to b
b = 5

# assign the sum of a and b to a


a += b # a = a + b

print(a)

Output:

15

Here, we have used the += operator to assign the sum of a and b to a. Similarly, we can
use any other assignment operators according to the need.

3. Comparison Operators: Compare two values/variables and return a Boolean result: True or
False. Commonly used in decision-making and loops.
Operator Meaning Example
== Is Equal To 3 == 5 gives us False
!= Not Equal To 3 != 5 gives us True
> Greater Than 3 > 5 gives us False
< Less Than 3 < 5 gives us True
>= Greater Than or Equal To 3 >= 5 give us False
<= Less Than or Equal To 3 <= 5 gives us True

Example 1-9
a = 5
b = 2

# equal to operator
print('a == b =', a == b)

# not equal to operator


print('a != b =', a != b)

# greater than operator


print('a > b =', a > b)

# less than operator


print('a < b =', a < b)

# greater than or equal to operator


print('a >= b =', a >= b)

# less than or equal to operator


print('a <= b =', a <= b)

Output:

a == b = False
a != b = True
a > b = True
a < b = False
a >= b = True
a <= b = False

4. Logical Operators: Logical operators are used to combine or manipulate Boolean values. They
include logical AND , logical OR , and logical NOT . These operators are used to create more
complex conditions and make decisions based on multiple conditions.

Operator Example Meaning


and a and b Logical AND:
True only if both the operands are True
or a or b Logical OR:
True if at least one of the operands is True
not not a Logical NOT:
True if the operand is False and vice-versa.
Example 1-10
a = 5
b = 6

print((a > 2) and (b >= 6)) # True

# logical AND
print(True and True) # True
print(True and False) # False

# logical OR
print(True or False) # True

# logical NOT
print(not True) # False

5. Bitwise Operators: Bitwise operators perform operations at the bit level on integer values.
They include operations like bitwise AND (&), bitwise OR (|), bitwise XOR (^), and more.

6. Unary Operators: Unary operators operate on a single operand. Examples include unary minus
(-x), and unary plus (+x)

Example 1-11
x=56
y=-(x)
print(y+(-2)) #output: -58

7. Identity Operators: A special type of operator in Python. The is and is not are used to check
if two values are located on the same part of the memory. Two variables that are equal do not
imply that they are identical.

Operator Meaning Example


is True if the operands are identical (refer to the x is True
same object)
is not True if the operands are not identical (do not x is not True
refer to the same object)

Example 1-12
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]

print(x1 is not y1) # prints False

print(x2 is y2) # prints True


print(x3 is y3) # prints False

Here, we see that x1 and y1 are integers of the same values, so they are equal as well as
identical. The same is the case with x2 and y2 (strings).

But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates
them separately in memory although they are equal.

These are just a few examples of the many operators available in various programming languages. The
specific operators and their behaviors might vary from one programming language to another, but the
fundamental concepts remain consistent across most languages. Operators allow programmers to
perform a wide range of computations and manipulations on data, forming the building blocks of
expressive and functional code.

Python Comments
 Comments can be used to explain Python code.
 Comments can be used to make the code more readable.
 Comments can be used to prevent execution when testing cod

Example 1-13
print("Hello, World!") #This is a comment

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

Variables
Variables are containers for storing data values.

Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.

Example 1-14
x = 5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type after they
have been set.

Example 1-15
x = 4 # x is of type int
x = "Sally" # x is now of type str
Answer = True
print(x)

Casting
In Python, casting refers to the process of converting a value from one data type to another. Python
provides built-in functions that allow you to perform typecasting. Here are some common types of
typecasting in Python:

 Integer Casting (int()): You can convert a value to an integer using the int() function. This
function can be used to convert floating-point numbers, strings containing valid integers, and
even other data types like Booleans.

Example 1-16
float_num = 3.14
int_num = int(float_num) # Converts float to int, resulting in 3

str_num = "42"
int_from_str = int(str_num) # Converts string to int, resulting
in 42

 Floating-Point Casting (float()): You can convert a value to a floating-point number using the
float() function. This is particularly useful when you want to perform division and obtain a
floating-point result.

Example 1-17
int_num = 10
float_num = float(int_num) # Converts int to float, resulting in
10.0

 String Casting (str()): You can convert a value to a string using the str() function. This is useful
when you want to concatenate a value with other strings or display it as text.

Example 1-18
num = 123
num_str = str(num) #Converts int to string, resulting in "123"
 Boolean Casting (bool()): You can convert a value to a boolean using the bool() function. In
general, empty values (e.g., 0, 0.0, "", None) are considered False, and non-empty values are
considered True.

Example 1-19
num = 0
bool_value = bool(num) # Converts int to boolean, resulting in
False

non_empty_str = "Hello"
bool_str = bool(non_empty_str) # Converts non-empty string to
boolean, resulting in True

 List, Tuple, Set, and Dictionary Casting: You can convert certain iterable types (like tuples, lists,
sets, and dictionaries) to each other using their respective constructor functions. For example,
you can convert a list to a tuple using tuple(), and vice versa.

Example 1-20
my_list = [1, 2, 3]
my_tuple = tuple(my_list) # Converts list to tuple

my_dict = {'a': 1, 'b': 2}


my_set = set(my_dict) # Converts dictionary keys to a set

Remember that not all types of casting are valid or make sense in all situations. Casting between
incompatible types might result in errors or unexpected behavior. Always consider the types of data
you're working with and the intended outcome when performing casting operations.

Import
In Python, the import statement is used to include external modules or libraries in your code. Modules
are Python files containing reusable code, and they can include functions, classes, variables, and more.
The import statement allows you to use the functionalities defined in these modules within your own
code.
Here's how the import statement works:
import module_name

You replace module_name with the name of the module you want to import. After importing a
module, you can access its functions, classes, and other attributes using dot notation, like
module_name.function() or module_name.ClassName.

For example, let's say you have a module named math_operations.py containing some
mathematical functions:

Example 1-21
import math
pie = math.pi
print("The value of pi is : ",pie)

In the above code module, math is imported, and its variables can be accessed by considering it
to be a class and pi as its object.

The value of pi is returned by __import__(). pi as a whole can be imported into our initial
code, rather than importing the whole module.

Example 1-22
from math import pi
# Note that in the above example,
# we used math.pi. Here we have used
# pi directly.
print(pi)

Here, we are importing the complete math module using *

Example 1-23
# Here, we are importing the complete math module using *
from math import *
# Here, we are accessing functions of math module without using
the dot operator
print( "Calculating square root: ", sqrt(25) )
# here, we are getting the sqrt method and finding the square root
of 25
print( "Calculating tangent of an angle: ", tan(pi/6) )
# here pi is also imported from the math module

You might also like