In Python we need not to declare datatype while declaring a variable like C or C++. We can simply just assign values in a variable. But if we want to see what type of numerical value is it holding right now, we can use type(), like this:
Python Data Type – Numeric
Python numeric data type is used to hold numeric values like;
int – holds signed integers of non-limited length.
long– holds long integers(exists in Python 2.x, deprecated in Python 3.x).
float– holds floating precision numbers and it’s accurate upto 15 decimal places.
complex– holds complex numbers.
#create a variable with integer value.
a=100
print("The type of variable having value", a, " is ", type(a))
#create a variable with float value.
b=10.2345
print("The type of variable having value", b, " is ", type(b))
#create a variable with complex value.
c=100+3j
print("The type of variable having value", c, " is ", type(c))
Python Data Type – String
The string is a sequence of characters. Python supports Unicode characters. Generally, strings are represented by either single or double quotes.
a = "string in a double quote"
b= 'string in a single quote'
print(a)
print(b)
# using ',' to concatenate the two or several strings
print(a,"concatenated with",b)
#using '+' to concate the two or several strings
print(a+" concated with "+b)
Python Data Type – List
The list is a versatile data type exclusive in Python. In a sense, it is the same as the array in C/C++. But the interesting thing about the list in Python is it can simultaneously hold different types of data. Formally list is an ordered sequence of some data written using square brackets([]) and commas(,).
#list of having only integers
a= [1,2,3,4,5,6]
print(a)
#list of having only strings
b=["hello","john","reese"]
print(b)
#list of having both integers and strings
c= ["hey","you",1,2,3,"go"]
print(c)
#index are 0 based. this will print a single character
print(c[1]) #this will print "you" in list c
Python Data Type – Tuple
Tuple is another data type which is a sequence of data similar to list. But it is immutable. That means data in a tuple is write protected. Data in a tuple is written using parenthesis and commas.
#tuple having only integer type of data.
a=(1,2,3,4)
print(a) #prints the whole tuple
#tuple having multiple type of data.
b=(“hello”, 1,2,3,”go”)
print(b) #prints the whole tuple
#index of tuples are also 0 based.
print(b[4]) #this prints a single element in a tuple, in this case “go”
Dictionary
Python Dictionary is an unordered sequence of data of key-value pair form. It is similar to the hash table type. Dictionaries are written within curly braces in the form key:value. It is very useful to retrieve data in an optimized way among a large amount of data.
#a sample dictionary variable
a = {1:"first name",2:"last name", "age":33}
#print value having key=1
print(a[1])
#print value having key=2
print(a[2])
#print value having key="age"
print(a["age"])
Python Comment
Python Comment are statements that are not part of your program. For this reason, comment statements are skipped while executing your program. Usually we use comments for making brief notes about a chunk of code. Also comments are important so that other can understand easily while reading your program. On the other hand, comments are also useful for the programmer himself. One can understand a program done a long time a ago simply from the comments of the program.
Single Line Comments
In Python for single line comments use # sign to comment out everything following it on that line.
#this is a comment
myVar = “hello comments” # a variable containing something
print(myVar) #print statement to print contents of a variable
Multiple Lines Comments
Multiple lines comments are slightly different. Simply use 3 single quotes before and after the part you want to be commented.
print(“I am in Multiple line comment line 1”)
print (“I am in Multiple line comment line 2”)
print(“I am out of Multiple line comment”)
Python Statement
Statements are logical lines we write in our code. Statements can be like below.
Assignment Statement:
myVariable1=”hello world”
myVariable2=100
myVariable3=12.23
Addition Statement:
myVariable4=myVariable2 + myVariable3
Subtraction Statement:
myVariable4=myVariable2 – myVariable3
Multiplication Statement:
myVariable4=myVariable2 * myVariable3
Division Statement:
myVariable4=myVariable2 / myVariable3
Python Input Output
I/O means Input and Output. We will learn about basic functions of python input and output.
Printing Output to the Screen
We are already familiar with the print() function. It is used to print something to the screen.
print(“Print something to the screen”)
Moreover, we can pass two or more different strings in the print function separated by either commas (,) or plus (+) signs. Like this;
print(“This is first String ” + “Followed by this string”);
#Or can be written like this also
print(“This is another String ” , “Followed by another string”);
Taking User Input
Sometimes our program may need to read keyboard inputs given by user. For that reason we will use input() function. The input() function reads one line from standard input. Or in other words input function reads from keyboard input until a line feed is given ( i.e. Pressed Enter).
#takes input from keyboard and stores in a string
str = input(“Enter your input: “);
#then we can print the string
print(str)
Python I/O – File Operations
Sometimes we need to read and write from files. For this reason there are some functions available.
File Opening
For opening a file we use open() functions. This is a built-in function in Python.
f = open(“input_file.txt”) # open “input_file.txt” file in current directory
f = open(“C:/Python34/README.txt”) # specifying full path of a file
f = open(“input_file.txt”,’r’) # open “input_file.txt” file to read purpose
f = open(“input_file”,’w’) # open “input_file.txt” file to write purpose
f = open(“input_file”,’a’) # open “input_file.txt” file to append purpose
File Closing
When we are done with a file, we need to close it. For that purpose, we will use close() function.
f = open(“input_file.txt”) # open “input_file.txt” file
#do file operation.
f.close()
Reading From a file
For reading a file, there are several functions. In this below program, we will explore those functions.
You can read a certain number of byte from the file with read() function.
f = open(“input.txt”) # open “input.txt” file
str=f.read(10) #read first 10 bytes from the file.
print(str) #print first 10 bytes from the file.
f.close()
You can read file line by line with readline() function.
f = open(“input.txt”) # open “input.txt” file
str=f.readline() #read first line from the file.
print(str) #print the first line.
str=f.readline() #read second line from the file.
print(str) #print the second line.
f.close()
You can also read all the lines at once and store the lines in a list of strings.
f = open(“input.txt”) # open “input.txt” file
str=f.readlines() #read all the lines from the file at once. and store as a list of string
print(str) #print list of all the lines.
f.close()
Writing to a file
For writing something into a file is pretty simple and similar to file read. We will use write() function.
f = open(“output.txt”,’w’) # open “output.txt” file
#write something in the file.
f.write(“this is my first line\n”)
f.write(“this is my second line\n”)
f.close()
Python Import
Whenever we want to use a package or module in our Python program, firstly we need to make it accessible. For that reason we need to import that package or module in our program.
Suppose, we have a number. we want to print it’s square root. So if we write this below program, it should work fine.
#get a variable having value 16
number=16
#square root this number.
number=sqrt(number)
print(number)
This is because, sqrt() function is under module name “math”. So if we want to use this function, we need to make this module accessible by importing the “math” module. So the correct code will be like this –
#first import math module
import math
#get a variable having value 16
number=16
#square root this number.
number=math.sqrt(number)
print(number)
Python Operators
Python Operators are the special symbols that can manipulate values of one or more operands.
Python Operator Types
Python operators can be classified into several categories.
- Arithmetic Operators
- Logical Operators
- Comparison Operators
- Bitwise Operators
- Assignment Operators
Python Arithmetic Operators
#create two variables
a=100
b=200
# addition (+) operator
print(a+b)
# subtraction (-) operator
print(a-b)
# multiplication (*) operator
print(a*b)
# division (/) operator
print(b/a)
# modulus (%) operator
print(a%b) # prints the remainder of a/b
# exponent (**) operator
print(a**b) #prints a^b
Python Comparison Operators
# create two variables
a=100
b=200
# (==) operator, checks if two operands are equal or not
print(a==b)
# (!=) operator, checks if two operands are not equal
print(a!=b)
# (>) operator, checks left operand is greater than right operand or not
print(a>b)
# (<) operator, checks left operand is less than right operand or not
print(a<b)
#(>=) operator, checks left operand is greater than or equal to right operand or not
print(a>=b)
# (<=) operator, checks left operand is less than or equal to right operand or not
print(a<=b)
Python Bitwise Operators
#create two variables
a=10 # binary 1010
b=7 # binary 0111
# Binary AND (&) operator, done binary AND operation
print(a&b)
# Binary OR (|) operator, done binary OR operation
print(a|b)
# Binary XOR (^) operator, done binary XOR operation
print(a^b)
# Binary ONEs Compliment (~) operator, done binary One's Compliment operation
print(~a)
# Binary Left Shift (<<) operator, done binary Left Shift operation
print(a<<1)
# Binary Right Shift (>>) operator, done binary Right Shift operation
print(a>>1)
Python Logical Operators
#take user input as int
a=int(input())
# logical AND operation
if a%4==0 and a%3==0:
print("divided by both 4 and 3")
# logical OR operation
if a%4==0 or a%3==0:
print("either divided by 4 or 3")
# logical NOT operation
if not(a%4==0 or a%3==0):
print("neither divided by 4 nor 3")
Python Assignment Operators
# take two variable, assign values with assignment operators
a=3
b=4
print("a: "+str(a))
print("b: "+str(b))
# it is equivalent to a=a+b
a+=b
print("a: "+str(a))
print("b: "+str(b))
# it is equivalent to a=a*b
a*=b
print("a: "+str(a))
print("b: "+str(b))
# it is equivalent to a=a/b
a/=b
print("a: "+str(a))
print("b: "+str(b))
# it is equivalent to a=a%b
a%=b
print("a: "+str(a))
print("b: "+str(b))
# it is equivalent to a=a**b ( exponent operator)
a**=b
print("a: "+str(a))
print("b: "+str(b))
# it is equivalent to a=a//b ( floor division)
a//=b
print("a: "+str(a))
print("b: "+str(b))
Discover more from CODE t!ps
Subscribe to get the latest posts sent to your email.