Python - Unit I
Python - Unit I
BASICS : Python – Variables – Executing Python from the Command Line – Editing Python Files –
Python Reserved Words – Basic Syntax-Comments – Standard Data Types – Relational
Operators
– Logical Operators – Bit Wise Operators – Simple Input and Output.
Introduction to Python
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
Python is easy to learn yet powerful and versatile scripting language, which makes it attractive
for Application Development.
Python's syntax and dynamic typing with its interpreted nature make it an ideal language for
scripting and rapid application development.
We don't need to use data types to declare variable because it is dynamically typed so we can
write a=10 to assign an integer value in an integer variable.
Python makes the development and debugging fast because there is no compilation step
included in Python development, and edit-test-debug cycle is very fast.
Variables
Variable is a name that is used to refer to memory location. Python variable is also known as
an identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a infer language and
smart enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin with a
letter or an underscore.
It is recommended to use lowercase letters for the variable name. Rahul and rahul both are
two different variables.
Var = "SKACAS"
print(Var)
Output:
SKACAS
Local variables are the ones that are defined and declared inside a function. We can not call
this variable outside the function.
Example
def f():
s = "Welcome SKACAS"
print(s)
f()
Output:
Welcome SKACAS
Global variables are the ones that are defined and declared outside a function, and we need
to use them inside a function.
Example :
def f():
print(s)
# Global scope
s = "I love SKACAS"
f()
Output:
I love SKACAS
print('Hello World!')
To run a Python script store in a ‘.py’ file in command line, we have to write ‘python’ keyword
before the file name in the command prompt.
python hello.py
Output:
1. Download a CPython interpreter. Press the Download Python 3.6.2 button to save
one of the more updated interpreters to Windows.
2. Open the Win + X menu by pressing the Win key + X hotkey.
3. Select Command Prompt (Admin) to open the CP’s window.
4. Open the folder that includes your Python script in the Command Prompt by
entering ‘Cd’ followed by the path of the file.
5. Next, enter the full path of the CPython interpreter followed by the full location of the
PY file in the Command Prompt, which must include the Python interpreter exe and PY
file title. For example, you might enter something like this: C:Python27python.exe
C:User FolderPY Files SubfolderPy file title.PY
6. Press Enter to open and run the PY script.
Reserved Keywords
Python has a set of keywords that are reserved words that cannot be used as variable names,
function names, or any other identifiers:
Basic Syntax
If you’ve been working in other programming languages such as Java, C#, or C/C++, you
know that these languages use semicolons (;) to separate the statements.
However, Python uses whitespace and indentation to construct the code
structure. The following shows a snippet of Python code:
# define main function to print out something
def main():
i=1
The meaning of the code isn’t important to you now. Please pay attention to the code
structure instead.
At the end of each line, you don’t see any semicolon to terminate the statement. And the code
uses indentation to format the code.
By using indentation and whitespace to organize the code, Python code gains the following
advantages:
● First, you’ll never miss the beginning or ending code of a block like in other
programming languages such as Java or C#.
● Second, the coding style is essentially uniform. If you have to maintain another
developer’s code, that code looks the same as yours.
● Third, the code is more readable and clear in comparison with other programming
languages.
Comments
The comments are as important as the code because they describe why a piece of code
was written.
When the Python interpreter executes the code, it ignores the comments.
In Python, a single-line comment begins with a hash (#) symbol followed by the comment.
For example:
Continuation of statements
Python uses a newline character to separate statements. It places each statement on one
line. However, a long statement can span multiple lines by using the backslash (\) character.
The following example illustrates how to use the backslash (\) character to continue a
statement in the second line:
\ (c == True):
print("Continuation of statements")
relational operator is used to compare two values. Based on the operator and values, the
operator returns either True or False.
== Equal to x == y Returns True if x and y have same value, else returns False.
> Greater than x>y Returns True if value of x is greater than value of y, else
returns False.
< Less than x<y Returns True if value of x is less than value of y, else returns
False.
!= Not equal to x != y Returns True if x and y do not have same value, else returns
False.
>= Greater than x >= y Returns True if value of x is greater than or equal to value
or equal to of y, else returns False. Equivalent to ( x>y or x==y )
<= Less than or x <= y Returns True if value of x is less than or equal to value of y,
equal to else returns False. Equivalent to ( x>y or x==y )
An Example Program Using Relational Operators
Let us consider two variables a & b of values 10 and 20 to understand relational operations
better.
a, b = 10, 20
print(a != b) # since both the values are not equal, the output of this print statement is True print(a
> b) # the value 10 is less than 20, hence the output of this print statement is False print(a < b) #
since the value 10 is less than 20, the output of this print statement is True print(a >= b) # Since
the value 10 is less than 20, the output of this print statement is False
print(a <= b) # Since the value 10 is less than 20, the output of this print statement is True Output:
FalseTrueFalseTrueFalseTrue
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
Operator Description
& Binary AND TThe operator sends the bit present in both operands to the output.
^ Binary XOR TIt is copied if the bit is set inside one argument but not both.
~ Binary Ones TIt has the function of 'flipping' bits and is unary.
Complement
<< Binary Left TThe left operand's value is moved to its left by the number of bits specified in the
Shift right argument.
>> Binary Right The quantity of bits provided by the right parameter advances the position of the
Shift left operand.
Examples
x = 10
y=4
# Bitwise AND operation
print("x & y =", x & y)
Output: x & y = 0
Simple Input and Output
input() Function
Python input() function is used to get input from the user. It prompts for the user input and reads
a line. After reading data, it converts it into a string and returns that. It throws an error EOFError
if EOF is read.
Signature
input ([prompt])
Parameters
prompt: It is a string message which prompts for the user
input. Return
It returns user input after converting into a string.
Let's see some examples of input() function to understand it's
functionality. Example
III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 12
Example
# Python input() function example
# Calling function
val = input("Enter a value:
") # Displaying result
print("You entered:",val)
Output:
Enter a value:
45 You entered:
45
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
print("Python is programming language.")
x=7
# Two objects passed
III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 13
print("x =", x)