7.6 Introduction to Python
Programming
Python
·
Python
is a high-level, interpreted programming language created by Guido van Rossum
in 1991.
·
It
is known for its simple and readable syntax, making it beginner-friendly and
highly versatile.
·
Python
is widely used in web development, data science and machine learning,
artificial intelligence, data analysis, automation and scripting, game
development, web scraping, cyber security, etc.
·
Python
has a simple to understand coding style, applying indentation instead of braces
to define blocks of code. For example, in a loop or conditional statement,
indentation signifies the scope of the block.
Features of Python
·
Easy
to read and write: Python uses simple and understandable syntax, making it easy
for programmers to write and understand the code.
·
Versatile:
Python can be used for a wide range of tasks like simple automating systems to
complex web development, data analysis, and Artificial Intelligence.
·
Beginner-friendly:
Python uses simple syntax, making it a great choice for those who are new to
programming.
·
Extensive
standard library: Python has an extensive standard library of pre-written code
that offers programmers ready-made solutions, without requiring them to write
code from ground level.
Installation process of Python
Visit the official Python website (
https://www.Python.org/downloads/ )and download the latest version of Python
3.x for Windows. The website will automatically detect your operating system
and offer the appropriate installer for your system (32-bit or 64-bit).
Download and install suitable IDE
for Python. (PyCharm, VS Code, Jupyter Notebook, etc)
7.7 Basic Syntaxes in Python
Python’s syntax is straightforward
and beginner-friendly.
Comments in Python
Comments are brief messages that
programmers write in their code to explain what the code is doing, like leaving
helpful hints for others to understand the program.
Single-line comments start with #,
and multi-line comments are enclosed in triple quotes (''' or
""").
Example:
# This is a single-line comment
"""
This is a
multi-line comment
"""
Keywords
Keywords are reserved words that
have predefined meanings and cannot be used as identifiers (variable names,
function names, etc.).
Example: False, await,
else, import, pass etc.
7.8 I/O statements and string
formatting
Input/Output statements (I/O)
I/O statements help us to interact
with the program. i.e. It allows us to provide our data and instructions to the
program as well as display the output on screen.
Print Statement
The print statement in Python is
used to display information on the screen. We use a ‘print’ statement to
display the output of data that we want to show.
Example: print(“Hello, Python!”)
Input Function
The ‘input’ function allows to
provide input to the program. We can give data to the program as we need.
Example: number = input(“Enter
number: ”)
String Formatting
String formatting in Python helps
to insert values into a string, making it easier to create dynamic and
personalized messages.
Using % Operator (Old Style)
This is the old style of string
formatting, where we use % to insert values into a string.
Example:
name = "Charlie"
age = 22
message = "My name is %s and I
am %d years old." % (name, age)
print(message)
Output
My name is Charlie and I am 22
years old.
Using format( ) Method
The format( ) method allows to
insert values into a string using curly braces {} as placeholders.
Example:
name = "Bob"
age = 30
message = "My name is {} and I
am {} years old.".format(name, age)
print(message)
Output
My name is Bob and I am 30 years old.
We can also use numbered or named
placeholders
Example:
message = "My name is {0} and
I am {1} years old.".format(name, age)
print(message)
Using f-strings (Formatted String
Literals)
f-strings are the most modern and
efficient way to format strings. We can directly embed expressions inside curly
braces {}. It was introduced in Python 3.6.
Example:
name = "Alice"
age = 25
message = f"My name is {name}
and I am {age} years old."
print(message)
Output
My name is Alice and I am 25 years
old.
7.9 Data types and variables
Data type
The classification of data based on
its nature is called data type. It defines the kind of data a variable can
hold.
Python supports several data types:
·
Integer
(int): It is a whole number ranging from negative infinity to positive
infinity.
Examples:
-,...,-3,-2,-1,0,1,2,3,....,
·
Float
(float): It is numbers with decimals.
Examples:
3.14, -0.5, 1.567.
·
String
(str): It consists of alphabets, special characters, alphanumeric values which
are enclosed in double quotes.
Examples:
“hello” , “Python@”, “Mahendranagar1”, “@#@#kathmandu”
·
Boolean
(bool): It only provides True or False values.
Example:
is_student = True, has_mobile=False
Identifier
Identifiers are names given to
program units such as variables, functions, classes, or other entities. They
are not predefined in the programming language but are defined by programmers
themselves.
Rules for identifier
·
An
identifier name must start with a letter or the underscore character.
·
An
identifier name cannot start with a number.
·
An
identifier name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ ).
·
Python
is case sensitive so identifier names are also case-sensitive. (age, Age and
AGE are three different identifiers).
· An identifier name cannot be any of
the Python keywords.
Valid identifiers
A1, B34, First_Name, x_1 etc.
Invalid identifiers
1A, 34BA,198, int, print first-name. def
etc.
Variables in Python
A variable is like a container that
holds a value which stores numbers, text, or other data types. A variable is
created when the value is assigned to it.
Example:
name = "Alice" # String variable
age = 25 # Integer variable
height = 5.5 # Float variable
is_student = True #Boolean variable
7.10 Concept of Type Casting
Type Casting (Type Conversion)
Type casting is the process of
converting one data type into another. For example, if we assign an integer
(int) value to a float variable, the compiler will convert the int value to a
float.
Types of casting
·
Implicit
casting
·
Explicit
casting
Implicit casting
Implicit type casting, also known
as automatic type conversion, occurs when the Python interpreter automatically
converts one data type to another in certain situations.
Examples:
x = 10 # integer
y = 5.5 # float
z = x + y # the integer ‘x’ is cast
to a float for the addition.
print(z)
Explicit casting
In explicit type casting, the user intentionally
converts the data type of a variable to another data type.
·
int():
Converts a value to an integer.
·
float():
Converts a value to a float.
·
str():
Converts a value to a string.
·
bool():
Converts a value to a boolean (True or False).
Example:
int(x): Converts x to an integer.
x = 3.14
y = int(x) # Converts float to int (removes decimal
part)
print(y) # Output: 3
x = 25
y = str(x) # Converts integer to string
print(y) # Output: "25"
7.11 Operators and Expressions:
Arithmetic, Relational, Logical, Assignment
Operators
Operators in Python are symbols
that perform specific operations on variables and values. Python supports
various types of operators, including arithmetic, relational, logical, and
assignment operators.
Arithmetic Operators
Arithmetic operators are used to
perform basic mathematical operations like addition, subtraction,
multiplication, and more.
Example:
Simple program to find the sum of
the two number for the user input
num1 = float(input(“Enter first
number: “))
num2 = float(input(“Enter second
number: “))
sum = num1 + num2
print(“The sum of {0} and {1} is
{2}”.format(num1, num2, sum))
Relational operator
Relational operator is used to
check and compare values. These operators check the relationship between two
things and tell us if they are equal, greater than or less than each other.
Logical operator
Logical operators in Python are
used to combine conditions and make decisions based on different situations.
This operator is like a tool that helps us make decisions based on different
situations. There are 3 main logical operators, ‘and’, ‘or’, and ‘not’.
AND
Both the conditions must be true
for the result to be true in the “and” operator.
Example: x = (5<2) and (5>3)
Result: False
OR
Only one of the conditions needs to
be true for the result to be true in the “or” operator.
Example: (5<2) or (5>3)
Result: True
NOT
The logical operator “not” provides
the opposite result of a given condition.
Example: not(5<2)
Result: True
Assignment operator
Assignment operators are used to
assign values to variables.
Expression
An expression is a combination of values,
variables, operators, and functions that are evaluated to produce a result.
Example:
Maths expression: result = 5 + 3
Text expression: greeting = “Hello”
Combining expression: combined = (5
* 3) + “Python”
Operands
Operands are values or variables
that operators operate on. Operands refer to the values or entities that are
operated upon by an operator.
Example: add = 5 + 3
Here, ‘5’ and ‘3’ are operands and
‘+’ is an operator, and it is performing an ‘addition’ operation.
No comments:
Post a Comment