Unit 1: Python Programming Fundamentals [8]
1.1 Python Introduction
1.2 Data Types and Type Conversion
1.3 Comments
1.4
Variables, Constants,
Operators and Performing Calculations
1.5 Reading Input from Keyboard
1.6
Print function, Displaying Formatted Output with F- strings
Practical
Works
·
Write program to illustrate variables, constants, data types
and type conversion.
·
Write program to demonstrate different types of operators
available in python and perform
calculations.
Write program to make use of I/O functions.
1.1
Python Introduction
Python is a
general-purpose, dynamically typed, high-level, compiled and interpreted,
garbage-collected, and purely object-oriented programming language that
supports procedural, object-oriented, and functional programming.
Features of
Python:
·
Easy to use and Read - Python's syntax is clear
and easy to read, making it an ideal language for both beginners and
experienced programmers. This simplicity can lead to faster development and
reduce the chances of errors.
·
Dynamically Typed - The data types of
variables are determined during run-time. We do not need to specify the data
type of a variable during writing codes.
·
High-level - High-level language means
human readable code.
·
Compiled and Interpreted - Python code first gets
compiled into bytecode, and then interpreted line by line. When we download the
Python in our system form org we download the default
implement of Python known as CPython. CPython is considered to be Complied and
Interpreted both.
·
Garbage Collected - Memory allocation and
de-allocation are automatically managed. Programmers do not specifically need
to manage the memory.
·
Purely Object-Oriented - It refers to everything
as an object, including numbers and strings.
·
Cross-platform Compatibility - Python can be
easily installed on Windows, macOS, and various Linux distributions, allowing
developers to create software that runs across different operating systems.
·
Rich Standard Library - Python comes with several
standard libraries that provide ready-to-use modules and functions for various
tasks, ranging from web development and data manipulation to machine learning
and networking.
·
Open Source - Python is an open-source,
cost-free programming language. It is utilized in several sectors and
disciplines as a result.
1.2
Data Types and Type Conversion
In Python, there are two kinds of type
conversion, these are -
1. Explicit Type
Conversion-The programmer must perform this task manually.
2. Implicit Type Conversion-By
the Python program automatically.
Implicit Type
Conversion:
Implicit
character data conversion is used in Python when a data type conversion occurs,
whether during compilation or runtime. We do not need to manually change the
file format into some other data type because Python performs the implicit
character data conversion. Without user input, the Programming language
automatically changes one data type to another in an implicit shift of data
types.
Program code 1: a = 15 print("Data type of a:",type(a)) b = 7.6 print("Data type of b:",type(b)) c = a + b print("The value of c:", c) print("Data type of c:",type(c)) d = "Priya" print("Data type of d:",type(d)) Output: Data type of a:
<class 'int'> Data type of b:
<class 'float'> The value of c:
22.6 Data type of c:
<class 'float'> Data type of d:
<class 'str'> Program code 2: x = input() print("Data type of x:",type(x)) y = int(input()) print("Data type of y:",type(y)) z = float(input()) print("Data type of z:",type(z)) Output: riya Data type of x:
<class 'str'> 23 Data type of y:
<class 'int'> 0.5 Data type of z:
<class 'float'> Explanation: Explicit Type
Conversion: Explicit type
conversion, commonly referred to as type casting, now steps in to save the
day. Using built-in Language functions like str() to convert to string form
and int() to convert to integer type, a programmer can explicitly change the
data form of an object by changing it manually. The user can
explicitly alter the data type in Python's Explicit Type Conversion according
to their needs. Since we are compelled to change an expression into a certain
data type when doing express type conversion, there is chance of data loss.
Here are several examples of explicit type conversion. Program 3: a = "10010" b = int(a,2) print ("following the conversion to integer base 2: ", end="") print (r) d = float(a) print ("After converting to float : ", end="") print (d) Output: following the
conversion to integer base 2: 18 After
converting to float : 1010.0 The ord()
method turns a character into an integer. The hex()
method turns an integer into a hexadecimal string. The oct()
method turns an integer into an octal string. Program 4: a = '4' b = ord(a) print ("After converting character into integer : ",end="") print (b) b = hex(56) print ("After converting 56 to hexadecimal string : ",end="") print (b) b = oct(56) print ("After converting 56 into octal string : ",end="") print (b) Output: After
converting the character into integer : 52 After
converting the 56 to hexadecimal string : 0x38 After
converting the 56 into octal string : 0o70 The tuple()
method is used to transform data into a tuple. The set()
function, which converts a type to a set, returns the set. The list()
function transforms any data type into a list type. |
1.3
Comments
In Python, comments are used to explain the
code and make it easier to understand. Comments are ignored by the Python
interpreter, so they do not affect the execution of the program. Python
supports both single-line and multi-line comments.
Single-line comments
A single-line comment starts with the hash
(#) symbol. Everything after the # on that line is considered a comment.
# This is a single-line comment
print("Hello, World!") # This is an inline comment
Multi-line comments
Python doesn't
have a specific syntax for multi-line comments like some other programming
languages. However, multi-line comments can be created by using a series of
single-line comments or by using triple quotes (''' or """) as a
workaround. The triple quotes are actually for multi-line strings, but they can
also serve as multi-line comments when not assigned to any variable.
# This is a comment
# that spans multiple lines
'''
This is another way
to write a multi-line comment
'''
"""
And yet another way
to write multi-line comments
"""
1.4 Variables,
Constants, Operators and Performing Calculations
Python
Variables:
A
variable is the name given to a memory location. A value-holding Python
variable is also known as an identifier.
Variable
names must begin with a letter or an underscore, but they can be a group of
both letters and digits.
The
name of the variable should be written in lowercase. Both Rahul and rahul are
distinct variables.
Identifier Naming:
Identifiers
are things like variables. An Identifier is utilized to recognize the literals
utilized in the program. The standards to name an identifier are given
underneath.
·
The variable's first character must
be an underscore or alphabet (_).
·
Every one of the characters with
the exception of the main person might be a letter set of lower-case(a-z),
capitalized (A-Z), highlight, or digit (0-9).
·
White space and special characters
(!, @, #, %, etc.) are not allowed in the identifier name. ^, &, *).
·
Identifier name should not be like
any watchword characterized in the language.
·
Names of identifiers are
case-sensitive; for instance, my name, and MyName isn't something very similar.
·
Examples of valid identifiers:
a123, _n, n_9, etc.
·
Examples of invalid identifiers:
1a, n%4, n 9, etc.
Constant:
Arithmetic
also has the idea of constants. This term refers to a value or amount that
never adjusts. In programming, a steady is a name associated with a value that
does not change during software execution. A programming regular, like a
variable, consists of a name and a corresponding value. The name clearly
describes the contents of the constant. The value is a concrete expression of
the constant itself. Like variables, the value assigned to a particular
constant can be any data type. So, you can define integer constants, floating
factor constants, character constants, string constants, and so on.
Once
a constant is defined, only one operation can be performed on it. You could
handily get entry to the steady value, but you cannot alternate it through the
years. This is different from variables whose value can be accessed and
reassigned. Use constants to represent unchanging values. Many of these values
can be found in everyday programming. For example, the rate of light, the
number of mins in an hour, the name of the undertaking's root folder, and so
forth.
Example:
1.
import constant
2.
print(constant.PI)
3.
print(constant.GRAVITY)
Output
3.14
9.8
Operators:
The operator is a symbol that performs a specific
operation between two operands, according to one definition. Operators serve as
the foundation upon which logic is constructed in a program in a particular
programming language. In every programming language, some operators perform
several tasks. Same as other languages, Python also has some operators, and
these are given below -
·
Arithmetic operators
·
Comparison operators
·
Assignment Operators
·
Logical Operators
·
Bitwise Operators
·
Membership Operators
·
Identity Operators
Arithmetic Operators:
Arithmetic
operators used between two operands for a particular operation. There are many
arithmetic operators. It includes the exponent (**) operator as well as the +
(addition), - (subtraction), * (multiplication), / (divide), % (reminder), and
// (floor division) operators.
Program
Code:
- a = 32 # Initialize the value of a b = 6 # Initialize the value of b print('Addition of two numbers:',a+b) print('Subtraction of two numbers:',a-b) print('Multiplication of two numbers:',a*b) print('Division of two numbers:',a/b) print('Reminder of two numbers:',a%b) print('Exponent of two numbers:',a**b) print('Floor division of two numbers:',a//b) Output: Addition of two numbers: 38 Subtraction of two numbers: 26 Multiplication of two numbers:
192 Division of two numbers:
5.333333333333333 Reminder of two numbers: 2 Exponent of two numbers:
1073741824 Floor division of two numbers: 5 Comparison operator : Comparison operators mainly use for comparison
purposes. Comparison operators compare the values of the two operands and
return a true or false Boolean value in accordance. The example of comparison
operators are ==, !=, <=, >=, >, <. In the below table, we
explain the works of the operators. Program Code: Now we give code examples of Comparison operators in
Python. The code is given below - a = 32 # Initialize the value of a b = 6 # Initialize the value of b print('Two numbers are equal or not:',a==b) print('Two numbers are not equal or not:',a!=b) print('a is less than or equal to b:',a<=b) print('a is greater than or equal to b:',a>=b) print('a is greater b:',a>b) print('a is less than b:',a<b) Output: Two numbers are equal or not:
False Two numbers are not equal or not:
True a is less than or equal to b: False a is greater than or equal to b: True a is greater b: True a is less than b: False Assignment Operators: Using the assignment operators, the right
expression's value is assigned to the left operand. There are some examples
of assignment operators like =, +=, -=, *=, %=, **=, //=. In the below table,
we explain the works of the operators.
Program Code: Now we give code examples of Assignment operators in
Python. The code is given below - 1.
a = 32 # Initialize the value of a 2.
b = 6 # Initialize the value of b 3.
print('a=b:', a==b) 4.
print('a+=b:', a+b) 5.
print('a-=b:', a-b) 6.
print('a*=b:', a*b) 7.
print('a%=b:', a%b) 8.
print('a**=b:', a**b) 9.
print('a//=b:', a//b) Output: a=b: False a+=b: 38 a-=b: 26 a*=b: 192 a%=b: 2 a**=b: 1073741824 a//=b: 5 Bitwise Operators: The two operands' values are processed bit by bit by
the bitwise operators. The examples of Bitwise operators are bitwise OR (|),
bitwise AND (&), bitwise XOR (^), negation (~), Left shift (<<),
and Right shift (>>). Consider the case below. Program Code: a = 5 # initialize the value of a b = 6 # initialize the value of b print('a&b:', a&b) print('a|b:', a|b) print('a^b:', a^b) print('~a:', ~a) print('a<<b:', a<<b) print('a>>b:', a>>b) Output: a&b: 4 a|b: 7 a^b: 3 ~a: -6 a<>b: 0 Logical Operators: The assessment of expressions to make decisions
typically uses logical operators. The examples of logical operators are and,
or, and not. In the case of logical AND, if the first one is 0, it does not
depend upon the second one. In the case of logical OR, if the first one is 1,
it does not depend on the second one. Python supports the following logical
operators. In the below table, we explain the works of the logical operators. Program Code: a = 5 # initialize the value of a print(Is this statement true?:',a > 3 and a < 5) print('Any one statement is true?:',a > 3 or a < 5) print('Each statement is true then return False and vice-versa:',(not(a > 3 and a < 5))) Output: Is this statement true?: False Any one statement is true?: True Each statement is true then return False and
vice-versa: True Membership Operators The membership of a value inside a Python data
structure can be verified using Python membership operators. The result is
true if the value is in the data structure; otherwise, it returns false. Program Code: x = ["Rose", "Lotus"] print(' Is value Present?', "Rose" in x) print(' Is value not Present?', "Riya" not in x) Output: Is value Present? True Is value not Present? True Identity Operators:
Program Code: a = ["Rose", "Lotus"] b = ["Rose", "Lotus"] c = a print(a is c) print(a is not c) print(a is b) print(a is not b) print(a == b) print(a != b) Output: True False False True True False Reading Input
from Keyboard: Taking input is a way of
interact with users, or get data to provide some result. Python provides two built-in methods to
read the data from the keyboard. These methods are given below. ·
input(prompt) ·
raw_input(prompt) input(): The input function is used in all latest version of the Python. It
takes the input from the user and then evaluates the expression. The Python interpreter
automatically identifies the whether a user input a string, a number, or a
list. Let's understand the following example. Example - 1. # Python program showing 2. # a use of input() 3. 4. name = input("Enter your name: ") 5. print(name) Output: Enter your name: Devansh Devansh Example - 2 1. # Python program showing 2. # a use of input() 3. name = input("Enter your name: ") # String Input 4. age = int(input("Enter your age: ")) # Integer Input 5. marks = float(input("Enter your marks: ")) # Float Input 6. print("The name is:", name) 7. print("The age is:", age) 8. print("The marks is:", marks) Output: Enter your name: Johnson Enter your age: 21 Enter your marks: 89 The name is: Johnson The age is 21 The marks is: 89.0
|
Print function, Displaying Formatted
Output with F- strings:
Print function():
Python print() function prints the given object on the
screen or other standard output devices.
Signature
print(object(s), sep=separator, end=end, file=file, flush=flush)
Parameters
object(s):
It is an object to be printed. The Symbol * indicates that there may be more
than one object.
sep='separator'
(optional): The objects are separated by sep. The default value
of sep is ' '.
end='end'
(optional): it determines which object should be print at last.
file
(optional): - The file must be an object with write(string)
method. If it is omitted, sys.stdout will be used which prints objects on the
screen.
flush
(optional): If True, the stream is forcibly flushed. The default
value of flush is False.
Return
It
does not return any value.
Example
1:
print("Python is programming language.")
x = 7
# Two objects passed
print("x =", x)
y = x
# Three objects passed
print('x =', x, '= y')
Output:
Python
is programming language.
x
= 7
x
= 7 = y
Example 2:
x = 7
print("x =", x, sep='00000', end='\n\n\n')
print("x =", x, sep='0', end='')
Output:
a
=000007
a
=07
Displaying Formatted Output with F- strings:
The f-string is the best way to format the string. The
string's formatting style makes the string more readable, more concise, and
less prone to error. It is also faster than the other.
Example
-
1.
# Python3 program introducing f-string
2.
val = 'Geeks'
3.
print(f"{val}for{val} is a portal for {val}.")
4.
name = 'Tushar'
5.
age = 23
6.
print(f"Hello, My name is {name} and I'm {age} years old.")
Output:
Hello,
My name is Tushar and I'm 28 years old.
Example - first_name = "Steve" last_name = "Rogers" age = 70 profession = "Superhero" group = "Marvel? print(""Hello, %s %s. Your age is %s. You are a %s. You were a member of %s." %(first_name, last_name, age, profession)") Output: Hello, Steve Rogers. Your age is 70. You are a
Superhero. You were a member of Marvel. |
No comments:
Post a Comment