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

Python Note With Code

This document discusses various Python concepts including: 1. Importing modules like numpy and math, taking user input, and using functions like degrees(), cos(), radians() from the math module. 2. Exploring string operations like indexing, slicing, upper(), lower(), split(), strip(), and length. 3. Introducing lists, tuples, sets, and dictionaries - their usage and common operations. 4. Covering operators, data type casting, number systems, and bitwise operations in Python.

Uploaded by

Zobahaa Horunku
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
52 views19 pages

Python Note With Code

This document discusses various Python concepts including: 1. Importing modules like numpy and math, taking user input, and using functions like degrees(), cos(), radians() from the math module. 2. Exploring string operations like indexing, slicing, upper(), lower(), split(), strip(), and length. 3. Introducing lists, tuples, sets, and dictionaries - their usage and common operations. 4. Covering operators, data type casting, number systems, and bitwise operations in Python.

Uploaded by

Zobahaa Horunku
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 19

import numpy

print('Numpy :{}'.format(numpy.__version__))

import math

x=float(input("Please Enter the number:"))

print(f'The Degree of {x} is:',math.degrees(x)) # using single quote with {x} is used to display entered
values

print(f’The cosine value of {x} is:’,math.cos(x))

math.radians(x)//prints radians

#string in python it is mutable

name="Youtube" #string in python

print(name)

print(len(name)) # prints the length of string "Youtube"=> 7

print(name[0])#prints the first character 'Y'

print(name[0:]) # prints all characters including index 0

print(name[-1]) #prints the last character 'e'

print(name[0:6]) #prints all characters starting from index 0 to index 5

# NB: it excludes the index 6. output='Youtub'

print(name[:6]) # prints all characters starting from index 0 to index 5.

# output='Youtub' which is equal to print(name[-7:-1])

print(name[-7:-1])

#print(name[9]) erro will be happen because it is out of bound

print(name[3:10]) #prints all characters starting from index 3 to end index 7 with excluding others.

print(name.upper()) #prints all characters in upper case

print(name.lower()) #prints all characters in lower case

sentence="I want to be a good programmer in python"

print(sentence.split()) #splits the sentence in to each word

sentence=" I want to be a good programmer in python "


print(sentence) # the sentence will be displayed with white spaces in both end sides.

print(sentence.strip()) # removes the white space from statring end and last end.

print(len(sentence))

#Lists in Python used too store different data types and it is mutable eg list=[3.2,'Dere',4]

list1=[1,2,3]

print(list1) # print(list1[0:]) prints all elements of list [1,2,3]

print(list1[0]) # prints the index 0 value => 1

print(list1[0:2]) #prints values starting from index 0 to index 1 that mean it excludes the value of index 2

list2=['Dere','Hewi','Kuku']

list3=[list1,list2] # two different lists#

print(list3) #[[1, 2, 3], ['Dere', 'Hewi', 'Kuku']]

print(list3[0]) #[1, 2, 3] because it assigns index 0 to list1 elements and index 1 to list2 elements#

#NB: You can't use the following methods the same time with print() method.Use them diffirently

list1.append(4) # it appends the number 4 at the end of the list NB: you can append only one element at
a time

print(list1)

list1.insert(1,5) # inserts the new single value between lists elements and it takes two parameters those
refer index and its value

print(list1) # output:[1, 5, 2, 3, 4]

list1.remove(4) #it removes the element 4 from the list NB: It takes element to be removed but not index

print(list1) #output:[1, 5, 2, 3]

list1.pop(1) # it takes index but not element. Here it removes the index 1 element which is 5
print(list1) # output:[1, 2, 3]

list1.pop() # If you did not provide the index number, then it pops the element from the end as stack does
which is 3 will be poped

print(list1) #[1, 2]

del list2[1:] # del method used to remove many elements from the list. You have to provide index
numbers.Here it removes all elements startrting from index 1.

print(list2) #output: ['Dere']

list1.extend([6,7,8,9]) # used to add many elements to the list. Accepts only elements to be added in to the
list rear part but not indexes

print(list1) #output:[1, 2, 6, 7, 8, 9]

list1.sort() # sorts the elements in correct order

print(list1)

print(min(list1)) # prints minimum value from the list

print(max(list1)) # prints maximum value from the list

print(sum(list1)) #prints total sum

#Tuple in python=> Immutable. We use bracket===>()

tup=(1,3,6,2)

list1[1]=3 # it is possible to change the list value but in tuple changing is impossible

print(list1)

print(tup) #output: (1, 3, 6, 2)

print(tup[0])

print(tup[1:4])
# tup[1]=3 => impossible because it is immutable

print(len(tup))# possible

#Set in Python=> It is a collection of unique element and it uses curly bracket {}. It has no
sequence(indexing) like others

set1={3,6,1,8,9}

print(set1)

set1={98,14,8,3,7,98}

print(set1)

#in set using index is not supported like print(set1[1])

#Dictionary or Mapping in python=====> uses curly barces==> {}. It has no Index value but we can
provide unique key values as index.

dict1={'Dereje':'HP','Moges':'Toshiba','Temesgen':'Dell'} #index are keys, Use methods .keys()==> to


display keys, .values()===> to display values

print(dict1.keys()) #output:dict_keys(['Dereje', 'Moges', 'Temesgen'])

print(dict1.values()) #output:dict_values(['HP', 'Toshiba', 'Dell'])

print(dict1['Dereje'])#output: HP, we can use keys with square barcket as index

print(dict1.get('Dereje')) #output:HP, we can use .get(' ') method with bracket

#How to display the address of a variable=====> By using built-in method called id()

#NB:One or more variables can point the same value in the memory with the same address content.

x=3

print(x)

print(id(x)) #output:140726574126816 # id() is a pyhton built-in method that displays the address of a
variable.

y=x #Here the same value or 3 is assigned for both x and y;

print(y)
print(id(y)) # output:140726574126816

# x and y pointing the same value 3 and they have the same address

# This increases the memory efficiency in python

# One or more variables can point the same value in the memory with the same address content

#Data Type Casting in Python

# Data types=> none,numeric(int, float,complex and bool),string,tuple,list,set, range and


mapping(Dictionary)

#In python we don't have char type but we can write the string as char!

# none means a variable does not assined any value;which is the same with null in other programming
languages.

py=3

print(type(py))#<class 'int'>

print(py)#3

pyf=float(py)

print(type(pyf))#<class 'float'>

print(pyf)#3.0

#complex number can written as a+bj in python

complex1=3+2j

print(complex1)# (3+2j)

print(type(complex1))#<class 'complex'>

a=4

b=2

print(complex(a,b))#(4+2j) #it converts two integer(float) numbers in to complex number. Vice versa is
may not true
bool1=True # bool==> True has integer value 1 and False has integer value 0. We can convert boolean
value in to integer

print(bool1)

print(int(bool1))#output:1

print(range(10)) #output:range(0, 10)

print(type(range(10)))# displays type of a range <class 'range'>

print(list(range(10))) #output:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],prints the range values by assigning it to the list

#what about if we want to display all odd numbers starting from 3 to 25.

print(list(range(3,26,2))) #Here number 3 is the starting odd number, Number 25 is the last odd number to
be displayed and number 2 is the increamental value.

# Operators in python======> Arithmetic,Assignment,Relational,Logical and Unary

# Arithematic (+,-,*,/) ======> especial operators(x//y==> used to retun only integer value)

# =========================(x**y==> used to perform exponential operation)

val1=10 #assining the value to val1

val2=2

print("Addition:",val1+val2)# we can not write as print("Addition:"+(val1+val2) beacues the


concatenation of string with integer is not possible

#but we can write as print("Addition:"+str(val1+val2)), which converts integer value in


to string and concatenates them.

print("Subtraction:",val1+val2)

print("Division:",val1/val2) # output:5.0,prints float value. if we want to display integer value, we can use
as val1//val2

print("Division:",val1//val2)#output:5,prints integer value

print("Multiplication:",val1*val2)

print("Power(val1,val2):",val1**val2)# output: 100,prints power(exponential value)


#How to Assign the value? The concept is the same as other programming

# val1=3, val1+=2=====> val1=val1+2,val1*=2,val1-=2,val1/=2

#a,b=6,2 ===> In python assigning variable with values in a single line is possible by using comma.

#Unary operator(-),used to negate a number

x=7

print(x)

x=-x

print(x)

# Relational Operator ===> (>,<,>=,<=,==,!=)

a,b=6,2

print(a<b)#outpu:False

#Logical Operators ===> (And,or, Not)

x,y=5,4

x<8 and y<3 #output:False

x<8 and y>3 #output:True

x<8 or y<3 #output:True

bool1=False

print(not bool1)# it reverses the output

bool1=True

print(not bool1)

#Number System Conversion

#1. Decimal to Binary by using bin()


print(bin(10)) #output: 0b1010 ===> the 0b(zero with alphabet b) tells us the number is binary

#2. Binary to Decimal

print(0b1010) # output: 10 ====> mean that we have provided binary number and the compiler displays
its decimal equivalent number

#3. Decimal to Octal by using oct()

print(oct(10)) # output:0o12 ===>the 0o(zero with alphabet o) tells us the number is octal

#4. Octal to Decimal

print(0o12) #output: 10

#5. Decimal to Hexadecimal by using hex()

print(hex(10)) #output:0xa ===> the 0xa(zero with x) tells the number is hexadecimal. NB: in
hexadecimal the number 10 is refered by a.

#6. Hexadecimal to Decimal

print(0xa) #output:10

#Bitwise Operators ===> works with binary number


===>types(complement(~),And(&),or(|),xor(^),leftshift(<<),rightshift(>>))

#1. complement(~)

#It first converts the given decimal numbers in to 8 digit binary numbers and then performs 1's
complement===>output

# Note:We don't store a negative numbers in the computer but we store positive numbers. To store
negative numbers, we have to convert them to the positive number

#by using 2's complement ===>(2's complement=1's complement + 1)

print(~10) #Here first it converts decimal 10 to 8 digit binary and then performs 1's complement. You will
get 11110101

#output:-11, Take postive 11, convert it in to 8 digit binary and then again convert it in to 2's
complement. You will get also 11110101

#2. Bitwise And===> &, which is a little bit different from Logical And(used for comparson)

print (5&6) #output:4, How?, Convert each decimal number in to 8 digit binary and perform AND
GATE(AND Truth Table).Finally, it prints binary equivalent decimal num.
print(5|6) #output:7, The operation is the same to above but it performs OR GATE(OR Truth Table)
operation

#2. Bitwise XOR===> ^, It provides output 1,if both values have different binary number i.e
(1^0=1,0^1=1,0^0=0,1^1=0)

print(5^6)#output:3, The operation is the same to above bitwise operators but it performs XOR
GATE(XOR Truth Table) operation.Finally, it prints binary equivalent decimal num.

#2. Bitwise leftshift==> <<, First convert the given decimal number in to 4 digit binary and then add extra
zeros' to the right side.Finally, find its equivalent decimal num.

print(5<<2) # convert 5 in to 4 digit binary and add to it 2 extra zeros' to the right side. Then convert it in
to equivalent dec num.

# output:20, 5(0101),after adding two zeros'==>(010100),The equivalent decimal number is(20)

#3. Bitwise rightshift==> >>, First convert the given decimal number in to 4 digit binary and then remove
digits from right side.Finally, find its equivalent decimal num.

print(5>>2)# output:1, 5(0101),after removing 2 bits from right side, we will get(01),The equivalent
decimal num=1.

#Mathematical Functions

#To use mathematical methods, you have to import the 'math' module

import math

#if you want to import a specific methods, you can write as

#from math import sqrt,pow

x=math.sqrt(49)

print(x)

print(math.floor(2.65)) # it always changes to lower integer

print(math.ceil(2.65)) #it always changes to upper integer


print(math.pow(2,3)) # it performs powering or we can also use as 2**3

print(math.pi) #prints the pi constant value

print(math.e) # prints the e constant value

#Again we can import the modules by providing our name to use our time efficiently

import math as m # m is user defined variable. Here we can both of them as shown below

print(m.sqrt(25))

print(math.sqrt(25))

#if you want to import a specific methods, you can write as follows. So it is not mandatory using (math.).

from math import sqrt,pow

print(pow(2,3))

print(sqrt(25))

print("Number Pattern 1:")


for i in range(1,6):
for j in range(1,6):
print("*"," ",end="")

print()

print("Number Pattern 2:")


for i in range(1,6):
for j in range(1,6):
print(j, " ",end="")
print()
print("Number Pattern 3:")
for i in range(1,6):
for j in range(1,6):
print(i, " ",end="")
print()

print("Number Pattern 4:Using for loop:")


for i in range(5,0,-1):
for j in range(5,0,-1):
print(i, " ",end="")
print()

print("Number Pattern 4: Using While loop")


i=5

while i>=1:
j=1
while j<=5:
print(i, " ",end="")
j=j+1
print()
i=i-1
print("Number Pattern 5:")
for i in range(5,0,-1):
for j in range(5,0,-1):
print(j, " ",end="")
print()
import time as t
import calendar as cal
localtime=t.asctime(t.localtime(t.time()))
print("The Date is:",localtime)
ca=cal.month(2021,4)
print("Calendar for April:")
print(ca)

Developing a simple calculator


import tkinter as tkt

import math

root=tkt.Tk()

root.title("Calculator")

expression=""

def add(value):

global expression

expression+=value

label1.config(text=expression)

def clear(value):

global expression

expression=""

label1.config(text=expression)
def calculate():

global expression

result=""

if expression!="":

try:

result=eval(expression)

expression=str(result)

except:

result="error"

expression=""

label1.config(text=expression)

label1=tkt.Label(root,text=" ",bg="Blue",width=15)

label1.grid(row=0,column=0, columnspan=4,padx=8,pady=12)# The result of calculations will be seen on


this menu

# Lambda method is used to call the methods with braces and arguments

#Unless the lambda is not used, after 'command' the method should be written its name only.

#command is used to call methods

button1=tkt.Button(root,text="1",command=lambda: add("1"))

button1.grid(row=1,column=0)

button2=tkt.Button(root,text="2",command=lambda: add("2"))

button2.grid(row=1,column=1)

button3=tkt.Button(root,text="3",command=lambda: add("3"))

button3.grid(row=1,column=2)
button_div=tkt.Button(root,text="/",command=lambda: add("/"))

button_div.grid(row=1,column=3)

button4=tkt.Button(root,text="4",command=lambda: add("4"))

button4.grid(row=2,column=0)

button5=tkt.Button(root,text="5",command=lambda: add("5"))

button5.grid(row=2,column=1)

button6=tkt.Button(root,text="6",command=lambda: add("6"))

button6.grid(row=2,column=2)

button_mult=tkt.Button(root,text="*",command=lambda: add("*"))

button_mult.grid(row=2,column=3)

button7=tkt.Button(root,text="7",command=lambda: add("7"))

button7.grid(row=3,column=0)

button8=tkt.Button(root,text="8",command=lambda: add("8"))

button8.grid(row=3,column=1)

button9=tkt.Button(root,text="9",command=lambda: add("9"))

button9.grid(row=3,column=2)

button_sub=tkt.Button(root,text="-",command=lambda: add("-"))

button_sub.grid(row=3,column=3)
button_clear=tkt.Button(root,text="C",command=lambda: clear(" "))

button_clear.grid(row=4,column=0)

button0=tkt.Button(root,text="0",command=lambda: add("0"))

button0.grid(row=4,column=1)

button_point=tkt.Button(root,text=".",command=lambda: add("."))

button_point.grid(row=4,column=2)

button_add=tkt.Button(root,text="+",command=lambda: add("+"))

button_add.grid(row=4,column=3)

button_eqauls=tkt.Button(root,text="=", width=16,command=lambda: calculate())

button_eqauls.grid(row=5,column=0,columnspan=4)

root.mainloop()

How to find the character and its integer value?

x=98

print(chr(x))# prints b

How to find Random Number?

import random

print(random.randint(3,10)) # prints different random numbers

random1=[2,6,8,3,0]

print(random.choice(random1))

How to Convert Ferahanait to Celsius?

class Fer_to_cel:
user_input=""

def __init__(self): # act as constructor

print("This Convertes Ferahnait to celciues")

def getinput(self): # adding self as argument is mandatory for methods which are found in the class.

pass

def calculates(self):

fer=(input("Please enter temperature in Ferahanait \n"))

try:

number=float(fer)

cel=(fer-32.0)*(5.0/9.0)

print(f'The celcius value for ferahnait of {fer} is=',cel)

except:

Fer_to_cel.user_input=""

print("Please Enter the Number\n")

tempr=Fer_to_cel()

tempr.calculates()

How to create array in python?(They are mutable(changeable))


import array as ary

arr= ary.array('i',[4,6,1,9,7])

# arr referes an array name

# i referes array data type. Here it is integer

# ary referes your alias(you provided your own name)

print("New Created array=",arr)

print(f'Array value at index {2}=',arr[2])


from array import *

arr=array('i',[3,5,8,9,1])

print("Array created:",arr)

print(f'Array value at index {4}=',arr[4])

arr[4]=10

print(f'Array value after changing at index {4}=',arr)

print("The last removed element is=",arr.pop())

print("The elements of an array after removed element=",arr)

print(f'The removed element from index {2}=',arr.pop(2))

print(f'The elements of an array after removed element=',arr)print("The maximum value in


array=",max(arr)) #prints the maximum number in Array

print(f'Poped array element by using negative index {-2}=',arr.pop(-2))

print(arr)

print("The length of array is=",len(arr)) # used to find the length of an array

How to Perform file operations in Python


# r for read file

# w for write file

# x for create file

# a opens file for appending creates a file if it does not exist

# t refers a text to be in text mode

# b refers a binary mode eg image

import os

f = open('C:/Users/KUKU/Desktop/file.txt', 'r')

print(f.read())
f.close()

import os

print("The following reads the first line only")

f = open('C:/Users/KUKU/Desktop/file.txt', 'r')

print(f.readline()) # used to first line only

f.close()

print("The following reads in separate lines format by adding \n @ the end")

import os

f = open('C:/Users/KUKU/Desktop/file.txt', 'r')

print(f.readlines()) # reads in separate lines format by adding \n @ the end

f.close()

print(r"The following reads in separate lines format by adding \n")

import os

file = open('C:/Users/KUKU/Desktop/file.txt', 'r')

for line in file:

print(file.readlines())

f.close()

#writing in to the file


import os

f = open('C:/Users/KUKU/Desktop/file.txt', 'w')

f.write("This removes all previously stored info \n")

f.write(" And writes new one ")

f.close()

# how to create a file and write in to it?


import os

f=open('C:/Users/KUKU/Desktop/pythonfile.txt', 'x')

f.write(" Pythonfile-New file created! ")

f.close()

#how to delete file name?


import os

os.remove('C:/Users/KUKU/Desktop/pythonfile.txt')

print(“The file is deleted successfully”)

# how to get date of today?


import datetime

print(datetime.date,today())

How to display images in python?


import numpy

import cv2

file='E:/Camera/deree.jpg'

image1=cv2.imread(file)

image2=cv2.imshow('image',image1)

image3=cv2.resize(image2,(224,224))

print(image3)

Build a Mobile Application With the Kivy Python Framework – Real Python

Programming Guide — Kivy 2.0.0 documentation

You might also like